21

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 on the sd card no matter where is the file located. Is there any way to do this?

Elad92
  • 2,471
  • 4
  • 22
  • 36

4 Answers4

53

The SharedPreferences interface contains a method called getAll() which returns a map with the key-value pairs. So instead of copying the file itself, I just serialize the map that being returned from this method and then retrieve it back afterwards.

Some code:

private boolean saveSharedPreferencesToFile(File dst) {
    boolean res = false;
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(new FileOutputStream(dst));
        SharedPreferences pref = 
                            getSharedPreferences(prefName, MODE_PRIVATE);
        output.writeObject(pref.getAll());

        res = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if (output != null) {
                output.flush();
                output.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return res;
}

@SuppressWarnings({ "unchecked" })
private boolean loadSharedPreferencesFromFile(File src) {
    boolean res = false;
    ObjectInputStream input = null;
    try {
        input = new ObjectInputStream(new FileInputStream(src));
            Editor prefEdit = getSharedPreferences(prefName, MODE_PRIVATE).edit();
            prefEdit.clear();
            Map<String, ?> entries = (Map<String, ?>) input.readObject();
            for (Entry<String, ?> entry : entries.entrySet()) {
                Object v = entry.getValue();
                String key = entry.getKey();

                if (v instanceof Boolean)
                    prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
                else if (v instanceof Float)
                    prefEdit.putFloat(key, ((Float) v).floatValue());
                else if (v instanceof Integer)
                    prefEdit.putInt(key, ((Integer) v).intValue());
                else if (v instanceof Long)
                    prefEdit.putLong(key, ((Long) v).longValue());
                else if (v instanceof String)
                    prefEdit.putString(key, ((String) v));
            }
            prefEdit.commit();
        res = true;         
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }finally {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return res;
}

I hope that I helped someone, and if something here is wrong please tell me.

Elad

Elad92
  • 2,471
  • 4
  • 22
  • 36
  • Can you plz tell why iam having this issue when using your code: http://stackoverflow.com/questions/23535545/android-cannot-use-entry-entryset – Dev01 May 08 '14 at 07:40
  • Entry entry give me : "The type DropBoxManager.Entry is not generic; it cannot be parameterized with arguments " – Matan Sep 02 '14 at 20:58
  • Thank you, this was a lot harder than I expected. This solution was the best. I had to modify it a little for file handling but it works like a charm. – midiwriter Sep 06 '16 at 03:03
  • Would be nice if you post your working code too to help out others and not to keep it for yourself. – Frank Oct 30 '17 at 03:13
4
File ff = new File("/data/data/"
                            + MainActivity.this.getPackageName()
                            + "/shared_prefs/pref file name.xml");

                    Log.i("ddddddddddddd", ff.getPath() + "");

                    copyFile(ff.getPath().toString(), sdcard path/save file name.xml");

private void copyFile(String filepath, String storefilepath) {
    try {
        File f1 = new File(filepath);
        File f2 = new File(storefilepath);
        InputStream in = new FileInputStream(f1);

        OutputStream out = new FileOutputStream(f2);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        System.out.println("File copied.");
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());

    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

}
  • 1
    This is a good way to get an exact copy of the xml file, but maybe is a better way not to hardcode /data path, use Context.getFilesDir().getPath() – Pelanes Oct 16 '15 at 10:45
3

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<String, ?> entries = XmlUtils.readMapXml(input);
        for (Entry<String, ?> 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.

Graeme Gill
  • 626
  • 5
  • 11
0
try {
    input = new FileInputStream(src1);
    SharedPreferences.Editor prefEdit =   getSharedPreferences("prueba100", MODE_PRIVATE).edit();
    prefEdit.clear();
    Map<String, ?> entries = XmlUtils.readMapXml(input);
    for (Map.Entry<String, ?> entry : entries.entrySet()) {
        putObject(prefEdit, entry.getKey(), entry.getValue());
    }
    prefEdit.apply();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (XmlPullParserException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Adriano
  • 11
  • 1
    Code-only answers are frowned upon in SO. Please include an explanation of how your code answers the question. Also, please format the code by placing 4 spaces at the beginning of each code line. – Kelly Keller-Heikkila Jan 12 '16 at 16:12