Android SharedPreferences如何保存/存储对象

我们需要在很多地方获得用户对象,其中包含很多领域。 login后,我想保存/存储这些用户对象。 我们怎样才能实现这种情况?

我不能像这样保存:

SharedPreferences.Editor prefsEditor = myPrefs.edit(); prefsEditor.putString("BusinessUnit", strBusinessUnit); 

您可以使用gson.jar将类对象存储到SharedPreferences中 。 你可以从google-gson下载这个jar 包

或者在Gradle文件中添加GSON依赖项:

 compile 'com.google.code.gson:gson:2.7' 

创build一个共享首选项:

 SharedPreferences mPrefs = getPreferences(MODE_PRIVATE); 

保存:

 Editor prefsEditor = mPrefs.edit(); Gson gson = new Gson(); String json = gson.toJson(MyObject); prefsEditor.putString("MyObject", json); prefsEditor.commit(); 

检索:

 Gson gson = new Gson(); String json = mPrefs.getString("MyObject", ""); MyObject obj = gson.fromJson(json, MyObject.class); 

要添加到@ MuhammadAamirALi的答案,您可以使用Gson来保存和检索对象的列表

将用户定义的对象的列表保存到SharedPreferences中

 public static final String KEY_CONNECTIONS = "KEY_CONNECTIONS"; SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); User entity = new User(); // ... set entity fields List<Connection> connections = entity.getConnections(); // convert java object to JSON format, // and returned as JSON formatted string String connectionsJSONString = new Gson().toJson(connections); editor.putString(KEY_CONNECTIONS, connectionsJSONString); editor.commit(); 

从SharedPreferences获取用户定义的对象列表

 String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS, null); Type type = new TypeToken < List < Connection >> () {}.getType(); List < Connection > connections = new Gson().fromJson(connectionsJSONString, type); 

我知道这个线程有点老了。 但是我会发布这个无论如何希望它可以帮助某人。 我们可以通过将对象序列化到String来将任何Object的字段存储到共享偏好设置中。 在这里我已经使用GSON来存储共享偏好的任何对象。

将对象保存为首选项:

 public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) { SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0); SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit(); final Gson gson = new Gson(); String serializedObject = gson.toJson(object); sharedPreferencesEditor.putString(serializedObjectKey, serializedObject); sharedPreferencesEditor.apply(); } 

从首选项中检索对象:

 public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) { SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0); if (sharedPreferences.contains(preferenceKey)) { final Gson gson = new Gson(); return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType); } return null; } 

注意 :

请记住在您的Gradle中添加compile 'com.google.code.gson:gson:2.6.2'dependencies

例如

 //assume SampleClass exists SampleClass mObject = new SampleObject(); //to store an object saveObjectToSharedPreference(context, "mPreference", "mObjectKey", mObject); //to retrive object stored in preference mObject = getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class); 

快乐 编码!

更好的办法是创build一个全局的Constants类来保存键或variables来获取或保存数据。

为了保存数据,调用这个方法来保存每个地方的数据。

 public static void saveData(Context con, String variable, String data) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con); prefs.edit().putString(variable, data).commit(); } 

用它来获取数据。

 public static String getData(Context con, String variable, String defaultValue) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con); String data = prefs.getString(variable, defaultValue); return data; } 

和一个这样的方法将做的伎俩

 public static User getUserInfo(Context con) { String id = getData(con, Constants.USER_ID, null); String name = getData(con, Constants.USER_NAME, null); if(id != null && name != null) { User user = new User(); //Hope you will have a user Object. user.setId(id); user.setName(name); //Here set other credentials. return user; } else return null; } 

在此之后,您还没有说明如何使用prefsEditor对象,但为了保持首选项数据,还需要使用:

 prefsEditor.commit(); 

试试这个最好的方法:

PreferenceConnector.java

 import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class PreferenceConnector { public static final String PREF_NAME = "ENUMERATOR_PREFERENCES"; public static final String PREF_NAME_REMEMBER = "ENUMERATOR_REMEMBER"; public static final int MODE = Context.MODE_PRIVATE; public static final String name = "name"; 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 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(); } } 

写下价值:

 PreferenceConnector.writeString(this, PreferenceConnector.name,"Girish"); 

并获得价值使用:

 String name= PreferenceConnector.readString(this, PreferenceConnector.name, ""); 

看到这里,这可以帮助你:

 public static boolean setObject(Context context, Object o) { Field[] fields = o.getClass().getFields(); SharedPreferences sp = context.getSharedPreferences(o.getClass() .getName(), Context.MODE_PRIVATE); Editor editor = sp.edit(); for (int i = 0; i < fields.length; i++) { Class<?> type = fields[i].getType(); if (isSingle(type)) { try { final String name = fields[i].getName(); if (type == Character.TYPE || type.equals(String.class)) { Object value = fields[i].get(o); if (null != value) editor.putString(name, value.toString()); } else if (type.equals(int.class) || type.equals(Short.class)) editor.putInt(name, fields[i].getInt(o)); else if (type.equals(double.class)) editor.putFloat(name, (float) fields[i].getDouble(o)); else if (type.equals(float.class)) editor.putFloat(name, fields[i].getFloat(o)); else if (type.equals(long.class)) editor.putLong(name, fields[i].getLong(o)); else if (type.equals(Boolean.class)) editor.putBoolean(name, fields[i].getBoolean(o)); } catch (IllegalAccessException e) { LogUtils.e(TAG, e); } catch (IllegalArgumentException e) { LogUtils.e(TAG, e); } } else { // FIXME 是对象则不写入} } return editor.commit(); } 

https://github.com/AltasT/PreferenceVObjectFile/blob/master/PreferenceVObjectFile/src/com/altas/lib/PreferenceUtils.java

如果你的对象是复杂的,我build议序列化/ XML / JSON它并将这些内容保存到SD卡。 您可以在这里find有关如何保存到外部存储的其他信息: http : //developer.android.com/guide/topics/data/data-storage.html#filesExternal

另一种方式来保存和恢复android共享首选对象,而不使用Json格式

 private static ExampleObject getObject(Context c,String db_name){ SharedPreferences sharedPreferences = c.getSharedPreferences(db_name, Context.MODE_PRIVATE); ExampleObject o = new ExampleObject(); Field[] fields = o.getClass().getFields(); try { for (Field field : fields) { Class<?> type = field.getType(); try { final String name = field.getName(); if (type == Character.TYPE || type.equals(String.class)) { field.set(o,sharedPreferences.getString(name, "")); } else if (type.equals(int.class) || type.equals(Short.class)) field.setInt(o,sharedPreferences.getInt(name, 0)); else if (type.equals(double.class)) field.setDouble(o,sharedPreferences.getFloat(name, 0)); else if (type.equals(float.class)) field.setFloat(o,sharedPreferences.getFloat(name, 0)); else if (type.equals(long.class)) field.setLong(o,sharedPreferences.getLong(name, 0)); else if (type.equals(Boolean.class)) field.setBoolean(o,sharedPreferences.getBoolean(name, false)); else if (type.equals(UUID.class)) field.set( o, UUID.fromString( sharedPreferences.getString( name, UUID.nameUUIDFromBytes("".getBytes()).toString() ) ) ); } catch (IllegalAccessException e) { Log.e(StaticConfig.app_name, "IllegalAccessException", e); } catch (IllegalArgumentException e) { Log.e(StaticConfig.app_name, "IllegalArgumentException", e); } } } catch (Exception e) { System.out.println("Exception: " + e); } return o; } private static void setObject(Context context, Object o, String db_name) { Field[] fields = o.getClass().getFields(); SharedPreferences sp = context.getSharedPreferences(db_name, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); for (Field field : fields) { Class<?> type = field.getType(); try { final String name = field.getName(); if (type == Character.TYPE || type.equals(String.class)) { Object value = field.get(o); if (value != null) editor.putString(name, value.toString()); } else if (type.equals(int.class) || type.equals(Short.class)) editor.putInt(name, field.getInt(o)); else if (type.equals(double.class)) editor.putFloat(name, (float) field.getDouble(o)); else if (type.equals(float.class)) editor.putFloat(name, field.getFloat(o)); else if (type.equals(long.class)) editor.putLong(name, field.getLong(o)); else if (type.equals(Boolean.class)) editor.putBoolean(name, field.getBoolean(o)); else if (type.equals(UUID.class)) editor.putString(name, field.get(o).toString()); } catch (IllegalAccessException e) { Log.e(StaticConfig.app_name, "IllegalAccessException", e); } catch (IllegalArgumentException e) { Log.e(StaticConfig.app_name, "IllegalArgumentException", e); } } editor.apply(); } 

如果你想存储整个对象,你可以通过做类似的事情来实现,

首先创build一个方法,将您的JSON转换为util类中的string,如下所示。

  public static <T> T fromJson(String jsonString, Class<T> theClass) { return new Gson().fromJson(jsonString, theClass); } 

然后在共享喜好类做类似的事情,

`public void storeLoginResponse(yourResponseClass objName){

  String loginJSON = UtilClass.toJson(customer); if (!TextUtils.isEmpty(customerJSON)) { editor.putString(AppConst.PREF_CUSTOMER, customerJSON); editor.commit(); } }` 

然后为getPreferences创build一个方法

 public Customer getCustomerDetails() { String customerDetail = pref.getString(AppConst.PREF_CUSTOMER, null); if (!TextUtils.isEmpty(customerDetail)) { return GSONConverter.fromJson(customerDetail, Customer.class); } else { return new Customer(); } } 

然后,只要在得到回应时调用第一种方法,然后在需要从共享首选项中获取数据时调用第一种方法

 String token = SharedPrefHelper.get().getCustomerDetails().getAccessToken(); 

就这样。

希望它会帮助你..!