在用户杀死应用程序,Android之后保存状态



我一直在为我的某个项目挣扎。我需要保存2个 TextView值,以便当用户按下返回按钮或重新启动电话并返回应用程序时,它们在那里。。该应用显示用户本人输入的"目标"的TextView。第二个TextView显示了许多"梁",这些"光束"再次输入。用户旋转屏幕时,我已经能够保留数据,但是在App被杀死后,保留数据更加困难。

public class MainActivity extends AppCompatActivity {
SharedPreferences preferences;
TextView showGoalTextView;
TextView showBeamsTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    showGoalTextView = (TextView) findViewById(R.id.textView3);
    showBeamsTextView = (TextView) findViewById(R.id.textView2);
    preferences = getSharedPreferences("userData", MODE_PRIVATE);
    updateGoalTextView();
}

updateGoalTextView()方法:

    public void updateGoalTextView() {
    String goalSave = showGoalTextView.getText().toString();
    String beamsSave = showBeamsTextView.getText().toString();
    SharedPreferences preferences = getSharedPreferences("userData", MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("goals", goalSave);
    editor.putString("beam", beamsSave);
    editor.apply();
    // get the saved string from shared preferences
    String name1 = preferences.getString("goals", "");
// set reference to the text view
    showGoalTextView = (TextView) findViewById(R.id.textView3);
// set the string from sp as text of the textview
    showGoalTextView.setText(name1);
}

updateGoalTextViewonCreate中调用。希望我使用的方法正确,因为如果我在手机上运行它,它根本不会保存数据并重新创建它。

任何想法如何修复?要了解我的意思的更清晰的方法,请下载我的beta应用程序:https://play.google.com/store/apps/details?id=jhpcoenen.connectlife.beams

谢谢您,所有人都回答了。查看答案并在Google上进行搜索后,我终于修复了它。

您可以很容易地使用SharedPreference来存储TextViewEditText的值。如果要使用AutoSave,则可以使用TextWatcher获取文本类型事件,也可以使用Onpause((和onResume((方法存储和读取值。

这是将数据存储在SharedPreferences中的示例代码。

初始化SharedPreferences-

SharedPreferences pref=getSharedPreferences("my_shared_preferences",MODE_PRIVATE);

将数据存储在SharedPreferences-

SharedPreferences.Editor editor=pref.edit();
editor.putString("key1","value 1");
editor.putString("key2","value 2");
editor.commit();

SharedPreferences读取数据 -

String var1=pref.getString("key1","")
String var2=pref.getString("key2","")

希望它能帮助您找到解决方案。谢谢。

最新更新