How to serialize a Bundle?

后端 未结 4 632
青春惊慌失措
青春惊慌失措 2020-12-03 07:12

I\'d like to serialize a Bundle object, but can\'t seem to find a simple way of doing it. Using Parcel doesn\'t seem like an option, since I want to store the serialized dat

4条回答
  •  悲哀的现实
    2020-12-03 07:47

    Convert it to SharedPreferences:

    private void saveToPreferences(Bundle in) {
        Parcel parcel = Parcel.obtain();
        String serialized = null;
        try {
            in.writeToParcel(parcel, 0);
    
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.write(parcel.marshall(), bos);
    
            serialized = Base64.encodeToString(bos.toByteArray(), 0);
        } catch (IOException e) {
            Log.e(getClass().getSimpleName(), e.toString(), e);
        } finally {
            parcel.recycle();
        }
        if (serialized != null) {
            SharedPreferences settings = getSharedPreferences(PREFS, 0);
            Editor editor = settings.edit();
            editor.putString("parcel", serialized);
            editor.commit();
        }
    }
    
    private Bundle restoreFromPreferences() {
        Bundle bundle = null;
        SharedPreferences settings = getSharedPreferences(PREFS, 0);
        String serialized = settings.getString("parcel", null);
    
        if (serialized != null) {
            Parcel parcel = Parcel.obtain();
            try {
                byte[] data = Base64.decode(serialized, 0);
                parcel.unmarshall(data, 0, data.length);
                parcel.setDataPosition(0);
                bundle = parcel.readBundle();
            } finally {
                parcel.recycle();
            }
        }
        return bundle;
    }
    

提交回复
热议问题