I would like to backup a value in SharedPreferences so that I can read out this value after a reinstall.
My code does not work and I do not know what is the mistake
Your backup agent class for SharedPreferences should be something like this:
public class MyPrefsBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS = "user_preferences";
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "prefs";
// Allocate a helper and add it to the backup agent
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
Then, you must request a cloud backup (it will be done async) with something like:
import android.app.backup.BackupManager;
...
public void requestBackup() {
BackupManager bm = new BackupManager(this);
bm.dataChanged();
}
and you don't need to manually restore your SharedPreferences as they are automagically managed by the SharedPreferencesBackupHelper class.
Besides your backup API key, don't forget to add your backup agent class in your manifest:
<application android:label="MyApplication"
android:backupAgent="MyBackupAgent">
More info about all this at http://developer.android.com/guide/topics/data/backup.html and http://developer.android.com/training/cloudsync/backupapi.html