[英]SharedPreferences not saving
我一直在嘗試保存一個名為“ first”的布爾值,它表示自安裝該應用程序以來,該活動是否是第一次啟動。 布爾值“ first”最初為true,但在使用一次活動后將其設置為false(即,將值設置為false,就在下一個活動開始之前)。 我曾嘗試使用SharedPreferences保存此布爾值,但是每當我在殺死應用程序后啟動應用程序時,MainActivity仍然會再次顯示(如果“ first”為false,則不會發生這種情況)。
我的MainActivity.java看起來像這樣-
protected final static String INTENT_KEY = "NAME";
private static final String PREFS_NAME = "SaveStates"; //The SharedPreferences file name.
private Boolean first = true; // Signifies whether the app started for the first time.
SharedPreferences settings;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
resetParam(); // Retrieving the boolean "first".
// Start the next activity if the app has been started before.
if (!first) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
startActivity(intent);
}
setContentView(R.layout.activity_main);
}
/** Sends the name input by the user to the next activity */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_name);
String name = editText.getText().toString();
// Send name to next activity if it's not empty.
if (!("".equals(name))) {
setParam(); // SETTING AND SAVING "first" AS FALSE.
intent.putExtra(INTENT_KEY, name);
startActivity(intent);
}
}
/** Saving the Boolean "first" in the SharedPreferences PREF_NAME file */
private void setParam() {
// Saving the Boolean "first" in the SharedPreferences PREF_NAME file.
editor.clear();
editor.putBoolean("first", false);
editor.commit();
}
/** Retrieving the Boolean "first" from the SharedPreferences PREF_NAME file */
private void resetParam() {
first = settings.getBoolean("first", true);
}
當我第一次使用該應用程序時(即“ first”為真),請轉到下一個活動(即在下一個活動開始之前將“ first”設置為false),完全殺死該應用程序並返回到它,為什么我要從MainActivity重新開始嗎? 為什么“第一個”不保存為我的SharedPreferences文件(PREFS_NAME)中的?
你這樣做是錯的。
請更好地了解如何使用SharedPreferences 。
我個人使用此方法 :
使用它來保存 SharedPreferences
值:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
使用此從SharedPreferences
讀取的值:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
name = name + " Sethi"; /* Edit the value here*/
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.