我試圖保存和加載字符串到/從內部存儲的方式,允許用戶退出應用程序,甚至關閉手機,但仍然訪問此字符串每當該應用程序被使用。從Android的內部存儲加載文件
當我退出應用程序並重新輸入時,它不會加載之前存儲的字符串。我需要它來加載以前的字符串,即使我重新啓動手機。以下是我迄今爲止:
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;
}
}
歡迎堆棧溢出!我們通常喜歡這個網站上的問題是關於特定的編程問題。你的問題到底是什麼? – gobernador 2012-07-23 00:22:01
哦,親愛的 - 我忘了實際指定發生了什麼,致歉!當我退出應用程序並重新輸入時,它不會加載我以前存儲的數據。 – 2012-07-23 00:41:55