Android Backup of ENTIRE SharedPreferences file

三世轮回 提交于 2020-02-28 08:38:31

问题


I have been trying to get the backup of my sharedpreferences file in my Android app working and so far it is not. I am using the simple Google code from the developer's guide. Below is the code for the MyPrefsBackup class.

public class MyPrefsBackup extends BackupAgentHelper {

    // The name of the SharedPreferences file

    static final String PREFS = "UserDB";

    // 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

  public  void onCreate() {

        SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
        addHelper(PREFS_BACKUP_KEY, helper);


    }

I think I have finally realized that the PREFS_BACKUP_KEY actually has to be the specific key that I stored the data under. I was just using "prefs" so I think that's why no data was being backed up. However, I am storing quite a bit of data in the SharedPreferences file so how can I go ahead and save the entire SharedPreferences files without specifiying every individual key. (some keys are generated by the app so I don't even know if they are in use until the user inputs their data).

I want to know is there a way to just tell the BackupHelper class to backup the entire SharedPreferences file?


回答1:


Example SharedPreferences

SharedPreferences preferences=getSharedPreferences("Test", getApplicationContext().MODE_MULTI_PROCESS)

Date For the Backup Folder

Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd_MMMM_yyyy HH_mm_ss");
            String strDate = sdf.format(c.getTime());

Export SharedPreferences

exportSH("Test.xml", strDate);

Exporting the SharedPreferences .xml File in a Folder to the Downloads directory

private void exportSH(String sh_name, String strDate){




        File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + 
                File.separator + "Backup Folder "+strDate+ 
                File.separator );

          boolean success = true;
           if (!sd.exists()) {
               success = sd.mkdir();
           }
           if (success) {

        File data = Environment.getDataDirectory();
       FileChannel source=null;
       FileChannel destination=null;
       String currentDBPath = "/data/"+ context.getPackageName() +"/shared_prefs/"+ sh_name;
       String backupDBPath = sh_name;
       File currentDB = new File(data, currentDBPath);
       File backupDB = new File(sd, backupDBPath);
       try {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
        } catch(IOException e) {
            e.printStackTrace();
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show();
        }
           }}

You can import the Files with small changes. Some people said that it won't work so easily but it does. Just make sure you create a empty Sharedpreferences File before you import, because otherwise it doesn't work.

You can do this for example

    SharedPreferences dummy = getSharedPreferences("dummy", getApplicationContext().MODE_MULTI_PROCESS);
                Editor editor = dummy.edit();
editor.putBoolean("asdf", true);

    editor.commit();

And if you import it on the same Layout where the SharedPreferences are used, you can use this to refresh

                        finish();
                        startActivity(getIntent());



回答2:


The key you pass to addHelper isn't the key you use inside your SharedPreferences. It's a key that identifies this particular helper from all the helpers you add. The SharedPreferencesBackupHelper backs up every value in each SharedPreferences file you tell it about.

If your SharedPreferences aren't being backed up, it's for a different reason. Check that the name of the SharedPreferences file is correct, and that you've specified your key correctly in the <meta-data> tag in your AndroidManifest.xml .




回答3:


Getting sharedpreference files backup was easy one. Please find the below example to understand much better:

SharedPreferences sharedPref = getSharedPreferences("EmpDetails", MODE_PRIVATE);
Editor prefEditor = sharedPref.edit();
prefEditor.putString("empName1", "valuelabs");
prefEditor.putString("empName2", "webmd");
prefEditor.commit();

So If you want to retrive backup for shared preference files, You need to use the below logic. Here you can access based on your key if the values are required.

public class MyPrefsBackup extends BackupAgentHelper {

    // The name of the SharedPreferences file
    static final String PREFS = "EmpDetails";
   // A key to uniquely identify the set of backup data
    static final String PREFS_BACKUP_KEY = "PREF";

  public  void onCreate() {

        SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
        addHelper(PREFS_BACKUP_KEY, helper)

    }
}



回答4:


This was a challenge for me to figure out, but I got it. Hopeful it'll be useful to someone. ~Ann :-)

ORY's answer will work, but you will need to exit the app completely in order for the new setting to load. This is an update of his method and a way to import the Sharepreference. Toasting will not show when restarting through this method. **Remember you will need to create a .xml file if none existed. This method used "transferFrom". You will also need to override the backpressed() to clear the activity as this will create layers of activities.

To execute:

importSH("App_settings.xml", "/TodoFolder/Backup/");

Method:

    private void importSH(String sh_name, String location){


          File sd = new File(Environment.getExternalStorageDirectory().
                  getAbsolutePath() +location);


         File data = Environment.getDataDirectory();
         FileChannel source=null;
         FileChannel destination=null;
         String currentDBPath = "/data/"+ ToDoListActivity.this.getPackageName() +"/shared_prefs/"+ sh_name;
         String backupDBPath = sh_name;
         File currentDB = new File(sd, backupDBPath);
         File backupDB = new File(data, currentDBPath);



             try {
                  source = new FileInputStream(currentDB).getChannel();
                  destination = new FileOutputStream(backupDB).getChannel();

                  destination.transferFrom(source, 0, source.size());
                  source.close();
                  destination.close();

 // Toast.makeText(this, "App need to exit to load new setting", Toast.LENGTH_SHORT).show(); //will not show when rebooting. Not sure how to fix it.

                  String value =shared.getString("Demo List",null);
                     if (value != null) {

                         shared.edit().remove("Demo List").commit(); //remove the item created by dummy SharedPreferences, as mention. 
                     } 

 //restartin app to original activity.
                     Intent mStartActivity = new Intent(ToDoListActivity.this, ToDoListActivity.class);
                       int mPendingIntentId = 123456;
                       PendingIntent mPendingIntent = PendingIntent.getActivity(ToDoListActivity.this, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
                       AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                       mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                       System.exit(0);

              } catch(IOException e) {
                  e.printStackTrace();
                  Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show();
              }

           }  


来源:https://stackoverflow.com/questions/6991355/android-backup-of-entire-sharedpreferences-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!