Android Shared Preferences Backed Up

I have been looking around for some way to back up the preferences in my Android app – just a simple serialization of the SharedPreferences object. Here are some code snips from my backup object that allowed me to get the job done:

private void importSharedPreferences()
{
  SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
  File myPath = new File(EXPORT_FILE_PATH);
  File myFile = new File(myPath, PREFS_FILE_NAME);
  if(myFile.exists())
	{
		BufferedReader i = new BufferedReader(new InputStreamReader(new FileInputStream(EXPORT_FILE_PATH + PREFS_FILE_NAME), "UTF8"));
		String line;

		while ((line = i.readLine()) != null)
		{
				String[] pair = line.split(":");

				SharedPreferences.Editor prefEdit = prefs.edit();

				if(pair[2].indexOf("Boolean")>-1)
				{
					prefEdit.putBoolean(pair[0], Boolean.parseBoolean(pair[1]));
				}
				else if(pair[2].indexOf("Integer")>-1)
				{
					prefEdit.putInt(pair[0], Integer.parseInt(pair[1]));
				}
				else if(pair[2].indexOf("Float")>-1)
				{
					prefEdit.putFloat(pair[0], Float.parseFloat(pair[1]));
				}
				else if(pair[2].indexOf("Long")>-1)
				{
					prefEdit.putLong(pair[0], Long.parseLong(pair[1]));
				}
				else if(pair[2].indexOf("String")>-1)
				{
					prefEdit.putString(pair[0], pair[1]);
				}

				prefEdit.commit();
			}
	}
}
public void exportSharedPreferences()
{
    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);

    File myPath = new File(EXPORT_FILE_PATH);
    File myFile = new File(myPath, PREFS_FILE_NAME);

    FileWriter fw = new FileWriter(myFile);
    PrintWriter pw = new PrintWriter(fw);

    Map<String,?> prefsMap = prefs.getAll();

    for(Map.Entry<String,?> entry : prefsMap.entrySet())
    {
    		pw.println(entry.getKey() + ":" + entry.getValue().toString() + ":" + entry.getValue().getClass());
    }

    pw.close();
    fw.close();
}

I removed all of the error handling and might have messed up the formatting a bit, but you get the idea. Also, I plan on moving the serialization to a XML format in the next few days instead of the janky colon-separated bit. Hope this is helpful to you!

One thought on “Android Shared Preferences Backed Up

Leave a Reply

Your email address will not be published. Required fields are marked *