Strings mixed up reading from internal storage - android

I'm using internal storage to store multiple strings entered by the user through multiples edit text.
So the layout is composed of multiples Textviews which correspond to the title of the fields, and multiples Edittexts which correspond to the fields where the user can enter his string.
When the user has finished, he presses the save button and this function is triggered :
public void save(View view) // SAVE
{
File file= null;
String name = editname.getText().toString()+"\n";
String marque = editmarque.getText().toString()+"\n";
String longueur = editlongueur.getText().toString()+"\n";
String largeur = editlargeur.getText().toString()+"\n";
String tirant = edittirant.getText().toString()+"\n";
String immatri = editImmatriculation.getText().toString()+"\n";
String port = editPort.getText().toString()+"\n";
String contact = editContact.getText().toString()+"\n";
String panne = editPanne.getText().toString()+"\n";
String poste = editPoste.getText().toString()+"\n";
String police = editPolice.getText().toString()+"\n";
String assurance = editAssurance.getText().toString();
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
fileOutputStream.write(name.getBytes());
fileOutputStream.write(marque.getBytes());
fileOutputStream.write(longueur.getBytes());
fileOutputStream.write(largeur.getBytes());
fileOutputStream.write(tirant.getBytes());
fileOutputStream.write(immatri.getBytes());
fileOutputStream.write(port.getBytes());
fileOutputStream.write(contact.getBytes());
fileOutputStream.write(panne.getBytes());
fileOutputStream.write(poste.getBytes());
fileOutputStream.write(police.getBytes());
fileOutputStream.write(assurance.getBytes());
Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
editname.setText("");
editmarque.setText("");
editlargeur.setText("");
editlongueur.setText("");
edittirant.setText("");
editImmatriculation.setText("");
editPort.setText("");
editContact.setText("");
editPanne.setText("");
editPoste.setText("");
editPolice.setText("");
editAssurance.setText("");
return;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Than, in another file I retrieve this data through another button that triggers this function :
public void load(View view)
{
try {
FileInputStream fileInputStream = openFileInput("Code.txt");
int read = -1;
StringBuffer buffer = new StringBuffer();
while((read =fileInputStream.read())!= -1){
buffer.append((char)read);
}
fileInputStream.close();
String tab[] = buffer.toString().split("\n");
String boatname = tab[0];
String marque = tab[1];
String longueur = tab[2];
String largeur = tab[3];
String tirant = tab[4];
String immatri = tab[5];
String port = tab[6];
String contact = tab[7];
String panne = tab[8];
String poste = tab[9];
String assurance = tab[10];
String police = tab[11];
getboatname.setText(boatname);
getmarque.setText(marque);
getlongueur.setText(longueur);
getlargeur.setText(largeur);
getTirantdeau.setText(tirant);
getImmatriculation.setText(immatri);
getPort.setText(port);
getContact.setText(contact);
getPanne.setText(panne);
getPoste.setText(poste);
getAssurance.setText(assurance);
getPolice.setText(police);
} catch (Exception e) {
e.printStackTrace();
}
}
So in the save function I'm splitting the entered strings with \n, and I save the file to the internal storage, and in the load function I retrieve the strings using an array and splitting with every \n and I set the text with the correct index.
What I don't understand is that the results are all mixed up, the string of the first field is displayed in the last field for example, why ?

You can Make a Single String and write it. Also, use a different separator. You can use StringBuffer for it.
StringBuffer s=new StringBuffer();
s.append(editname.getText().toString());
s.append("##########");
s.append(editmarque.getText().toString());
s.append("##########");
s.append(editlongueur.getText().toString());
s.append("##########");
s.append(editlargeur.getText().toString());
s.append("##########");
s.append(edittirant.getText().toString());
s.append("##########");
s.append(editPort.getText().toString());
s.append("##########");
s.append(editContact.getText().toString());
s.append("##########");
s.append(editPanne.getText().toString());
s.append("##########");
s.append(editPoste.getText().toString());
s.append("##########");
s.append(editPolice.getText().toString());
s.append("##########");
s.append(editAssurance.getText().toString());
s.append("##########");
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
fileOutputStream.write(s.toString().getBytes());
Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
editname.setText("");
editmarque.setText("");
editlargeur.setText("");
editlongueur.setText("");
edittirant.setText("");
editImmatriculation.setText("");
editPort.setText("");
editContact.setText("");
editPanne.setText("");
editPoste.setText("");
editPolice.setText("");
editAssurance.setText("");
return;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When you get FileInputStream split the String with this "##########" vlaue

Related

Speeding up the doinbackground() process

I'm splitting an encrypted video into 4 parts using this code
public class SplitVideoFile {
private static String result;
static ArrayList<String>update=new ArrayList<>();
public static String main(File file) {
try {
// File file = new File("C:/Documents/Despicable Me 2 - Trailer (HD) - YouTube.mp4");//File read from Source folder to Split.
if (file.exists()) {
String videoFileName = file.getName().substring(0, file.getName().lastIndexOf(".")); // Name of the videoFile without extension
// String path = Environment.getDataDirectory().getAbsolutePath().toString() + "/storage/emulated/0/Videointegrity";
String path = "/storage/emulated/0/Videointegrity";
// File myDir = new File(getFile, "folder");
//myDir.mkdir();
File splitFile = new File(path.concat("/").concat(videoFileName));//Destination folder to save.
if (!splitFile.exists()) {
splitFile.mkdirs();
Log.d("Directory Created -> ", splitFile.getAbsolutePath());
}
int i = 01;// Files count starts from 1
InputStream inputStream = new FileInputStream(file);
String videoFile = splitFile.getAbsolutePath() +"/"+ String.format("%02d", i) +"_"+ file.getName();// Location to save the files which are Split from the original file.
OutputStream outputStream = new FileOutputStream(videoFile);
Log.d("File Created Location: ", videoFile);
update.add("File Created Location: ".concat(videoFile));
int totalPartsToSplit =4 ;// Total files to split.
int splitSize = inputStream.available() / totalPartsToSplit;
int streamSize = 0;
int read = 0;
while ((read = inputStream.read()) != -1) {
if (splitSize == streamSize) {
if (i != totalPartsToSplit) {
i++;
String fileCount = String.format("%02d", i); // output will be 1 is 01, 2 is 02
videoFile = splitFile.getAbsolutePath() +"/"+ fileCount +"_"+ file.getName();
outputStream = new FileOutputStream(videoFile);
Log.d("File Created Location: ", videoFile);
streamSize = 0;
}
}
outputStream.write(read);
streamSize++;
}
inputStream.close();
outputStream.close();
Log.d("Total files Split ->", String.valueOf(totalPartsToSplit));
result="success";
} else {
System.err.println(file.getAbsolutePath() +" File Not Found.");
result="failed";
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public ArrayList<String> getUpdate()
{
return update;
}
And in my activity file i call this using async task's doinbackground method like below
protected String doInBackground(Void...arg0) {
Log.d(TAG + " DoINBackGround", "On doInBackground...");
File encvideo=new File(epath.getText().toString());
SplitVideoFile split=new SplitVideoFile();
String result=split.main(encvideo);
publishProgress(1);
return result;
}
Even though it splits the video, it takes too much of time to do the process.
How can I speed them up. As I'm showing a progress bar in preexecute method it looks like the user sees the progress bar for a long time, which I don't want.

How to read text file line by line?

My Goal is to be able to save as many high scores from my application to my text file i create using FileOutputStream. I then want to be able to read from the file and put each line into an array list item. While using InputStreamReader I am able to load all of the lines of text from the text file into the variable s. My problem now is i want to take each line from the text file and save it into an array list item. How would i accomplish this?
Example string variables for high scores:
String myStr = "Ryan 150 hard \n";
String myStr2 = "Andrew 200 Medium \n";
public void saveClick(){
try{
//String myNum = Integer.toString(life);
FileOutputStream fOut = openFileOutput("storetext.txt", Context.MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fOut);
outputWriter.write(myStr);
outputWriter.write(myStr2);
outputWriter.close();
/*OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.write(life);
out.close();*/
Toast.makeText(getApplicationContext(), "Save Successful", Toast.LENGTH_LONG).show();
}
catch(Throwable t){
Toast.makeText(getApplicationContext(), "Save Unsuccessful", Toast.LENGTH_LONG).show();
}
}
public void readFileInEditor(){
try{
FileInputStream fileIn = openFileInput("storetext.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
char [] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0){
//char to string conversion
String readString = String.copyValueOf(inputBuffer,0,charRead);
s += readString;
}
InputRead.close();
Toast.makeText(getApplicationContext(), "New Text: " + s , Toast.LENGTH_LONG).show();
//myText.setText("" + s);
try{
//life = Integer.parseInt(s);
//Toast.makeText(getApplicationContext(), "My Num: " + life , Toast.LENGTH_LONG).show();
}
catch(NumberFormatException e){
//Toast.makeText(getApplicationContext(), "Could not get number" + life , Toast.LENGTH_LONG).show();
}
}
catch(java.io.FileNotFoundException e){
//have not created it yet
}
catch(Throwable t){
Toast.makeText(getApplicationContext(), "Exception: "+t.toString(), Toast.LENGTH_LONG).show();
}
}
To make your life easier, better to use (1) BufferedReader::readline() method, or (2) Scanner::nextLine() method. And add each line to a List<String> in the for loop.
A simple example:
List<String> lines = new ArrayList<>();
String curLine = null;
BufferedReader reader = new BufferedReader(new FileReader("storetext.txt"));
while ((curLine = reader.readLine()) != null) {
lines.add(curLine);
}
Use BufferedReader to read line by line and put them in an ArrayList right away.

Check if removable sd-card is on device

I'm developing an app for the specific device. When i get external storage path it gives me the location, that is placed on internal memory. I need to find out if there is any removable sd card found on device(true,false).
Use this code to check external sdcard present or not
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent){
}else{
}
It worked for me
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}

Read HTML file from assets

I have an html file in assets, aaa.html.
I want to read the contents of html file and replace it from another string.
Is this way is right or is there any other option.
my code:
File f = new File("file:///android_asset/aaa.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
But its giving file not found, where as loading in web view loads the file.
InputStream is = getAssets().open("aaa.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
str = str.replace("old string", "new string");
If you want to load file in webview then use this
mWebView.loadUrl("file:///android_asset/myfile.html");
you want to replace content inside Html file tags so the solution class code is here..
public class CardDetail {
public static String newHtmlString = "";
// private Context context;
#SuppressWarnings("rawtypes")
public String getNewHtmlString(String htmlString, HashMap hm) {
try {
StringTokenizer st = new StringTokenizer(htmlString, "##");
CardDetail.newHtmlString = "";
while (st.hasMoreTokens()) {
String token = st.nextToken();
CardDetail.newHtmlString += token;
if (st.hasMoreTokens()) {
String token2 = st.nextToken();
if (token2.equals("NAME") || token2.equals("POSITION") || token2.equals("COMPANY") || token2.equals("PHOTOURL"))
CardDetail.newHtmlString += hm.get(token2);
if (token2.equals("SKYPE_CONTAINER1")
|| token2.equals("TWITTER_CONTAINER1")
|| token2.equals("PHONENUMBER_CONTAINER1")
|| token2.equals("EMAIL_CONTAINER1")
|| token2.equals("ADDRESS_CONTAINER1")) {
String replaceString = st.nextToken();
String tokenMiddle = (String) hm.get(st.nextToken());
if (!tokenMiddle.equals("")) {
replaceString += tokenMiddle;
CardDetail.newHtmlString += replaceString + st.nextToken();
st.nextElement();
} else {
st.nextElement();
st.nextElement();
}
}
}
}
// Log.i("convertedHTMLString", newHtmlString);
return CardDetail.newHtmlString;
// htmlString = "<img src='" + hm.get("PHOTOURL") + "' width=80 height=80>";
// return htmlString;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
public HashMap<?, ?> getProfileHashMap(JSONObject jsonObject) {
#SuppressWarnings("rawtypes")
HashMap hm = new HashMap();
jsonObject = (new JSONConverterClass()).convertJsonObjectToCardDetail(jsonObject);
try {
hm.put("EMAIL", jsonObject.getString("email"));
hm.put("NAME", jsonObject.getString("firstname") + " " + jsonObject.getString("lastname"));
hm.put("COMPANY", jsonObject.getString("company_name"));
hm.put("POSITION", jsonObject.getString("position"));
hm.put("WEBSITE", jsonObject.getString("website"));
hm.put("PHONENUMBER", jsonObject.getString("phonenumber"));
hm.put("PHOTOURL", jsonObject.getString("picture_url"));
hm.put("SKYPE", jsonObject.getString("skype_username"));
hm.put("TWITTER", jsonObject.getString("twitter_username"));
hm.put("ADDRESS", jsonObject.getString("generic_location"));
} catch (Exception e) {
e.printStackTrace();
}
return hm;
}
}
convertJsonObjectToCardDetail this class just replace string with values from Json
hope this solves your problem ....

How to write and read data into the file base on different language

Actually in my app i have an EditText box and an TextView. In this EditText box whatever i write is stored in the file. So when i open my app again the stored text is shown in the TextView. All works fine for me. But whenever i change the language in Russian, the Keyboard that appear on click of EditText box contain Russian character. Now when i follow the same process of storing and reading the text that i entered, the while reading it read some garbage value and display in TextView instead of the text that i have stored. So my questions is why this happen only when i stored the text in other Language, because in storing the text in english language it works fine. The code that i have used while storing data into the file is shown below.
Write Notes into the file and register
public void writeNotesToFile(Context c)
{
SharedPreferences preferencesWrite = c.getSharedPreferences("myPreferences", 0);
SharedPreferences.Editor editor = preferencesWrite.edit();
// write notes count into the register
editor.putInt("notesCount", m_noteCount);
editor.commit();
// write notes to the file
SimpleDateFormat sdFormater = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
File file = c.getFileStreamPath("Notes");
if (m_noteCount > 0)
{
if(!file.exists())
{
try
{
file.createNewFile();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
try
{
FileOutputStream writer = c.openFileOutput("Notes", Context.MODE_PRIVATE);
for (int i = 0; i < m_noteCount; i++)
{
String noteDate = sdFormater.format(m_arrNoteDate[i]);
writer.write(noteDate.getBytes());
writer.write(" ".getBytes());
writer.write(m_arrNoteString[i].getBytes());
writer.write("~`".getBytes());
}
writer.close();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
else
{
try
{
file.createNewFile();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
}
Read notes from the file and register
public void readNotesFromFile(Context c)
{
SharedPreferences preferencesRead = c.getSharedPreferences("myPreferences", 0);
// Reads notes count from the register
m_noteCount = preferencesRead.getInt("notesCount", 0);
// Reads notes from file
String note = "";
char nextCharacter;
int count = 0, ch;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
File file = c.getFileStreamPath("Notes");
if (m_noteCount > 0)
{
if(file.exists())
{
try
{
FileInputStream fin = c.openFileInput("Notes");
while( (ch = fin.read()) != -1)
{
nextCharacter = (char)ch;
if (nextCharacter == '~')
{
ch = fin.read();
nextCharacter = (char)ch;
if (nextCharacter == '`')
{
int i=note.indexOf(" ");
String temp = note.substring(0, i);
try
{
m_arrNoteDate[count] = formatter.parse(temp);
}
catch (Exception e)
{
// To handle dates saved before the file was written in Local.US format.
// This code can be removed after few releases and all user have migrated.
SimpleDateFormat defFormatter = new SimpleDateFormat("dd-MMM-yyyy");
m_arrNoteDate[count] = defFormatter.parse(temp);
}
m_arrNoteString[count] = note.substring(i + 1);
count++;
note = "";
}
}
else
{
note = note + nextCharacter;
}
}
}
catch (Exception e)
{
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
}
}
}
}
Updated code that solve the problem
public void writeNotesToFile(Context c)
{
SharedPreferences preferencesWrite = c.getSharedPreferences("myPreferences", 0);
SharedPreferences.Editor editor = preferencesWrite.edit();
// write notes count into the register
editor.putInt("notesCount", m_noteCount);
editor.commit();
// write notes to the file
SimpleDateFormat sdFormater = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
File file = c.getFileStreamPath("Notes");
if (m_noteCount > 0)
{
if(!file.exists())
{
try
{
file.createNewFile();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
try
{
//convert to UTF format while Writing Data
FileOutputStream fos = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(fos, "UTF8");
// FileOutputStream writer = c.openFileOutput("Notes", Context.MODE_PRIVATE);
for (int i = 0; i < m_noteCount; i++)
{
String noteDate = sdFormater.format(m_arrNoteDate[i]);
writer.write(noteDate);
writer.write(" ");
writer.write(m_arrNoteString[i]);
writer.write("~`");
}
writer.close();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
else
{
try
{
file.createNewFile();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
}
public void readNotesFromFile(Context c)
{
SharedPreferences preferencesRead = c.getSharedPreferences("myPreferences", 0);
// Reads notes count from the register
m_noteCount = preferencesRead.getInt("notesCount", 0);
// Reads notes from file
String note = "";
char nextCharacter;
int count = 0, ch;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
File file = c.getFileStreamPath("Notes");
if (m_noteCount > 0)
{
if(file.exists())
{
try
{
//convert to UTF format while Reading Data
FileInputStream fis = new FileInputStream(file);
InputStreamReader fin = new InputStreamReader(fis, "UTF8");
// FileInputStream fin = c.openFileInput("Notes");
while( (ch = fin.read()) != -1)
{
nextCharacter = (char)ch;
if (nextCharacter == '~')
{
ch = fin.read();
nextCharacter = (char)ch;
if (nextCharacter == '`')
{
int i=note.indexOf(" ");
String temp = note.substring(0, i);
try
{
m_arrNoteDate[count] = formatter.parse(temp);
}
catch (Exception e)
{
// To handle dates saved before the file was written in Local.US format.
// This code can be removed after few releases and all user have migrated.
SimpleDateFormat defFormatter = new SimpleDateFormat("dd-MMM-yyyy");
m_arrNoteDate[count] = defFormatter.parse(temp);
}
m_arrNoteString[count] = note.substring(i + 1);
count++;
note = "";
}
}
else
{
note = note + nextCharacter;
}
}
}
catch (Exception e)
{
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
}
}
}
}

Categories

Resources