Backup/restore shared preferences android
Asked Answered
S

4

6

I'm trying to backup/restore shared preferences of my app, I followed this step using Android Backup Service:

In Manifest.xml in <application> tag

<meta-data android:name="com.google.android.backup.api_key" android:value="My Key" />

added this class:

public class MyBackupAgent extends BackupAgentHelper {

    // The name of the SharedPreferences file
    static final String PREFS = "my_preferences";


    @Override
    public void onCreate() {
        SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
        addHelper(Utilities.SETTINGS_KEY, helper);
    }

}

when set value to shared preference I do this:

BackupManager backupManager = new BackupManager(context);
backupManager.dataChanged();

But if I uninstall/reinstall app, changes doesn't apply...

Sift answered 22/6, 2017 at 18:19 Comment(3)
I think you need to also have android:allowBackup="true" in your <activity> tag in AndroidManifestRuder
It wasn't clear from your description. But can you check if you have this in your Manifest <manifest ... > <application android:label="MyApplication" android:backupAgent="MyBackupAgent"> </application> </manifest>Esma
@Esma already do!Sift
A
4

My guess is you forgot to add

android:allowBackup="true"

inside your <application> tag in the AndroidManifest.xml file

Anthropoid answered 30/6, 2017 at 20:31 Comment(1)
No, I've added thisSift
B
2

You have to allocate a helper and add it to the backup agent like this:

    @Override
public void onCreate() {
    FileBackupHelper helper = new FileBackupHelper(this,
            TOP_SCORES, PLAYER_STATS);
    addHelper(FILES_BACKUP_KEY, helper);
}

and also consider overriding onBackup() and onRestore() methods. See explanation here: https://developer.android.com/guide/topics/data/keyvaluebackup.html#BackupAgentHelper

Boltzmann answered 1/7, 2017 at 10:47 Comment(0)
B
1

when you call dataChanged() you just notify system that something is changed, it does not start backup in this moment, give it some time and wi fi connection. Check in your device's settings under 'Backup and reset' if 'automatic restore' is set.

Make sure that you writing to the same preferences (with the same key) which you are saving context.getSharedPreferences("my_preferences", Context.MODE_PRIVATE);

Byrne answered 22/6, 2017 at 18:40 Comment(0)
H
0

I assume you have setting something like this (depends on android version and even on the device)

"Cloud and Accounts"->"Backup and Restore"->"Automatic restoration"

turned on. If not, turning it on may solve your problem.

Hauptmann answered 20/12, 2019 at 11:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.