[英]Save state after user kills app, Android
我一直在为我的一些项目而苦苦挣扎。 我需要保存2个TextView
值,以便在用户按下“后退”按钮或重新启动电话并稍后返回到应用程序时它们就在那里。.到目前为止,我已经尝试了很多方法,但是某种程度上它是行不通的。该应用程序显示带有用户自己输入的“目标”的TextView
。 第二个TextView
显示许多“光束”,用户自己再次输入。 当用户旋转屏幕时,我已经能够保留数据,但是在应用被杀死后,保留数据更加困难。
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);
}
在onCreate
调用了updateGoalTextView
get。 希望我使用的方法是正确的,因为如果我在带有AS的手机上运行它,它将不会保存数据并重新创建它。
知道如何解决吗? 要更清楚地了解我的意思,请下载我的Beta版应用程序: https : //play.google.com/store/apps/details?id=jhpcoenen.connectlife.beams
谢谢大家。 在查看答案并在GOOGLE上进行搜索后,我已将其修复。
您可以使用SharedPreference
轻松存储TextView
或EditText
值。 如果要使用自动保存,则可以使用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","")
希望它能帮助您找到解决方案。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.