8

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

谢谢。

4

5 回答 5

18
  1. gson-1.7.1.jar从此链接下载: GsonLibJar

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

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

任何关于这个工具的建议都非常受欢迎。

于 2013-01-24T12:31:06.893 回答
1

另一种方法是自己保存每个属性。首选项只接受原始类型,因此您不能将复杂的对象放入其中

于 2013-01-24T12:18:40.183 回答
1

您可以使用全局类

    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();       
于 2013-01-24T12:24:24.560 回答
0

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

于 2013-01-24T12:20:18.890 回答
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();

现在你可以在其他地方使用它,比如其他类。下面是输出类。

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);
于 2013-02-04T03:21:36.763 回答