简体   繁体   English

如果我在内部修改默认的SharedPreferences文件,则SharedPreferences值不会出现

[英]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. 如果我在内部修改默认的sharedPreferences文件,则不会出现SharedPreferences值。 But if I am closing and opening application then its coming fine. 但是,如果我要关闭和打开应用程序,那么它将正常进行。

Because of some requirement, I am storing sharedPreferences file in google drive. 由于某些要求,我将sharedPreferences文件存储在Google驱动器中。 After that I am restoring same sharedPreferences data in other device using same google account, all xml data is coming fine. 之后,我使用相同的Google帐户在其他设备中还原了相同的sharedPreferences数据,所有xml数据都正常了。 But in sharedPreferences object those values are not refreshing. 但是在sharedPreferences对象中,这些值没有刷新。 But while closing and opening application values are coming fine. 但是,在关闭和打开应用程序值时会很好。

How to refresh sharedPreferences without application close? 如何在不关闭应用程序的情况下刷新sharedPreferences?

Below is my method for writing sharedPreferences file in default file pathstrong text. 以下是我在默认文件pathstrong文本中编写sharedPreferences文件的方法。

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. SharedPreferences缓存值,因此不需要每次都访问磁盘。 The documentation clearly specifies that you should only write to the preference file via the Editor or you'll get unexpected behavior: 该文档明确指定您仅应通过Editor写入首选项文件,否则会出现意外行为:

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. 对首选项的修改必须通过SharedPreferences.Editor对象,以确保首选项值保持一致状态并控制将它们提交到存储时的状态。 Objects that are returned from the various get methods must be treated as immutable by the application. 从各种get方法返回的对象必须被应用程序视为不可变的。

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. 与其尝试覆盖默认文件,不如尝试从文件中读取xml,然后通过Editor将其写回到应用的共享首选项中,以同步值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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