我正在尝试以允许用户退出应用程序的方式保存和加载内部存储器,甚至关闭手机,但每当使用应用程序时仍然可以访问此String。
当我退出应用程序并重新输入时,它将不会加载我之前存储的字符串。我需要它来加载以前的字符串,即使我重新启动手机。以下是我到目前为止的情况:
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String FILENAME = "InternalString";
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
setupVariables();
}
private void setupVariables() {
// TODO Auto-generated method stub
sharedData = (EditText) findViewById(R.id.editText_SharedPrefs);
dataResults = (TextView) findViewById(R.id.textView_LoadSharedPrefs);
Button save = (Button) findViewById(R.id.button_save);
Button load = (Button) findViewById(R.id.button_load);
save.setOnClickListener(this);
load.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button_save:
String data = sharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.button_load:
String collected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
}
dataResults.setText(collected);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
答案 0 :(得分:0)
根据您使用的“字符串”类型,您应该使用SharedPreferences而不是写入文件...除非是大量数据。
getSharedPreferences(getPackageName() , MODE_PRIVATE).edit().putString("myString").commit();
这将持续通过手机动力循环。如果您卸载应用程序它会丢失(这可能是一件好事)。
以下是适用于您的所有各种数据保存可能性的Android文档...