我一直在尝试保存名为" first"的布尔值,表示自安装应用以来该活动是否第一次启动。布尔"第一"最初为true,但在活动使用一次后设置为false(即,在下一个活动开始之前,该值设置为false)。我尝试使用SharedPreferences保存此布尔值但是每当我在杀死它之后启动应用程序时,MainActivity仍会再次显示(如果"第一个"为假"则不会发生这种情况)。
我的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);
}
当我第一次使用该应用程序时(即"第一次"为真),转到下一个活动(即"第一个"在下一个活动开始前设置为false) ),完全杀死应用程序并回到它,为什么我再次从MainActivity开始?为什么不是第一个"在我的SharedPreferences文件(PREFS_NAME)中保存为false?
答案 0 :(得分:1)
你做错了。
请更好地了解how you use SharedPreferences。
我个人使用this method:
将其用于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*/
}