我正在尝试以一种允许用户退出应用程序,甚至关闭手机,但在使用应用程序时仍可以访问此字符串的方式,将字符串保存到/从内部存储中加载。
当我退出应用程序并重新进入时,它不会加载我之前存储的字符串。即使我重新启动手机,我也需要它来加载以前的字符串。这是我到目前为止所拥有的:
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;
}
}