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

后端 未结 20 2743
野趣味
野趣味 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 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);
    

提交回复
热议问题