我一直在为我的某个项目挣扎。我需要保存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);
}
updateGoalTextView
在 onCreate
中调用。希望我使用的方法正确,因为如果我在手机上运行它,它根本不会保存数据并重新创建它。
任何想法如何修复?要了解我的意思的更清晰的方法,请下载我的beta应用程序:https://play.google.com/store/apps/details?id=jhpcoenen.connectlife.beams
谢谢您,所有人都回答了。查看答案并在Google上进行搜索后,我终于修复了它。
您可以很容易地使用SharedPreference
来存储TextView
或EditText
的值。如果要使用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","")
希望它能帮助您找到解决方案。谢谢。