-2

用户登录并勾选“让我登录”复选框后,活动将继续进行另一个活动,其中有许多 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"));
}
4

1 回答 1

-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();
  }
于 2013-08-05T06:08:15.900 回答