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

时间:2013-01-24 12:15:29

标签: android sharedpreferences

我想在android sharedpreference中存储类对象。我做了一些基本的搜索,我得到了一些答案,比如使它成为可序列化的对象并存储它,但我的需求是如此简单。我想存储一些用户信息,如名称,地址,年龄和布尔值是活动的。我为此制作了一个用户类。

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;
    }
}

感谢。

5 个答案:

答案 0 :(得分:18)

  1. 从以下链接下载gson-1.7.1.jarGsonLibJar

  2. 将此库添加到您的android项目并配置构建路径。

  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. 通过像{/ p>这样扩展Application类来再创建一个类

    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());
    }  }
    
  8. 希望这可以帮到你。在这个答案中,我使用你的课程作为参考'用户',这样你就可以更好地理解。但是,如果您选择优先存储非常大的对象,我们无法继续使用此方法,因为我们都知道数据目录中的每个应用程序的内存大小都有限,因此如果您确定只有有限的数据存储在共享首选项中你可以使用这个替代方案。

    欢迎对此工具提出任何建议。

答案 1 :(得分:1)

另一种方法是自己保存每个属性。参考只接受基本类型,因此你不能在其中放置复杂的对象

答案 2 :(得分:0)

你可以添加一些正常的SharedPreferences“name”,“address”,“age”&amp; “isActive”并在实例化类

时简单地加载它们

答案 3 :(得分:0)

您可以使用全局类

    public class GlobalState extends Application
       {
   private String testMe;

     public String getTestMe() {
      return testMe;
      }
  public void setTestMe(String testMe) {
    this.testMe = testMe;
    }
} 

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

  android:name="com.package.classname"  

您可以使用以下代码设置和获取任何活动的数据。

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

      // Get values
  GlobalState gs = (GlobalState) getApplication();
  String s = gs.getTestMe();       

答案 4 :(得分:0)

如何通过SharedPreferences存储登录值的简单解决方案。

您可以扩展MainActivity类或其他类,您将在其中存储“您想要保留的值的值”。把它放到作家和读者类中:

public static final String GAME_PREFERENCES_LOGIN = "Login";

这里InputClass是输入,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);