共享首选项不起作用,android?
Shared Preferences is not working, android?
下面的方法是有效的,但现在它没有将我的整数写入文件。
public void writeChpNum(int num) {
SharedPreferences prefs = context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).apply();
}
这就是我从 Main class 获得的方式:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
chapterNum = prefs.getInt("chapter", 1);
方法在这种情况下不起作用:
writeChpNum(1);
writeLastLine("0");
boolean deleted = file.delete();
boolean deleted2 = file2.delete();
boolean deleted3 = file3.delete();
boolean deleted4 = last.delete();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
在这里,我想重新启动一切并退出,所以我正在删除文件,但对于章节我只需要写“1”-chapter。然而,它并没有写。
这是因为我正在退出应用程序吗?
当您这样访问上下文对象时,其他活动将无法使用它。如果您只想将此方法写入一个 class,请尝试在方法中传递它的上下文。使方法静态,这样你就不需要创建 activity 对象。
编辑
根据您退出应用程序的新代码,您需要 commit()
而不是 apply()
参考:https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
public static void writeChpNum(Context c, int num) {
SharedPreferences prefs = c.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).commit() ;
}
下面的方法是有效的,但现在它没有将我的整数写入文件。
public void writeChpNum(int num) {
SharedPreferences prefs = context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).apply();
}
这就是我从 Main class 获得的方式:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
chapterNum = prefs.getInt("chapter", 1);
方法在这种情况下不起作用:
writeChpNum(1);
writeLastLine("0");
boolean deleted = file.delete();
boolean deleted2 = file2.delete();
boolean deleted3 = file3.delete();
boolean deleted4 = last.delete();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
在这里,我想重新启动一切并退出,所以我正在删除文件,但对于章节我只需要写“1”-chapter。然而,它并没有写。
这是因为我正在退出应用程序吗?
当您这样访问上下文对象时,其他活动将无法使用它。如果您只想将此方法写入一个 class,请尝试在方法中传递它的上下文。使方法静态,这样你就不需要创建 activity 对象。
编辑
根据您退出应用程序的新代码,您需要 commit()
而不是 apply()
参考:https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
public static void writeChpNum(Context c, int num) {
SharedPreferences prefs = c.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).commit() ;
}