繁体   English   中英

SharedPreferences不保存

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM