问题
I'm new to android studio and I have this textview which shows the data that is stored to my text file. If I click the button, it should read the data inside the text file, add integer and the sum should replace the existing data in the text file. However when I return to the activity which show's the textView with the new data in the text file, it does not change.
Here's the code for my textView
txt_stars = (TextView) findViewById(R.id.txtStars);
try {
FileInputStream fileInputStream = openFileInput("Stars.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String star;
while ((star=bufferedReader.readLine()) != null){
stringBuffer.append(star);
}
txt_stars.setText(stringBuffer.toString());
}
catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And the code for the button
Integer stars, totalStars;
public void onClick(DialogInterface dialog, int whichButton) {
try {
FileInputStream fileInputStream = openFileInput("Stars.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String star;
while ((star = bufferedReader.readLine()) != null) {
stringBuffer.append(star);
}
stars = Integer.parseInt(stringBuffer.toString());
totalStars = stars + 50;
//is this acceptable?
FileOutputStream fileOutputStream = openFileOutput("Stars.txt", MODE_PRIVATE);
fileOutputStream.write(totalStars.toString().getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent nextForm = new Intent(".MainActivity");
startActivity(nextForm);
}
And also, where can I find the created text file in my phone so that I can assure that the text file is created? I'm using Android studio 1.5.1 and running the app to my phone.
I have this in my manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Is there anything I should do to locate and create the text file?
I have been stuck here for days. Please help me. Thanks a lot!
回答1:
This might be due to a FileNotFoundException when you'd read the file in the save method. When you try to update the file and write into it, you don't separate the try/catch methods so you might have an exception at the reading part which prevents to continue the script and to update the file. Maybe this was printing in the Logcat but you haven't take a look.
So I'd suggest you to check if the file already exists and to separate the reading/writing parts.
When you first read the file to display it in TextView, just check if it's created to avoid a background exception:
File f = new File(getFilesDir().toString() + "/stars.txt");
Log.v("", "Does the file exist? " + f.exists());
if (f.exists()) {
readFile();
}
You can see here where the file should be stored (in getFilesDir()). The path is choosen by default when you use openFileInput(String), and it's:
data/data/com.package.name/files/
You have to keep in mind that you actually don't create /files folder in your code and for example, I had to create it myself to work with the above method. (This can be only my device but you'd be aware this can prevent the file to be created.)
Now, there is no big changes in your reading method and this is how it looks:
private void readFile() {
try {
FileInputStream file = openFileInput("stars.txt");
InputStreamReader inRead = new InputStreamReader(file);
BufferedReader buffReader = new BufferedReader(inRead);
StringBuffer stringBuffer = new StringBuffer();
String star;
while ((star = buffReader.readLine()) != null) {
stringBuffer.append(star);
}
inRead.close();
file.close();
txt_stars.setText(stringBuffer.toString());
} catch (Exception e) {
Log.e("ReadFile", e.toString());
}
}
Obviously, this method is called only if the previous check returns true. You have to do the same when the Button is clicked: check if it exists -> if yes, get the content, do your stuff (add, sum, etc) and write into it -> if not, just create it by writing into it.
Something as follows will work:
public void writeFile(View v) {
File f = new File(getFilesDir().toString() + "/stars.txt");
Log.v("", "Does it exist? " + f.exists());
String result = "";
if ( f.exists() ) {
try {
FileInputStream file = openFileInput("stars.txt");
InputStreamReader inRead = new InputStreamReader(file);
BufferedReader buffReader = new BufferedReader(inRead);
StringBuffer stringBuffer = new StringBuffer();
String star;
while ((star=buffReader.readLine()) != null) {
stringBuffer.append(star);
}
result = stringBuffer.toString();
inRead.close();
file.close();
} catch (Exception e) {
Log.e("WriteFile", "--- Error on reading file: "+e.toString());
}
} else {
// get the user's star or whatever
result = editRating.getText().toString();
}
Log.v("WriteFile", "--- Read file returns: " + result);
stars = Integer.parseInt(result);
totalStars = stars + 50;
try {
FileOutputStream fileOut = openFileOutput("stars.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);
outputWriter.write(String.valueOf(totalStars));
outputWriter.close();
fileOut.close();
// display file saved message
Toast.makeText(getBaseContext(), "File saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(" WriteFile", e.toString());
}
}
At this point, when you returned to the previous activity, you should be able to see the changes.
However, in order to see the file in your storage, you unfortunately must to have a rooted device, else you'll see an empty folder. Then finally, you'd avoid to restart the Activity. You should finish the editing one, this will come back to the previous one, and you just have to call readFile() in onResume() instead of onCreate(). It will update the new content into the TextView.
回答2:
Have you tried on updating textview before starting new Activity? Example:
txt_start.setText(""+totalStars);
来源:https://stackoverflow.com/questions/34709033/how-to-read-data-from-text-file-then-overwrite-it-with-new-data