How can I backup SharedPreferences to SD card?

前端 未结 4 940
盖世英雄少女心
盖世英雄少女心 2020-12-08 08:55

I saw in a lot of places that it\'s a problem to copy the SharedPreferences file to the sd card because every manufacturer place it somewhere else.

I want to backup

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 08:58

    An alternative to using ObjectOutputStream/ObjectInputStream is to add the XmlUtils.java and FastXmlSerializer.java files from the Android source to your project, and then use XmlUtils.writeMapXml() and XmlUtils.readMapXml():

    boolean res = false;
    FileOutputStream output = null;
    try {
        output = new FileOutputStream(dst);
        SharedPreferences pref = 
                            getSharedPreferences(prefName, MODE_PRIVATE);
        XmlUtils.writeMapXml(pref.getAll(), output);
    
        res = true;
        }
    

    .....

    FileInputStream input = null;
    try {
        input = new FileInputStream(src);
            Editor prefEdit = getSharedPreferences(prefName, MODE_PRIVATE).edit();
            prefEdit.clear();
            Map entries = XmlUtils.readMapXml(input);
            for (Entry entry : entries.entrySet()) {
                putObject(prefEdit, entry.getKey(), entry.getValue());
            }
        }
    

    .....

    static SharedPreferences.Editor putObject(final SharedPreferences.Editor edit,
                                              final String key, final Object val) {
        if (val instanceof Boolean)
            return edit.putBoolean(key, ((Boolean)val).booleanValue());
        else if (val instanceof Float)
            return edit.putFloat(key, ((Float)val).floatValue());
        else if (val instanceof Integer)
            return edit.putInt(key, ((Integer)val).intValue());
        else if (val instanceof Long)
            return edit.putLong(key, ((Long)val).longValue());
        else if (val instanceof String)
            return edit.putString(key, ((String)val));
    
        return edit;
    }
    

    The storage format will then be the same XML as is used to store the SharedPreferences.

提交回复
热议问题