[Shared Preferences
是XML文件,用于将私有原始数据存储在键值对中。数据类型包括Boolean,floats >>,ints,longs和strings。
[我们要保存一些可在整个应用程序中访问的数据时,一种方法是将其保存在全局变量中。但是,一旦应用程序关闭,它将消失。另一个推荐的方法是保存在SharedPreference
中。保存在SharedPreferences文件中的数据可在整个应用程序中访问,并且即使在应用程序关闭或重新启动后也可以保留。
SharedPreferences
将数据保存为键值对,并且可以以相同的方式进行访问。
您可以使用两种方法创建SharedPreferences
的对象,
1)。getSharedPreferences()
:使用此方法,您可以创建多个SharedPreferences。及其第一个参数,名称为
SharedPreferences
。
2)。getPreferences():使用此方法可以创建单个SharedPreferences
。
存储数据
添加变量声明/创建首选项文件
public static final String PREFERENCES_FILE_NAME = "MyAppPreferences";
检索文件名的句柄(使用getSharedPreferences)
SharedPreferences settingsfile= getSharedPreferences(PREFERENCES_FILE_NAME,0);
打开编辑器并添加键值对
SharedPreferences.Editor myeditor = settingsfile.edit();
myeditor.putBoolean("IITAMIYO", true);
myeditor.putFloat("VOLUME", 0.7)
myeditor.putInt("BORDER", 2)
myeditor.putLong("SIZE", 12345678910L)
myeditor.putString("Name", "Amiyo")
myeditor.apply();
不要忘记使用myeditor.apply()
来应用/保存,如上所示。
检索数据
SharedPreferences mysettings= getSharedPreferences(PREFERENCES_FILE_NAME, 0);
IITAMIYO = mysettings.getBoolean("IITAMIYO", false);
//returns value for the given key.
//second parameter gives the default value if no user preference found
// (set to false in above case)
VOLUME = mysettings.getFloat("VOLUME", 0.5)
//0.5 being the default value if no volume preferences found
// and similarly there are get methods for other data types
public class Preferences {
public static final String PREF_NAME = "your preferences name";
@SuppressWarnings("deprecation")
public static final int MODE = Context.MODE_WORLD_WRITEABLE;
public static final String USER_ID = "USER_ID_NEW";
public static final String USER_NAME = "USER_NAME";
public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String PHONE = "PHONE";
public static final String address = "address";
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key,
boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
public static void writeFloat(Context context, String key, float value) {
getEditor(context).putFloat(key, value).commit();
}
public static float readFloat(Context context, String key, float defValue) {
return getPreferences(context).getFloat(key, defValue);
}
public static void writeLong(Context context, String key, long value) {
getEditor(context).putLong(key, value).commit();
}
public static long readLong(Context context, String key, long defValue) {
return getPreferences(context).getLong(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
****使用首选项通过以下方式写入值:-****
Preferences.writeString(getApplicationContext(),
Preferences.NAME, "dev");
****使用首选项使用以下方法读取值:-****
Preferences.readString(getApplicationContext(), Preferences.NAME,
"");
创建SharedPreference
的最佳方法,并且要全局使用,您需要创建一个如下所示的类:
public class PreferenceHelperDemo {
private final SharedPreferences mPrefs;
public PreferenceHelperDemo(Context context) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
private String PREF_Key= "Key";
public String getKey() {
String str = mPrefs.getString(PREF_Key, "");
return str;
}
public void setKey(String pREF_Key) {
Editor mEditor = mPrefs.edit();
mEditor.putString(PREF_Key, pREF_Key);
mEditor.apply();
}
}
SharedPreferences mPref;
SharedPreferences.Editor editor;
public SharedPrefrences(Context mContext) {
mPref = mContext.getSharedPreferences(Constant.SharedPreferences, Context.MODE_PRIVATE);
editor=mPref.edit();
}
public void setLocation(String latitude, String longitude) {
SharedPreferences.Editor editor = mPref.edit();
editor.putString("latitude", latitude);
editor.putString("longitude", longitude);
editor.apply();
}
public String getLatitude() {
return mPref.getString("latitude", "");
}
public String getLongitude() {
return mPref.getString("longitude", "");
}
public void setGCM(String gcm_id, String device_id) {
editor.putString("gcm_id", gcm_id);
editor.putString("device_id", device_id);
editor.apply();
}
public String getGCMId() {
return mPref.getString("gcm_id", "");
}
public String getDeviceId() {
return mPref.getString("device_id", "");
}
public void setUserData(User user){
Gson gson = new Gson();
String json = gson.toJson(user);
editor.putString("user", json);
editor.apply();
}
public User getUserData(){
Gson gson = new Gson();
String json = mPref.getString("user", "");
User user = gson.fromJson(json, User.class);
return user;
}
public void setSocialMediaStatus(SocialMedialStatus status){
Gson gson = new Gson();
String json = gson.toJson(status);
editor.putString("status", json);
editor.apply();
}
public SocialMedialStatus getSocialMediaStatus(){
Gson gson = new Gson();
String json = mPref.getString("status", "");
SocialMedialStatus status = gson.fromJson(json, SocialMedialStatus.class);
return status;
}
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
从共享首选项中读取
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Initialise here..
SharedPreferences msharedpref = getSharedPreferences("msh",
MODE_PRIVATE);
Editor editor = msharedpref.edit();
store data...
editor.putString("id",uida); //uida is your string to be stored
editor.commit();
finish();
fetch...
SharedPreferences prefs = this.getSharedPreferences("msh", Context.MODE_PRIVATE);
uida = prefs.getString("id", "");
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
您还可以查看我的过去sample project,为此目的而编写。我会在本地保存一个名称,并根据用户的请求或应用启动时进行检索。
但是,此时最好使用commit
(而不是apply
)来持久保存数据。更多信息here。
// Create object of SharedPreferences.
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("name", required_Text);
//commits your edits
editor.commit();
// Its used to retrieve data
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
String name = sharedPref.getString("name", "");
if (name.equalsIgnoreCase("required_Text")) {
Log.v("Matched","Required Text Matched");
} else {
Log.v("Not Matched","Required Text Not Matched");
}
共享的首选项很容易学习,因此请看一下关于sharedpreference的简单教程>
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class UserSettingActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}