我正在创建一个应用程序,您可以在其中输入日期,时间,往返地点以及跟踪里程数的任何注释。在我的AddActivity.java中,您输入信息。然后,BufferedWriter将此信息写入txt文件。在我的EditActivity.java(附件)中,文本应自动从文件中读取,然后在EditText中显示给用户。当我运行一个模拟器时,文本显示正常。当我在导出后在手机上运行它时,文本"无法检索"显示意味着try / catch块中的BufferedReader未成功运行。我在这里错过了什么?谢谢!
package com.reese.mileagelog;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class EditActivity extends Activity implements View.OnClickListener {
Button addBut;
Button editBut;
Button emailBut;
EditText editText;
String currentText;
Button delete;
public String current;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
editText=(EditText)findViewById(R.id.edit1);
delete = (Button)findViewById(R.id.delete);
delete.setOnClickListener(this);
editText.setText(getCurrentText());
Toast.makeText(getBaseContext(), getCurrentText(), Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.delete:
deleteText();
editText.setText(getCurrentText());
break;
}
}
public void deleteText(){
BufferedWriter bufferedWriter;
try {
bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MileageLog.txt")));
bufferedWriter.write("");
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getCurrentText()
{
String currentText ="Could not retrieve";
try {
BufferedReader bufferedReader;
bufferedReader = new BufferedReader(new FileReader(new
File(getFilesDir()+File.separator+"MileageLog.txt")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = bufferedReader.readLine()) != null){
builder.append(read);
}
currentText = builder.toString();
editText.setText(currentText);
bufferedReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return currentText;
}
}
答案 0 :(得分:1)
很难说没有更多信息,但我最好的猜测是你的应用程序正在安装在SD卡(外部存储设备)而不是内置设备上。
发生这种情况时,您需要一个特殊的权限来编写文件,您可以在AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
如果您宁愿避免此权限,请确保不将android:installLocation设置为preferExternal