【问题标题】:How to store class object in android sharedPreference?如何在android sharedPreference中存储类对象?
【发布时间】:2013-01-08 04:44:12
【问题描述】:

我想将类对象存储在 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;
    }
}

谢谢。

【问题讨论】:

  • 为什么不让它可序列化呢?这是正确的解决方案。

标签: android sharedpreferences


【解决方案1】:
  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. 通过像这样扩展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());
    }  }
    

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

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

【讨论】:

  • 如果我将它保存为使用此类型的 Arraylist,我如何才能将数组列表作为对象获取
  • @PankajNimgade 您可以将您的arrayList 设置为对象,但请确保您可以序列化您的对象包含在arrayList 中。此外,您可以使其可打包并直接传递给意图。
  • @user456118 嗨,在我找到之前,你的答案是最好的,就像魅力一样,只是我需要修改一下,如果用户已经登录过一次,那么它不应该显示登录屏幕,它应该直接显示主活动屏幕。请帮我解决这个问题...
【解决方案2】:

另一种方法是自己保存每个属性。.Preferences 只接受原始类型,所以你不能在里面放一个复杂的 Object

【讨论】:

    【解决方案3】:

    你可以使用全局类

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

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

      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】:

      您可以添加一些普通的 SharedPreferences “name”、“address”、“age”和“isActive”,然后在实例化类时简单地加载它们

      【讨论】:

        【解决方案5】:

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

        您可以扩展 MainActivity 类或其他您将存储“您想要保留的东西的价值”的类。将其放入 writer 和 reader 类:

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

        【讨论】:

          猜你喜欢
          • 2014-01-17
          • 2016-08-23
          • 1970-01-01
          • 2017-09-10
          • 2017-11-27
          • 1970-01-01
          • 2019-03-08
          • 1970-01-01
          • 2013-02-23
          相关资源
          最近更新 更多