且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-12 09:09:04

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

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

Add this library to your android project and configure build path.

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

Add the following class to your package.

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

  • 通过扩展 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;
    } }
    

  • 像这样在清单的 application 标记中添加该应用程序类.

  • Add that application class in your manifest's application tag like this.

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

  • 在您要在 Shared Preference 中存储价值的主要活动中,执行以下操作.

  • In Your Main Activity where you wanted to store value in Shared Preference do something like this.

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

  • 在另一个活动中,您想从 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());
    }  }
    

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

    Hope this can help you. In this answer I used your class for the reference 'User' so you can better understand. However we can not relay on this method if you opted to store very large objects in preference as we all know that we have limited memory size for each app in data directory so that if you are sure you have only limited data to store in shared preference you can use this alternative.

    对此工具的任何建议都将受到欢迎.

    Any suggestions on this implement are most welcome.