Android - SharedPreferences with serializable object

前端 未结 6 1707
死守一世寂寞
死守一世寂寞 2020-11-29 01:55

I know that SharedPreferences has putString(), putFloat(), putLong(), putInt() and putBoolean(). But I need

6条回答
  •  天命终不由人
    2020-11-29 02:19

    It is possible to do it without a file.

    I'm serializing the information to base64 and like this I'm able to save it as a string in the preferences.

    The following code is Serializing a serializable objec to base64 string and vice versa: import android.util.Base64;

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    
    public class ObjectSerializerHelper {
        static public String objectToString(Serializable 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;
        }
    
        @SuppressWarnings("unchecked")
        static public Serializable stringToObject(String string){
            byte[] bytes = Base64.decode(string,0);
            Serializable object = null;
            try {
                ObjectInputStream objectInputStream = new ObjectInputStream( new ByteArrayInputStream(bytes) );
                object = (Serializable)objectInputStream.readObject();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (ClassCastException e) {
                e.printStackTrace();
            }
            return object;
        }
    
    }
    

提交回复
热议问题