Android - Save key-value data(基于 SharedPreferences)
发布日期:2021-05-06 23:02:47 浏览次数:18 分类:技术文章

本文共 11774 字,大约阅读时间需要 39 分钟。

文章目录

Save key-value data

If you have a relatively small collection of key-values that you’d like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.

This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.

Note: The SharedPreferences APIs are for reading and writing key-value pairs, and you should not confuse them with the Preference APIs, which help you build a user interface for your app settings (although they also use SharedPreferences to save the user’s settings). For information about the Preference APIs, see the .

Get a handle to shared preferences

You can create a new shared preference file or access an existing one by calling one of these methods:

  • getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.
  • getPreferences() — Use this from an Activity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don’t need to supply a name.

For example, the following code accesses the shared preferences file that’s identified by the resource string R.string.preference_file_key and opens it using the private mode so the file is accessible by only your app:

Context context = getActivity();SharedPreferences sharedPref = context.getSharedPreferences(        getString(R.string.preference_file_key), Context.MODE_PRIVATE);

When naming your shared preference files, you should use a name that’s uniquely identifiable to your app. An easy way to do this is prefix the file name with your . For example: "com.example.myapp.PREFERENCE_FILE_KEY"

Alternatively, if you need just one shared preference file for your activity, you can use the getPreferences() method:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

Caution: The MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE modes have been deprecated since API level 17. Starting with Android 7.0 (API level 24), Android throws a SecurityException if you use them. If your app needs to share private files with other apps, it may use a FileProvider with the FLAG_GRANT_READ_URI_PERMISSION. For more information, also see .

If you’re using the SharedPreferences API to save app settings, you should instead use getDefaultSharedPreferences() to get the default shared preference file for your entire app. For more information, see the .

Write to shared preferences

To write to a shared preferences file, create a SharedPreferences.Editor by calling edit() on your SharedPreferences.

Note: You can edit shared preferences in a more secure way by calling the edit() method on an object instead of on a SharedPreferences object. To learn more, see the guide on how to .

Pass the keys and values you want to write with methods such as putInt() and putString(). Then call apply() or commit() to save the changes. For example:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPref.edit();editor.putInt(getString(R.string.saved_high_score_key), newHighScore);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.

Read from shared preferences

To retrieve values from a shared preferences file, call methods such as getInt() and getString(), providing the key for the value you want, and optionally a default value to return if the key isn’t present. For example:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);

准备

IDE:

Android Studio 4.1.1Build #AI-201.8743.12.41.6953283, built on November 5, 2020Runtime version: 1.8.0_242-release-1644-b01 amd64VM: OpenJDK 64-Bit Server VM by JetBrains s.r.oWindows 10 10.0

Android Virtual Devices:

Name: Pixel_2_API_28CPU/ABI: Google Play Intel Atom (x86)Path: C:\Users\86188\.android\avd\Pixel_2_API_28.avdTarget: google_apis_playstore [Google Play] (API level 28)Skin: pixel_2SD Card: 512Mfastboot.chosenSnapshotFile: runtime.network.speed: fullhw.accelerometer: yeshw.device.name: pixel_2hw.lcd.width: 1080hw.initialOrientation: Portraitimage.androidVersion.api: 28tag.id: google_apis_playstorehw.mainKeys: nohw.camera.front: emulatedavd.ini.displayname: Pixel 2 API 28hw.gpu.mode: autohw.ramSize: 1536PlayStore.enabled: truefastboot.forceColdBoot: nohw.cpu.ncore: 4hw.keyboard: yeshw.sensors.proximity: yeshw.dPad: nohw.lcd.height: 1920vm.heapSize: 256skin.dynamic: yeshw.device.manufacturer: Googlehw.gps: yeshw.audioInput: yesimage.sysdir.1: system-images\android-28\google_apis_playstore\x86\showDeviceFrame: yeshw.camera.back: virtualsceneAvdId: Pixel_2_API_28hw.lcd.density: 420hw.arc: falsehw.device.hash2: MD5:55acbc835978f326788ed66a5cd4c9a7fastboot.forceChosenSnapshotBoot: nofastboot.forceFastBoot: yeshw.trackBall: nohw.battery: yeshw.sdCard: yestag.display: Google Playruntime.network.latency: nonedisk.dataPartition.size: 6442450944hw.sensors.orientation: yesavd.ini.encoding: UTF-8hw.gpu.enabled: yes

注意:以下示例仅在安卓虚拟设备上运行测试,并没有在真实的设备上运行测试。

项目

  • 方法 getPreferences(Context.MODE_PRIVATE) 返回的对象可以用于存储 Ativity 范围的数据;
  • 方法 getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE) 返回的对象可以用于存储应用范围的数据。

效果:

在这里插入图片描述

新建项目,选择 Empty Activity,在配置项目时,Minimum SDK 选择 API 16: Android 4.1 (Jelly Bean)

新建 Empty Activity,命名 SecondaryActivity

编辑 src\main\res\layout\activity_secondary.xml 布局文件,添加如下组件:

编辑 SecondaryActivity

package com.mk;import android.content.Context;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.android.material.snackbar.Snackbar;public class SecondaryActivity extends AppCompatActivity {
private static final String TAG = "SecondaryActivity"; @Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_secondary); // 用于存储 Activity 范围的数据 SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE); ((Button) findViewById(R.id.buttonStoreForActivity)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String name = ((EditText) findViewById(R.id.editTextForActivity)).getText().toString(); SharedPreferences.Editor editor = preferences.edit(); editor.putString(MainActivity.KEY_NAME, name); editor.apply(); } }); ((Button) findViewById(R.id.buttonRetrieveForActivity)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String name = preferences.getString(MainActivity.KEY_NAME, null); Snackbar.make(v, name, Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); // 用于存储应用范围的数据 SharedPreferences sharedPreferences = getSharedPreferences(MainActivity.FILE_NAME, Context.MODE_PRIVATE); ((Button) findViewById(R.id.buttonStoreForApp)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String name = ((EditText) findViewById(R.id.editTextForApp)).getText().toString(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(MainActivity.KEY_NAME, name); editor.apply(); } }); ((Button) findViewById(R.id.buttonRetrieveForApp)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String name = sharedPreferences.getString(MainActivity.KEY_NAME, null); Snackbar.make(v, name, Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); }}

编辑 src\main\res\layout\activity_main.xml 布局文件,添加如下组件:

编辑 MainActivity

package com.mk;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import androidx.appcompat.app.AppCompatActivity;import com.google.android.material.snackbar.Snackbar;public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity"; public static final String FILE_NAME = "com.mk"; public static final String KEY_NAME = "name"; @Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 用于存储 Activity 范围的数据 SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE); ((Button) findViewById(R.id.buttonStoreForActivity)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String name = ((EditText) findViewById(R.id.editTextForActivity)).getText().toString(); SharedPreferences.Editor editor = preferences.edit(); editor.putString(KEY_NAME, name); editor.apply(); } }); ((Button) findViewById(R.id.buttonRetrieveForActivity)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String name = preferences.getString(KEY_NAME, null); Snackbar.make(v, name, Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); // 用于存储应用范围的数据 SharedPreferences sharedPreferences = getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); ((Button) findViewById(R.id.buttonStoreForApp)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String name = ((EditText) findViewById(R.id.editTextForApp)).getText().toString(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(KEY_NAME, name); editor.apply(); } }); ((Button) findViewById(R.id.buttonRetrieveForApp)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String name = sharedPreferences.getString(KEY_NAME, null); Snackbar.make(v, name, Snackbar.LENGTH_LONG).setAction("Action", null).show(); } }); ((Button) findViewById(R.id.buttonToSecondary)).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
startActivity(SecondaryActivity.class); } }); } private void startActivity(Class
cls) {
startActivity(new Intent(this, cls)); }}

参考

上一篇:Android - Access app-specific files(不完整)
下一篇:Android - Broadcasts overview(不完整)

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年03月13日 16时33分28秒