变量需要保存

时间:2014-11-24 00:50:21

标签: android onrestoreinstancestate

我正在创建一个包含表单的应用程序,每当数据单击按钮从EditText中的BD加载时,但每次按下其他按钮时,其他EditText都会被清除,我试过:

@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putString("data", myVariable);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
   super.onRestoreInstanceState(savedInstanceState);
   other = savedInstanceState.getString("data");
   name.setText(other);

}

很抱歉,如果我没有解释清楚,我需要每次更改活动变量而我没有删除。有什么建议?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用Android SharedPreferences。这是Android为其应用提供的持久键值存储,旨在涵盖此类问题。这是使用它的简单方法:

SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);

// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();

...

// ..and to retrieve it..
prefs.getString("data", null);

// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't 
// yet exist.

希望这有帮助。