How do you save/store objects in SharedPreferences on Android?

后端 未结 20 2462
野趣味
野趣味 2020-11-22 13:35

I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?

<
相关标签:
20条回答
  • 2020-11-22 14:21

    You can save object in preferences without using any library, first of all your object class must implement Serializable:

    public class callModel implements Serializable {
    
    private long pointTime;
    private boolean callisConnected;
    
    public callModel(boolean callisConnected,  long pointTime) {
        this.callisConnected = callisConnected;
        this.pointTime = pointTime;
    }
    public boolean isCallisConnected() {
        return callisConnected;
    }
    public long getPointTime() {
        return pointTime;
    }
    

    }

    Then you can easily use these two method to convert object to string and string to object:

     public static <T extends Serializable> T stringToObjectS(String string) {
        byte[] bytes = Base64.decode(string, 0);
        T object = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
            object = (T) objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
    
     public static String objectToString(Parcelable object) {
        String encoded = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            objectOutputStream.close();
            encoded = new String(Base64.encodeToString(byteArrayOutputStream.toByteArray(), 0));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encoded;
    }
    

    To save:

    SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);
    Editor prefsEditor = mPrefs.edit();
    prefsEditor.putString("MyObject", objectToString(callModelObject));
    prefsEditor.commit();
    

    To read

    String value= mPrefs.getString("MyObject", "");
    MyObject obj = stringToObjectS(value);
    
    0 讨论(0)
  • 2020-11-22 14:24

    If you want to store the whole Object that you get in response, It can achieve by doing something like,

    First Create a method that converts your JSON into a string in your util class as below.

     public static <T> T fromJson(String jsonString, Class<T> theClass) {
        return new Gson().fromJson(jsonString, theClass);
    }
    

    Then In Shared Preferences Class Do something like,

     public void storeLoginResponse(yourResponseClass objName) {
    
        String loginJSON = UtilClass.toJson(customer);
        if (!TextUtils.isEmpty(customerJSON)) {
            editor.putString(AppConst.PREF_CUSTOMER, customerJSON);
            editor.commit();
        }
    }
    

    and then create a method for getPreferences

    public Customer getCustomerDetails() {
        String customerDetail = pref.getString(AppConst.PREF_CUSTOMER, null);
        if (!TextUtils.isEmpty(customerDetail)) {
            return GSONConverter.fromJson(customerDetail, Customer.class);
        } else {
            return new Customer();
        }
    }
    

    Then Just call the First method when you get response and second when you need to get data from share preferences like

    String token = SharedPrefHelper.get().getCustomerDetails().getAccessToken();
    

    that's all.

    Hope it will help you.

    Happy Coding();

    0 讨论(0)
  • 2020-11-22 14:24

    Using Delegation Kotlin we can easily put and get data from shared preferences.

        inline fun <reified T> Context.sharedPrefs(key: String) = object : ReadWriteProperty<Any?, T> {
    
            val sharedPrefs by lazy { this@sharedPrefs.getSharedPreferences("APP_DATA", Context.MODE_PRIVATE) }
            val gson by lazy { Gson() }
            var newData: T = (T::class.java).newInstance()
    
            override fun getValue(thisRef: Any?, property: KProperty<*>): T {
                return getPrefs()
            }
    
            override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
                this.newData = value
                putPrefs(newData)
            }
    
            fun putPrefs(value: T?) {
                sharedPrefs.edit {
                    when (value) {
                        is Int -> putInt(key, value)
                        is Boolean -> putBoolean(key, value)
                        is String -> putString(key, value)
                        is Long -> putLong(key, value)
                        is Float -> putFloat(key, value)
                        is Parcelable -> putString(key, gson.toJson(value))
                        else          -> throw Throwable("no such type exist to put data")
                    }
                }
            }
    
            fun getPrefs(): T {
                return when (newData) {
                           is Int -> sharedPrefs.getInt(key, 0) as T
                           is Boolean -> sharedPrefs.getBoolean(key, false) as T
                           is String -> sharedPrefs.getString(key, "") as T ?: "" as T
                           is Long -> sharedPrefs.getLong(key, 0L) as T
                           is Float -> sharedPrefs.getFloat(key, 0.0f) as T
                           is Parcelable -> gson.fromJson(sharedPrefs.getString(key, "") ?: "", T::class.java)
                           else          -> throw Throwable("no such type exist to put data")
                       } ?: newData
            }
    
        }
    
        //use this delegation in activity and fragment in following way
            var ourData by sharedPrefs<String>("otherDatas")
    
    0 讨论(0)
  • 2020-11-22 14:28

    See here, this can help you:

    public static boolean setObject(Context context, Object o) {
            Field[] fields = o.getClass().getFields();
            SharedPreferences sp = context.getSharedPreferences(o.getClass()
                    .getName(), Context.MODE_PRIVATE);
            Editor editor = sp.edit();
            for (int i = 0; i < fields.length; i++) {
                Class<?> type = fields[i].getType();
                if (isSingle(type)) {
                    try {
                        final String name = fields[i].getName();
                        if (type == Character.TYPE || type.equals(String.class)) {
                            Object value = fields[i].get(o);
                            if (null != value)
                                editor.putString(name, value.toString());
                        } else if (type.equals(int.class)
                                || type.equals(Short.class))
                            editor.putInt(name, fields[i].getInt(o));
                        else if (type.equals(double.class))
                            editor.putFloat(name, (float) fields[i].getDouble(o));
                        else if (type.equals(float.class))
                            editor.putFloat(name, fields[i].getFloat(o));
                        else if (type.equals(long.class))
                            editor.putLong(name, fields[i].getLong(o));
                        else if (type.equals(Boolean.class))
                            editor.putBoolean(name, fields[i].getBoolean(o));
    
                    } catch (IllegalAccessException e) {
                        LogUtils.e(TAG, e);
                    } catch (IllegalArgumentException e) {
                        LogUtils.e(TAG, e);
                    }
                } else {
                    // FIXME 是对象则不写入
                }
            }
    
            return editor.commit();
        }
    

    https://github.com/AltasT/PreferenceVObjectFile/blob/master/PreferenceVObjectFile/src/com/altas/lib/PreferenceUtils.java

    0 讨论(0)
  • 2020-11-22 14:31

    You haven't stated what you do with the prefsEditor object after this, but in order to persist the preference data, you also need to use:

    prefsEditor.commit();
    
    0 讨论(0)
  • 2020-11-22 14:33

    I had trouble using the accepted answer to access Shared Preference data across activities. In these steps, you give getSharedPreferences a name to access it.

    Add the following dependency in the build.gradel (Module: app) file under Gradle Scripts:

    implementation 'com.google.code.gson:gson:2.8.5'
    

    To Save:

    MyObject myObject = new MyObject;
    //set variables of 'myObject', etc.
    
    SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
    
    Editor prefsEditor = mPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(myObject);
    prefsEditor.putString("Key", json);
    prefsEditor.commit();
    

    To Retrieve in a Different Activity:

    SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);
    
    Gson gson = new Gson();
    String json = mPrefs.getString("Key", "");
    MyObject obj = gson.fromJson(json, MyObject.class);
    
    0 讨论(0)
提交回复
热议问题