如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3624280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use SharedPreferences in Android to store, fetch and edit values
提问by Muhammad Maqsoodur Rehman
I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences
to do this?
我想存储一个时间值,需要检索和编辑它。我怎样才能SharedPreferences
做到这一点?
回答by naikus
To obtain shared preferences, use the following method In your activity:
要获取共享首选项,请在您的活动中使用以下方法:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
要阅读首选项:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
编辑和保存首选项
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:
android sdk 的示例目录包含检索和存储共享首选项的示例。它位于:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Edit==>
编辑==>
I noticed, it is important to write difference between commit()
and apply()
here as well.
我注意到,在这里写下commit()
和之间的差异也很重要apply()
。
commit()
return true
if value saved successfully otherwise false
. It save values to SharedPreferences synchronously.
commit()
true
如果值保存成功则返回,否则返回false
。它将值同步保存到 SharedPreferences 。
apply()
was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronouscommit.
More detail is here.
apply()
在 2.3 中添加并且在成功或失败时不返回任何值。它立即将值保存到 SharedPreferences,但会启动异步提交。更多细节在这里。
回答by Harneet Kaur
To store values in shared preferences:
要将值存储在共享首选项中:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
To retrieve values from shared preferences:
要从共享首选项中检索值:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
name = name + " Sethi"; /* Edit the value here*/
}
回答by DeRagan
To editdata from sharedpreference
要编辑从数据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();
To retrievedata from sharedpreference
为了获取从数据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);
}*/
}
Edit
编辑
I took this snippet from API Demo sample. It had an EditText
box there . In this context
it is not required.I am commenting the same .
我从 API Demo 示例中获取了这个片段。那里有一个EditText
盒子。在这context
不是必需的。我评论相同。
回答by stackoverflow
To Write :
来写 :
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
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();
To Read :
阅读 :
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
回答by ArcDare
Easiest way:
最简单的方法:
To save:
保存:
getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();
To retrieve:
检索:
your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);
回答by Jorgesys
Setting values in Preference:
在首选项中设置值:
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
从首选项中检索数据:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
more info:
更多信息:
回答by Magesh Pandian
Singleton Shared Preferences Class. it may help for others in future.
单例共享首选项类。将来可能会对其他人有所帮助。
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();
}
}
Simply call SharedPref.init()
on MainActivity
once
只需拨打SharedPref.init()
上MainActivity
一次
SharedPref.init(getApplicationContext());
To Write data
写入数据
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.
To Read Data
读取数据
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.
回答by fidazik
To store information
存储信息
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();
To reset your preferences
重置您的偏好
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
回答by alexm
If you are making a large application with other developers in your team and intend to have everything well organized without scattered code or different SharedPreferences instances, you may do something like this:
如果您正在与团队中的其他开发人员一起制作大型应用程序,并打算在没有分散的代码或不同的 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);
}
}
In your activity you may save SharedPreferences this way
在您的活动中,您可以通过这种方式保存 SharedPreferences
//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
and you may retrieve your SharedPreferences this way
你可以通过这种方式检索你的 SharedPreferences
//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
回答by Sathish
In any application, there are default preferences that can accessed through the PreferenceManager
instance and its related method getDefaultSharedPreferences(Context)
.
在任何应用程序中,都有可以通过PreferenceManager
实例及其相关方法访问的默认首选项getDefaultSharedPreferences(Context)
。
With the SharedPreference
instance one can retrieve the int value of the any preference with the getInt(String key, int defVal). The preference we are interested in this case is counter .
对于SharedPreference
实例,可以使用getInt(String key, int defVal)检索 any 首选项的 int 值。我们在这种情况下感兴趣的偏好是 counter 。
In our case, we can modify the SharedPreference
instance in our case using the edit() and use the putInt(String key, int newVal)
We increased the count for our application that presist beyond the application and displayed accordingly.
在我们的案例中,我们可以SharedPreference
使用 edit()修改我们案例中的实例,并使用putInt(String key, int newVal)
We 增加我们的应用程序的计数,该计数超出应用程序并相应地显示。
To further demo this, restart and you application again, you will notice that the count will increase each time you restart the application.
为了进一步演示这一点,重新启动应用程序,您会注意到每次重新启动应用程序时计数都会增加。
PreferencesDemo.java
首选项演示.java
Code:
代码:
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
}
}
main.xml
主文件
Code:
代码:
<?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>