FileoutputStream / bufferreader - android

I have an equation which result is displayed in a TextView.
Then i have another TextView which act like a History. This History i want to save with a file and the file should be reloaded after the app will be killed an restarted.
Whats i dont understand is that the second TextView which is the View that i will save is displayed wierd stuff after starting the app
Thise line over and over again.
android.widget.TextView{41852c0 VFED.VCL ..... ID32,316-419,351 #7f09000a app:id/tvHistory}
My own Code:
final static String FILENAME = "marks.txt";
mNotenHistory=(TextView)findViewById(R.id.tVhistory);
mNotenHistory.setMovementMethod(new ScrollingMovementMethod());
private void loadTextfromFile()
{
File f = new File(getFilesDir(),FILENAME);
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
try {
while ((line = br.readLine()) != null)
{
mNotenHistory.setText(line+"\n"+mNotenHistory.getText());
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view)
{
[...]
mNotenHistory.setText(mNotenHistory.getText() + "\n" + string_note);
String noten_history_string = String.valueOf(mNotenHistory);
try {
FileOutputStream fo = openFileOutput(FILENAME, Context.MODE_APPEND);
fo.write(noten_history_string.getBytes());
fo.write("\n".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Here is the offending line:
String noten_history_string = String.valueOf(mNotenHistory);
Look at this definition, from the Android documentation:
public static String valueOf(Object value)
Added in API level 1
Converts the specified object to its string representation. If the object is null return the string "null", otherwise use toString() to get the string representation.
The TextView class inherits toString() from the View class. Here is its definition:
public String toString ()
Added in API level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression: getClass().getName() + '#' + Integer.toHexString(hashCode())
So this is your problem. String.valueOf(mNotenHistory) does not give you the text within the text view. Thus, you are writing something else (specifically, the line you mentioned) to your file. To obtain the text from your TextView, use the getText() method instead. This is what the line should look like:
String noten_history_string = mNotenHistory.getText();

Quick resume what i do want to a complish.
TextView A gets the result of an equation which is clear after each new calculation.
To save the result there is TextView B.
The Results should write from botton to top in TextView B so that the newest in on top.
The same time it should write the content of the TextView into a file.
After closing/killing the App and reopen it the TextView B will show all the saved data.
A Reset Button should clear all the content of the file so it will be empty.

Related

Reading a large text file with over 130000 line of text

How can i read a large text file into my Application?
This is my code but it does not work. My code must read a file called list.txt. The code worked only with a file with only 10.000 lines.
can someone helps me?
Thanks!
My code:(Worked with small files, but not with large files)
private void largefile(){
String strLine2="";
wwwdf2 = new StringBuffer();
InputStream fis2 = this.getResources().openRawResource(R.raw.list);
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));
if(fis2 != null) {
try {
LineNumberReader lnr = new LineNumberReader(br2);
String linenumber = String.valueOf(lnr);
while ((strLine2 = br2.readLine()) != null) {
wwwdf2.append(strLine2 + "\n");
}
// Toast.makeText(getApplicationContext(), linenumber, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), wwwdf2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Since you are processing a large file, you should process the data in chunks . Here your file reading is fine but then you keep adding all rows in string buffer and finally passing to Toast.makeText(). It creates a big foot-print in memory. Instead you can read 100-100 lines and call Toast.makeText() to process in chunks. One more thing, use string builder instead of string buffer go avoid unwanted overhead of synchronization. You initializing wwwdf2 variable inside the method but looks it is a instance variable which I think is not required. Declare it inside method to make it's scope shorter.

Storing multi color text using a file in android

I'm currently working on an android project which allows user to write text using different colors and store them for later use(i.e., editing or reading).
Is their any way to store a file in android with multi color text ??
NOTE: I googled out for the solution but can't find anything useful.
I'm guessing the user has to perform some action to switch color?
If so - you can use that trigger to store the text position/length when switching and save a list of text position - color.
A commenter suggested HTML, and that may be a good choice. You are welcome to try Html.fromHtml() to populate your EditText with the contents of a simple HTML-formatted file, and you are welcome to try Html.toHtml() to generate HTML from the contents of your EditText. However, historically, those methods were not written to do a good job of implementing a "round trip", meaning that the contents of the EditText may wind up changing from its starting point to what it contains after doing Html.toHtml() (to generate and save the HTML) and Html.fromHtml() (to populate the EditText with the previously-saved HTML). If they do not work, you can either fork that Html class and try to modify it as needed, or write your own code to take a Spanned object and convert it to/from HTML, by examining the spans and generating HTML tags from them.
PROBLEM SOLVED:
Code for storing a multi color text from EditText to a txt file:
protected void onDestroy() {
super.onDestroy();
boolean writing_allowed= ExternalStorageWriting.isWritingPossible();
if(writing_allowed)
{
String store= Html.toHtml(et.getEditableText());
File myExternalFile = new File(getExternalFilesDir(filepath), filename3);
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(store.getBytes());
fos.close();
} catch (Exception e) {
Toast.makeText(Notes.this, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
}
Code for reading that txt file and displaying it in EditText :
private void setNotes()
{
String myData="";
try {
File myExternalFile = new File(getExternalFilesDir(filepath), filename3);
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
Spanned htmlText = Html.fromHtml(myData);
et.setText(htmlText);
}

Opening Text Files Within ListView in Android

I am working on a simple word processing app, and I'm close to the point of being able to release it, except that I have one problem. When I click on an item in a ListView that displays the file names of all the text files the user has created with my app, I would like to open the file that corresponds with the item name, and place the text from that file inside the main EditText that the user uses to input data. However, when the item is clicked, nothing happens. Here is my code for that action.
filesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemName = filesListView.getItemAtPosition(position).toString();
FileInputStream fis;
String content = null;
try {
fis = openFileInput(itemName);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {
content += new String(input);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textEntryEditText = (EditText) findViewById(R.id.textEntryEditText);
textEntryEditText.setText(content);
}
});
Please help. Thanks!
EDIT: SOLVED, check my Answer to see what I did.
There might be a problem with the focusable of your listView items.Set the focusable to false for the editText in the ListView.
Try to get the file or path object from the Listview adapter not file name.
when using openFileInput(String) method it creates or get the file from application files folder not from that file location. so use BaseAdapter and get File object using getItem(int) method
I believe you are using any a dapter for binding data to your listView,
So in custom adapter class
if(convertView==null){
convertView.setTag(holder);
convertView.setTag(R.string.fileName, array.get(position).getfileName());
}else {
holder = (ViewHolder) convertView.getTag();
}
then on item click try to fetch file name like this
fileName = view.getTag(R.string.fileName).toString();
Never mind, I solved it. After several hours of tears, rage, and frustration, I finally solved it, lol. But thank you everyone who responded. As for anyone else who has a similar problem, here's what I did.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemName = filesListView.getItemAtPosition(position).toString();
StringBuffer fileRead = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(new File(getDir("FOLDER", Context.MODE_APPEND), itemName));
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String readString = bufferedReader.readLine();
while (readString != null) {
fileRead.append(readString);
readString = bufferedReader.readLine();
}
fileInputStream.close();
inputStreamReader.close();
bufferedReader.close();
textEntryEditText.setText(fileRead);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
My previous method of using the openFileInput was flawed, because I was trying to locate the file inside the default directory that openFileInput looks in, which is not where my file was. After, I tried referencing it directly, and found out that openFileInput does not allow this. So, I eventually tried just making a new FileInputStream, and telling it to make a new File object that uses the getDir method to reference the directory FOLDER, and the name of the file as determined by itemName. Hopefully this helps other who were struggling as I was, so that they don't have to suffer like I did. Thanks again to those who responded, even if I didn't use your advice!

Custom function which searches for tags in file always return null

I've created a custom function which should search a file for a specified tag, and return the value of it, like this:
Function call:
getSingleLineValue("tagname");
Found line in file:
<tagname>=tagvalue
Returned String:
tagvalue
Here is the code for the function:
public String getSingleLineValue(String tag) {
// The value
String value;
// If the list of passed tags contains the wanted tag
if(passedTags.contains(tag)) {
// Close the readers
close();
// RESET EVERYTHING
try {
// Re-create the FileReader
fileReader = new FileReader(file);
// Re-create the BufferedReader
bufferedReader = new BufferedReader(fileReader);
// Reset the passed tags array
passedTags.clear();
// Recall the function
value = getSingleLineValue(tag);
// Return the value
return value;
} catch(IOException e) {
// Handle the exception
e.printStackTrace();
}
} else {
try {
// The current line
String line;
// While the file has lines left
while ((line = bufferedReader.readLine()) != null) {
// If the current line contains a pair of tag marks ( < and > )
if (line.contains("<") && line.contains(">")) {
// If the line contains the tag
if(line.contains(tag)) {
// Store the parts of the tag in an array (tag and value)
String[] tagParts = line.split("=");
// Get the value
value = tagParts[1];
// Return the value
return value;
} else {
// Get the passed tag
String passedTag = line.substring(1, line.indexOf(">") - 1);
// Add the tag to the passed tags array
passedTags.add(passedTag);
}
}
}
} catch(IOException e) {
// Handle the exception
e.printStackTrace();
}
}
// If the tag wasn't found, return null
return null;
}
The object called file is a simple File object with the path to the file I want to read. It's declared in the same class.
The objects called fileReader and bufferedReader is just what it sounds like. A FileReader and a BufferedReader, declared like this (also in the same class):
private FileReader fileReader;
private BufferedReader bufferedReader;
And in the constructor of the class:
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
The problem is that this function always return null, so when I call it, the above demonstration about how I want it to work would instead look something like this:
Function call:
getSingleLineValue("tagname");
Found line in file:
Unknown (maybe this is the problem?)
Returned String:
null
The problem might be something with the line, because when I print it, I don't get any message in the console, but I don't really know what could be wrong with it, if it's the problem.
All help is greatly appreciated!
I've found out what was the problem. It wasn't the function, which actually worked fine, but it was the file's encoding.
I created a simple computer version and added the function to it, and printed all read lines, and found out that the file was read differently in the program than in Sublime Text (a text editor on the computer). A line which looked like this:
ABCDEFG
in the text editor, was read by the program like this:
A B C D E F G
So basically, it added a space between each character. I think the problem is with the file encoding, so the function works great itself.
EDIT: I solved the file encoding problem by using a FileInputStream and set it's encoding to "UTF-16LE", which was the correct encoding for my file, so the code above instead looked like this:
public String getSingleLineValue(String tag) {
// The value
String value;
// If the list of passed tags contains the wanted tag
if(passedTags.contains(tag)) {
// Close the readers
close();
// RESET EVERYTHING
try {
// Re-create the FileInputStream
fileInput = new FileInputStream(file); // <----- Changed
// Re-create the InputStreamReader
inputReader = new InputStreamReader(fileInput, "UTF-16LE"); // <----- Changed
// Re-create the BufferedReader
bufferedReader = new BufferedReader(inputReader); // <----- Changed
// Reset the passed tags array
passedTags.clear();
// Recall the function
value = getSingleLineValue(tag);
// Return the value
return value;
} catch(IOException e) {
// Handle the exception
e.printStackTrace();
}
} else {
try {
// The current line
String line;
// While the file has lines left
while ((line = bufferedReader.readLine()) != null) {
// If the current line contains a pair of tag marks ( < and > )
if (line.contains("<") && line.contains(">")) {
// If the line contains the tag
if(line.contains(tag)) {
// Store the parts of the tag in an array (tag and value)
String[] tagParts = line.split("=");
// Get the value
value = tagParts[1];
// Return the value
return value;
} else {
// Get the passed tag
String passedTag = line.substring(1, line.indexOf(">") - 1);
// Add the tag to the passed tags array
passedTags.add(passedTag);
}
}
}
} catch(IOException e) {
// Handle the exception
e.printStackTrace();
}
}
// If the tag wasn't found, return null
return null;
}

Android - Compare String with .txt file in raw folder

I want to know how to compare string value with .txt file's every line and get equal value.
I get All values from .txt file but i don't understand how to compare it.
For example
ABC
CBA
CCC
are in my .txt file,
and in my activity
String someText = "ABC";
and how to compare it with .txt file eacline.
I done below code to get .txt file values.
String result;
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.out);
byte[] b = new byte[in_s.available()];
in_s.read(b);
result = new String(b);
tx.setText(result);
} catch (Exception e) {
// e.printStackTrace();
result = "Error: can't show file.";
tx.setText(result);
}
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("out.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine = reader.readLine();
while (mLine != null) {
//process line
//mLine = reader.readLine();
if ("ABC".equals(mLine)){
Toast.makeText(this, "Yuppppiiiiii", 1000).show();
}
mLine = reader.readLine();
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
I think that your problem is because the way you read the file.
you currently read all file content into a string and this makes you difficult to compare.
Ok, now is the procedures:
You open the file (Create an InputStream, use the Assert, and then wrap it inside a BufferedReader)
You read it line by line, store value in a variable (Use readline() function of bufferreader)
You call the compare string function for this variable and your string (String.equal)
I hope you can understand it clearly. All remain task are about the Android docs.

Categories

Resources