如何在android sharedPreference中存储类对象?

我想在android的sharedpreference中存储类对象。 我做了一些基本的search,我得到了一些答案,如使它可序列化的对象和存储,但我的需要是如此简单。 我想存储一些用户信息,如姓名,地址,年龄和布尔值是活跃的。 我为此做了一个用户类。

public class User { private String name; private String address; private int age; private boolean isActive; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } } 

谢谢。

Solutions Collecting From Web of "如何在android sharedPreference中存储类对象?"

  1. 从这个链接下载gson-1.7.1.jar : GsonLibJar

  2. 将这个库添加到你的android项目并configuration构buildpath。

  3. 将以下类添加到您的包中。

     package com.abhan.objectinpreference; import java.lang.reflect.Type; import android.content.Context; import android.content.SharedPreferences; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ComplexPreferences { private static ComplexPreferences complexPreferences; private final Context context; private final SharedPreferences preferences; private final SharedPreferences.Editor editor; private static Gson GSON = new Gson(); Type typeOfObject = new TypeToken<Object>(){} .getType(); private ComplexPreferences(Context context, String namePreferences, int mode) { this.context = context; if (namePreferences == null || namePreferences.equals("")) { namePreferences = "abhan"; } preferences = context.getSharedPreferences(namePreferences, mode); editor = preferences.edit(); } public static ComplexPreferences getComplexPreferences(Context context, String namePreferences, int mode) { if (complexPreferences == null) { complexPreferences = new ComplexPreferences(context, namePreferences, mode); } return complexPreferences; } public void putObject(String key, Object object) { if (object == null) { throw new IllegalArgumentException("Object is null"); } if (key.equals("") || key == null) { throw new IllegalArgumentException("Key is empty or null"); } editor.putString(key, GSON.toJson(object)); } public void commit() { editor.commit(); } public <T> T getObject(String key, Class<T> a) { String gson = preferences.getString(key, null); if (gson == null) { return null; } else { try { return GSON.fromJson(gson, a); } catch (Exception e) { throw new IllegalArgumentException("Object stored with key " + key + " is instance of other class"); } } } } 
  4. 通过像这样扩展Application类创build一个类

     package com.abhan.objectinpreference; import android.app.Application; public class ObjectPreference extends Application { private static final String TAG = "ObjectPreference"; private ComplexPreferences complexPrefenreces = null; @Override public void onCreate() { super.onCreate(); complexPrefenreces = ComplexPreferences.getComplexPreferences(getBaseContext(), "abhan", MODE_PRIVATE); android.util.Log.i(TAG, "Preference Created."); } public ComplexPreferences getComplexPreference() { if(complexPrefenreces != null) { return complexPrefenreces; } return null; } } 
  5. 像这样在清单的application标签中添加该应用程序类。

     <application android:name=".ObjectPreference" android:allowBackup="false" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > ....your activities and the rest goes here </application> 
  6. 在你想要在Shared Preference存储价值的主要活动中做这样的事情。

     package com.abhan.objectinpreference; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { private final String TAG = "MainActivity"; private ObjectPreference objectPreference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); objectPreference = (ObjectPreference) this.getApplication(); User user = new User(); user.setName("abhan"); user.setAddress("Mumbai"); user.setAge(25); user.setActive(true); User user1 = new User(); user1.setName("Harry"); user.setAddress("London"); user1.setAge(21); user1.setActive(false); ComplexPreferences complexPrefenreces = objectPreference.getComplexPreference(); if(complexPrefenreces != null) { complexPrefenreces.putObject("user", user); complexPrefenreces.putObject("user1", user1); complexPrefenreces.commit(); } else { android.util.Log.e(TAG, "Preference is null"); } } } 
  7. 在另一个你想要从Preference获得价值的活动中做这样的事情。

     package com.abhan.objectinpreference; import android.app.Activity; import android.os.Bundle; public class SecondActivity extends Activity { private final String TAG = "SecondActivity"; private ObjectPreference objectPreference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); objectPreference = (ObjectPreference) this.getApplication(); ComplexPreferences complexPreferences = objectPreference.getComplexPreference(); android.util.Log.i(TAG, "User"); User user = complexPreferences.getObject("user", User.class); android.util.Log.i(TAG, "Name " + user.getName()); android.util.Log.i(TAG, "Address " + user.getAddress()); android.util.Log.i(TAG, "Age " + user.getAge()); android.util.Log.i(TAG, "isActive " + user.isActive()); android.util.Log.i(TAG, "User1"); User user1 = complexPreferences.getObject("user", User.class); android.util.Log.i(TAG, "Name " + user1.getName()); android.util.Log.i(TAG, "Address " + user1.getAddress()); android.util.Log.i(TAG, "Age " + user1.getAge()); android.util.Log.i(TAG, "isActive " + user1.isActive()); } } 

希望这可以帮到你。 在这个答案中,我用你的class级的参考“用户”,所以你可以更好地理解。 但是,如果您select优先存储非常大的对象,则我们无法继续此方法,因为我们都知道,数据目录中的每个应用程序的内存大小都是有限的,所以如果您确定只有有限的数据要存储在共享首选项中你可以使用这个select。

任何关于这个工具的build议是最受欢迎的。

另一种方法是保存每个属性自己..Preferences只接受原始types,所以你不能把一个复杂的对象

您可以添加一些正常的SharedPreferences“名称”,“地址”,“年龄”和“isActive”,并简单地加载它们时实例化类

你可以使用全局类

  public class GlobalState extends Application { private String testMe; public String getTestMe() { return testMe; } public void setTestMe(String testMe) { this.testMe = testMe; } } 

然后在nadroid menifest中find您的应用程序标签,并将其添加到它:

  android:name="com.package.classname" 

您可以使用以下代码设置并从任何活动中获取数据。

  GlobalState gs = (GlobalState) getApplication(); gs.setTestMe("Some String");</code> // Get values GlobalState gs = (GlobalState) getApplication(); String s = gs.getTestMe(); 

如何通过SharedPreferences存储login值的简单解决scheme。

您可以扩展MainActivity类或其他类,您将在其中存储“您要保留的内容的值”。 把它写进作家和读者的课堂:

 public static final String GAME_PREFERENCES_LOGIN = "Login"; 

这里InputClass是input,OutputClass是输出类。

 // This is a storage, put this in a class which you can extend or in both classes: //(input and output) public static final String GAME_PREFERENCES_LOGIN = "Login"; // String from the text input (can be from anywhere) String login = inputLogin.getText().toString(); // then to add a value in InputCalss "SAVE", SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0); Editor editor = example.edit(); editor.putString("value", login); editor.commit(); 

现在,您可以像其他课程一样在其他地方使用它。 以下是OutputClass。

 SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0); String userString = example.getString("value", "defValue"); // the following will print it out in console Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);