[英]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.