简体   繁体   中英

SharedPreferences values are not coming if i am modifying default SharedPreferences file internally

SharedPreferences values are not coming if I am modifying default sharedPreferences file internally. But if I am closing and opening application then its coming fine.

Because of some requirement, I am storing sharedPreferences file in google drive. After that I am restoring same sharedPreferences data in other device using same google account, all xml data is coming fine. But in sharedPreferences object those values are not refreshing. But while closing and opening application values are coming fine.

How to refresh sharedPreferences without application close?

Below is my method for writing sharedPreferences file in default file pathstrong text.

private void restore(Context ctx, InputStream myInputs, String path) {
  OutputStream myOutput;

  try {
     myOutput = new FileOutputStream(path);

     byte[] buffer = new byte[1024];
     int length;
     while ((length = myInputs.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
     }

     // Close and clear the streams
     myOutput.flush();
     myOutput.close();
     myInputs.close();
     googleDriveBackUpActivity.setBackUpInfo();
     Toast.makeText(ctx, R.string.successfully_restored_from_google_drive, Toast.LENGTH_SHORT).show();

  } catch (IOException e) {
     e.printStackTrace();
  }
}

SharedPreferences caches values so that it doesn't need to hit the disk every time. The documentation clearly specifies that you should only write to the preference file via the Editor or you'll get unexpected behavior:

Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get methods must be treated as immutable by the application.

Instead of just overwriting the default file, instead try reading the xml from your file and writing it back into the app's shared preferences via the Editor to sync the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM