Android 共享首选项示例教程

在本教程中,我们将在Android应用程序 中使用** 共享首选项** ,以** 密钥-值** 对的形式存储数据。N

Android共享首选项概述

共享首选项允许活动和应用程序以键-值对的形式保留首选项,这种形式类似于即使用户关闭应用程序也会持续存在的映射。Android将共享偏好设置以XML文件的形式保存在data/data/{应用程序包}目录下的Shared_prefs 文件夹中。数据文件夹可以通过调用Environmental ment.getDataDirectory()获取。** 共享首选项** 是特定于应用程序的,即执行以下选项之一时会丢失数据:

  • 在卸载应用程序时
  • 清除应用程序数据(通过设置)

顾名思义,其主要目的是存储用户指定的配置详细信息,例如用户特定的设置,以保持用户登录到应用程序。要访问首选项,我们有三个API可供选择:

  • getPreferences() :在您的活动中使用,以访问特定于活动的首选项
  • getSharedPreferences() :在您的活动(或其他应用程序上下文)中使用,以访问应用程序级别的首选项
  • getDefaultSharedPreferences() :在PferenceManager上使用,获取与Android整体首选项框架一致的共享首选项

在本教程中,我们将使用getSharedPreferences()。方法定义如下:getSharedPreferences(字符串pref_name,int模式)prefs_name 为文件名。** 模式** 为操作模式。以下是适用的操作模式:

  • MODE_PRIVATE :默认模式,创建的文件只能被调用的应用程序访问
  • MODE_WORLD_READABLE :创建全球可读的文件非常危险,可能会导致应用程序存在安全漏洞
  • MODE_WORLD_WRITABLE :创建完全可写的文件非常危险,可能会导致应用程序存在安全漏洞
  • MODE_MULTI_PROCESS :即使共享首选项实例已经加载,该方法也会检查对首选项的修改
  • MODE_APPEND :这将使用已存在的首选项追加新的首选项
  • MODE_ENABLE_WRITE_AHEAD_LOGGING :数据库打开标志。设置后,默认情况下将启用预写日志

入会

我们需要一个编辑器来编辑和保存共享首选项中的更改。以下代码可用于获取共享首选项。

1SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
2Editor editor = pref.edit();

存储数据

editor.commit() 用于保存对共享首选项的更改。

1editor.putBoolean("key_name", true); // Storing boolean - true/false
2editor.putString("key_name", "string value"); // Storing string
3editor.putInt("key_name", "int value"); // Storing integer
4editor.putFloat("key_name", "float value"); // Storing float
5editor.putLong("key_name", "long value"); // Storing long
6
7editor.commit(); // commit changes

取数

通过调用getString() 可以从保存的首选项中取回数据,如下所示:

1pref.getString("key_name", null); // getting String
2pref.getInt("key_name", -1); // getting Integer
3pref.getFloat("key_name", null); // getting Float
4pref.getLong("key_name", null); // getting Long
5pref.getBoolean("key_name", null); // getting boolean

清除或删除数据

Remove() 用于删除该特定值。** Clear()** 用于删除所有数据

1editor.remove("name"); // will delete key name
2editor.remove("email"); // will delete key email
3
4editor.commit(); // commit changes
1editor.clear();
2editor.commit(); // commit changes

项目结构

android-shared-preferences-project-view

Android共享首选项项目代码

active_main.xml布局由两个EditText视图组成,它们存储和显示姓名和电子邮件。这三个按钮在MainActivity中实现各自的onClick。

 1<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
 2    android:layout_width="match_parent"
 3    android:layout_height="match_parent"
 4    android:paddingBottom="@dimen/activity_vertical_margin"
 5    android:paddingLeft="@dimen/activity_horizontal_margin"
 6    android:paddingRight="@dimen/activity_horizontal_margin"
 7    android:paddingTop="@dimen/activity_vertical_margin" >
 8
 9    <Button
10        android:id="@+id/btnSave"
11        android:layout_width="wrap_content"
12        android:layout_height="wrap_content"
13        android:layout_centerVertical="true"
14        android:layout_alignParentLeft="true"
15        android:layout_alignParentStart="true"
16        android:onClick="Save"
17        android:text="Save" />
18
19    <Button
20        android:id="@+id/btnRetr"
21        android:layout_width="wrap_content"
22        android:layout_height="wrap_content"
23        android:layout_centerHorizontal="true"
24        android:layout_centerVertical="true"
25        android:onClick="Get"
26        android:text="Retrieve" />
27
28    <Button
29        android:id="@+id/btnClear"
30        android:layout_width="wrap_content"
31        android:layout_height="wrap_content"
32        android:layout_alignRight="@+id/etEmail"
33        android:layout_centerVertical="true"
34        android:layout_alignParentRight="true"
35        android:layout_alignParentEnd="true"
36        android:onClick="clear"
37        android:text="Clear" />
38
39    <EditText
40        android:id="@+id/etEmail"
41        android:layout_width="match_parent"
42        android:layout_height="wrap_content"
43        android:ems="10"
44        android:hint="Email"
45        android:inputType="textEmailAddress"
46        android:layout_below="@+id/etName"
47        android:layout_marginTop="20dp"
48        android:layout_alignParentRight="true"
49        android:layout_alignParentEnd="true" />
50
51    <EditText
52        android:id="@+id/etName"
53        android:layout_width="match_parent"
54        android:layout_height="wrap_content"
55        android:ems="10"
56        android:hint="Name"
57        android:inputType="text"
58        android:layout_alignParentTop="true"
59        android:layout_alignLeft="@+id/etEmail"
60        android:layout_alignStart="@+id/etEmail" />
61
62</RelativeLayout>

MainActivity.java文件用于通过键保存和检索数据。

 1package com.journaldev.sharedpreferences;
 2
 3import android.app.Activity;
 4import android.content.Context;
 5import android.content.SharedPreferences;
 6import android.os.Bundle;
 7import android.view.Menu;
 8import android.view.View;
 9import android.widget.TextView;
10
11public class MainActivity extends Activity {
12    SharedPreferences sharedpreferences;
13    TextView name;
14    TextView email;
15    public static final String mypreference = "mypref";
16    public static final String Name = "nameKey";
17    public static final String Email = "emailKey";
18
19    @Override
20    protected void onCreate(Bundle savedInstanceState) {
21        super.onCreate(savedInstanceState);
22        setContentView(R.layout.activity_main);
23        name = (TextView) findViewById(R.id.etName);
24        email = (TextView) findViewById(R.id.etEmail);
25        sharedpreferences = getSharedPreferences(mypreference,
26                Context.MODE_PRIVATE);
27        if (sharedpreferences.contains(Name)) {
28            name.setText(sharedpreferences.getString(Name, ""));
29        }
30        if (sharedpreferences.contains(Email)) {
31            email.setText(sharedpreferences.getString(Email, ""));
32
33        }
34
35    }
36
37    public void Save(View view) {
38        String n = name.getText().toString();
39        String e = email.getText().toString();
40        SharedPreferences.Editor editor = sharedpreferences.edit();
41        editor.putString(Name, n);
42        editor.putString(Email, e);
43        editor.commit();
44    }
45
46    public void clear(View view) {
47        name = (TextView) findViewById(R.id.etName);
48        email = (TextView) findViewById(R.id.etEmail);
49        name.setText("");
50        email.setText("");
51
52    }
53
54    public void Get(View view) {
55        name = (TextView) findViewById(R.id.etName);
56        email = (TextView) findViewById(R.id.etEmail);
57        sharedpreferences = getSharedPreferences(mypreference,
58                Context.MODE_PRIVATE);
59
60        if (sharedpreferences.contains(Name)) {
61            name.setText(sharedpreferences.getString(Name, ""));
62        }
63        if (sharedpreferences.contains(Email)) {
64            email.setText(sharedpreferences.getString(Email, ""));
65
66        }
67    }
68
69    @Override
70    public boolean onCreateOptionsMenu(Menu menu) {
71        // Inflate the menu; this adds items to the action bar if it is present.
72        getMenuInflater().inflate(R.menu.menu_main, menu);
73        return true;
74    }
75
76}

_my首选项_是存储共享首选项键-值对的文件名。下图显示了我们项目的最终输出:android-shared-preference-example本教程就此结束。您可以通过下面的链接下载项目Android共享首选项

下载Android共享偏好示例项目

Published At
Categories with 技术
Tagged with
comments powered by Disqus