共享首选项不起作用,android吗?

Iriskul Turduev

以下方法有效,但现在无法将我的整数写入文件中。

public void writeChpNum(int num) {
    SharedPreferences prefs = context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    prefs.edit().putInt("chapter", num).apply();
}

这是我从主班得到的:

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”章。但是,它没有写。

这是因为我要退出该应用程序吗?

乌马尔·侯赛因

像这样访问时,上下文对象在其他活动中将不可用。如果只想将此方法编写到一个类中,请尝试在方法中传递它的上下文。使方法为静态,因此您无需创建活动对象。

编辑

根据您退出应用所需的新代码,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() ;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章