如何在Android中使用SharedPreferences来存储、获取和编辑值

598

我想储存一个时间值并且需要检索和编辑它。我该如何使用SharedPreferences实现这个目的?


我已经实现了一个通用的SharedPreferences包装器,请看这里:http://android-know-how-to.blogspot.co.il/2014/03/androids-shared-preferences.html - TacB0sS
一个简化的方法是使用这个库:http://github.com/viralypatel/Android-SharedPreferences-Helper ... 更多技术细节请参见我的答案 - Viral Patel
https://dev59.com/LGAg5IYBdhLWcg3wZ6TY#25585711 - CrandellWS
30个回答

866

要获取共享参数,请使用以下方法 在您的Activity中:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

读取偏好设置:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 
编辑和保存偏好设置。
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

Android SDK的示例目录中包含一个检索和存储共享首选项的示例。它位于:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

Edit==>

我注意到,同样需要在这里解释commit()apply()之间的区别。

commit()在成功保存值时返回true,否则返回false。它会同步地将值保存到SharedPreferences中。

apply()从2.3开始添加,无论成功或失败都没有返回值。它会立即将值保存到SharedPreferences中,但是会启动一个异步的提交。 更多细节请参见此处


5
(针对阅读上述内容的任何人)是的,这是任意的。这个例子只是将当前日期保存为一个偏好设置,并使用键“com.example.app.datetime”。 - MSpeed
1
this.getSharedPreferences 给我返回以下错误:The method getSharedPreferences(String, int) is undefined for the type MyActivity - Si8
18
SharedPreferences.Editor.apply() 是在2010年11月的Gingerbread版本中引入的(在此答案发布之后)。如果可能的话,请使用它代替commit(),因为apply()更加高效。 - UpLate
4
Editor.apply() 要求 API 等级在 9 或以上。若低于此等级,请使用 Editor.commit()。 - Mr. Developerdude
兄弟,考虑一下相对布局。我在相对布局上放了一个地图图片。我有一个针形图片作为ImageView。我成功地将动态ImageView(针形图片)添加到相对布局(地图)上。我想将带有标记的相对布局存储在我的应用程序本地文件夹中,并检索具有相同标记的相对布局。我想要使用SQLite进行存储。这是否可以使用共享首选项?我的想法是正确的还是错误的...请给出任何存储带有图像的布局的想法... - reegan29
显示剩余10条评论

307

要在共享首选项中存储值:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();

要从共享首选项中检索值:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}

21
我最喜欢这个答案,因为它使用了getDefaultSharedPreferences。对于大多数用户来说,这将简化操作,因为可以在整个应用程序中访问相同的首选项,并且无需担心命名首选项文件。更多信息请参见:https://dev59.com/cm025IYBdhLWcg3wi2mw#6310080。 - Dick Lucas
1
我同意...在尝试使用被接受答案中的方法从另一个活动访问我的共享首选项时,我曾经苦苦思索,直到找到了这个。非常感谢! - You'reAGitForNotUsingGit
我该如何使用它来保存和加载“Map<DateTime,Integer>”? - Dmitry
使用 https://github.com/AliEsaAssadi/Android-Power-Preference 来简化实现。 - Ali Asadi

169

编辑sharedpreference中的数据

 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
 editor.putString("text", mSaved.getText().toString());
 editor.putInt("selection-start", mSaved.getSelectionStart());
 editor.putInt("selection-end", mSaved.getSelectionEnd());
 editor.apply();

sharedpreference检索数据

SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) 
{
  //mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
  int selectionStart = prefs.getInt("selection-start", -1);
  int selectionEnd = prefs.getInt("selection-end", -1);
  /*if (selectionStart != -1 && selectionEnd != -1)
  {
     mSaved.setSelection(selectionStart, selectionEnd);
  }*/
}

编辑

我从API Demo示例中获取了这段代码片段。它包含一个EditText文本框,在这个context中是不必要的。我正在对此进行评论。


12
使用getPreferences(MODE_PRIVATE)而不是getPreferences(0),以提高可读性。 - Key
我还想知道mSaved是什么。算了,我认为它是编辑框。 - karlstackoverflow
2
在 getInt 中,-1 代表什么意思? - amr osama
2
如果sharedpreferences中不存在键(selection-start),那么将返回默认值。它可以是任何值,仅供参考。 - DeRagan
嘿,我有一个关于Shared Preferences的问题。你介意回答一下吗?http://stackoverflow.com/questions/35713822/shared-preferences-extremely-simple-issue - Ruchir Baronia
显示剩余2条评论

51

写作:

SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();

阅读:

SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");

MODE_WORLD_WRITEABLE已被弃用。 - Christopher Smit
谢谢你救了我的一天。 - undefined

30

单例共享首选项类。将来可能有助于他人。

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

只需在MainActivity上调用SharedPref.init()一次即可。

SharedPref.init(getApplicationContext());

写入数据

SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

读取数据

String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.

嗨,@Magesh Pandian,我使用了上面的代码。当第一次运行应用程序时,我读取userId的值,但不知道为什么它读取值“16”,而不是空白。请回复。提前致谢。 - Dharmishtha

29

最简单的方法:

保存:

getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();

获取:

your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);

我在活动之间尝试过这个,但它没有起作用。变量名中需要包结构吗? - Gaʀʀʏ
要在活动之间使用此结构,请将 getPreferences(MODE_PRIVATE) 替换为 PreferenceManager.getDefaultSharedPreferences(您的活动)。 - Lucian Novac
使用apply()代替commit()。 - Vaibhav

18

存储信息

SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();

重置您的偏好设置

SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

14
如果你正在与团队中的其他开发人员一起开发庞大的应用程序,希望代码井然有序,没有散乱的代码或不同的SharedPreferences实例,那么可以尝试以下做法:
//SharedPreferences manager class
public class SharedPrefs {

    //SharedPreferences file name
    private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";

    //here you can centralize all your shared prefs keys
    public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
    public static String KEY_MY_SHARED_FOO = "my_shared_foo";

    //get the SharedPreferences object instance
    //create SharedPreferences file if not present


    private static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
    }

    //Save Booleans
    public static void savePref(Context context, String key, boolean value) {
        getPrefs(context).edit().putBoolean(key, value).commit();       
    }

    //Get Booleans
    public static boolean getBoolean(Context context, String key) {
        return getPrefs(context).getBoolean(key, false);
    }

    //Get Booleans if not found return a predefined default value
    public static boolean getBoolean(Context context, String key, boolean defaultValue) {
        return getPrefs(context).getBoolean(key, defaultValue);
    }

    //Strings
    public static void save(Context context, String key, String value) {
        getPrefs(context).edit().putString(key, value).commit();
    }

    public static String getString(Context context, String key) {
        return getPrefs(context).getString(key, "");
    }

    public static String getString(Context context, String key, String defaultValue) {
        return getPrefs(context).getString(key, defaultValue);
    }

    //Integers
    public static void save(Context context, String key, int value) {
        getPrefs(context).edit().putInt(key, value).commit();
    }

    public static int getInt(Context context, String key) {
        return getPrefs(context).getInt(key, 0);
    }

    public static int getInt(Context context, String key, int defaultValue) {
        return getPrefs(context).getInt(key, defaultValue);
    }

    //Floats
    public static void save(Context context, String key, float value) {
        getPrefs(context).edit().putFloat(key, value).commit();
    }

    public static float getFloat(Context context, String key) {
        return getPrefs(context).getFloat(key, 0);
    }

    public static float getFloat(Context context, String key, float defaultValue) {
        return getPrefs(context).getFloat(key, defaultValue);
    }

    //Longs
    public static void save(Context context, String key, long value) {
        getPrefs(context).edit().putLong(key, value).commit();
    }

    public static long getLong(Context context, String key) {
        return getPrefs(context).getLong(key, 0);
    }

    public static long getLong(Context context, String key, long defaultValue) {
        return getPrefs(context).getLong(key, defaultValue);
    }

    //StringSets
    public static void save(Context context, String key, Set<String> value) {
        getPrefs(context).edit().putStringSet(key, value).commit();
    }

    public static Set<String> getStringSet(Context context, String key) {
        return getPrefs(context).getStringSet(key, null);
    }

    public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
        return getPrefs(context).getStringSet(key, defaultValue);
    }
}

在您的活动中,您可以通过以下方式保存SharedPreferences。
//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);

您可以通过以下方式检索您的SharedPreferences

//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);

12

在任何应用程序中,都可以通过PreferenceManager实例及其相关方法getDefaultSharedPreferences(Context)访问默认偏好设置。

使用SharedPreference实例,可以使用getInt(String key, int defVal)检索任何首选项的int值。在这种情况下,我们感兴趣的首选项是counter。

在我们的情况下,我们可以使用edit()修改SharedPreference实例,并使用putInt(String key, int newVal)将计数器递增到我们的应用程序中,使其持久存在应用程序之外并相应地显示。

要进一步演示此功能,请重新启动您的应用程序,您将注意到每次重新启动应用程序时计数器都会增加。

PreferencesDemo.java

代码:

package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class PreferencesDemo extends Activity {
   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Get the app's shared preferences
        SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);

        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);

        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");

        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important
    }
}

主要文件.xml

代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/text"  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello" />
</LinearLayout>

11

要将值存储在共享首选项中:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();

要从共享首选项中检索值:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接