用户登录并勾选“保持登录状态”复选框后,活动将进入另一个具有许多EditTexts的活动。但是,如果用户意外关闭/关闭设备,则在返回该应用程序时将检索数据,因为用户勾选了“保持登录状态”。我使用onSaveInstanceState和onRestoreInstanceState但它没有帮助。请帮帮我。
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
final EditText txt_Fname = (EditText) findViewById(R.id.txt_Fname);
final EditText txt_Mname = (EditText) findViewById(R.id.txt_Mname);
final EditText txt_Lname = (EditText) findViewById(R.id.txt_Lname);
final EditText txt_Suffix = (EditText) findViewById(R.id.txt_Suffix);
String Fname = txt_Fname.getText().toString();
String Mname = txt_Mname.getText().toString();
String Lname = txt_Lname.getText().toString();
String Suffix = txt_Suffix.getText().toString();
outState.putString("shared_fname", Fname);
outState.putString("shared_mname", Mname);
outState.putString("shared_lname", Lname);
outState.putString("shared_suffix", Suffix);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final EditText txt_Fname = (EditText) findViewById(R.id.txt_Fname);
final EditText txt_Mname = (EditText) findViewById(R.id.txt_Mname);
final EditText txt_Lname = (EditText) findViewById(R.id.txt_Lname);
final EditText txt_Suffix = (EditText) findViewById(R.id.txt_Suffix);
txt_Fname.setText(savedInstanceState.getString("shared_fname"));
txt_Mname.setText(savedInstanceState.getString("shared_mname"));
txt_Lname.setText(savedInstanceState.getString("shared_lname"));
txt_Suffix.setText(savedInstanceState.getString("shared_suffix"));
}
答案 0 :(得分:-1)
在活动之间切换和关闭应用程序时,使用SharedPreference保存数据。下面是示例方法,您可以在onCreate()和onDestroy()期间调用。
void saveText() {
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString(SAVED_TEXT, etText.getText().toString());
ed.commit();
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(SAVED_TEXT, "");
etText.setText(savedText);
Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
}