Export sharedPreferences to file

With the getAll function of sharedPreferences it is possible to save the shared preferences to a file. The following code example is probably the easyest way to do it. With the saveSharedPreferences method you can save all shared preferences a file to the root of your sdcard.

Make sure your App has the following permission. It allows the application to write to external storage.

 
/*
 Possible modes: 
 MODE_PRIVATE
 MODE_WORLD_READABLE
 MODE_WORLD_WRITEABLE
 MODE_MULTI_PROCESS
*/

/* Execute save SharedPreferences example code */
...
String name = "MyName";
int mode = MODE_PRIVATE;
File path = new File(Environment.getExternalStorageDirectory().toString());
File file = new File(path, "MySharedPreferences");
saveSharedPreferences (name, mode, file);
...


private void saveSharedPreferences(String name, int mode, File file)  
{
    SharedPreferences prefs = getSharedPreferences(name, mode);
    try
    {
        FileWriter fw = new FileWriter(file);
        PrintWriter pw = new PrintWriter(fw);
        Map prefsMap = prefs.getAll();
        for(Map.Entry entry : prefsMap.entrySet())
        {
            pw.println(entry.getKey() + ": " + entry.getValue().toString());            
        }
        pw.close();
        fw.close();
    }
    catch (Exception e)
    {
        Log.wtf(getClass().getName(), e.toString());
    }
}