java [共享首选项] android的键值存储。 #android_snippet #android

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java [共享首选项] android的键值存储。 #android_snippet #android相关的知识,希望对你有一定的参考价值。

// MODE_PRIVATE means created file can only be accessed by the calling application.
// if the preference file ("file name") does not exist by the given name, file will be created.
SharedPreferences sharedPref = context.getSharedPreferences(
        "file name", Context.MODE_PRIVATE);

// Use the following if you need to use only one shared preference file for the activity.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

// Writing to it
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("score", 4);
editor.commit(); // or editor.apply()

/* 
 * apply() changes the in-memory SharedPreferences object immediately but writes the 
 * updates to disk asynchronously. Alternatively, you can use commit() to write the 
 * data to disk synchronously. But because commit() is synchronous, you should avoid 
 * calling it from your main thread because it could pause your UI rendering.
 */

// Reading from it
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
// 0 is a default value.
int highScore = sharedPref.getInt("score", 0);

以上是关于java [共享首选项] android的键值存储。 #android_snippet #android的主要内容,如果未能解决你的问题,请参考以下文章

如何使用颤振中的键删除/清除共享首选项?

SharedPreferences 存储

JavaEE 配置文件 应用首选项存储

13.1 存储选项

如何使用 Android Studio 查看共享首选项文件?

访问共享首选项以进行多部分上传时,Android 上的 Java 错误