繁体   English   中英

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

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

如果我在内部修改默认的sharedPreferences文件,则不会出现SharedPreferences值。 但是,如果我要关闭和打开应用程序,那么它将正常进行。

由于某些要求,我将sharedPreferences文件存储在Google驱动器中。 之后,我使用相同的Google帐户在其他设备中还原了相同的sharedPreferences数据,所有xml数据都正常了。 但是在sharedPreferences对象中,这些值没有刷新。 但是,在关闭和打开应用程序值时会很好。

如何在不关闭应用程序的情况下刷新sharedPreferences?

以下是我在默认文件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缓存值,因此不需要每次都访问磁盘。 该文档明确指定您仅应通过Editor写入首选项文件,否则会出现意外行为:

对首选项的修改必须通过SharedPreferences.Editor对象,以确保首选项值保持一致状态并控制将它们提交到存储时的状态。 从各种get方法返回的对象必须被应用程序视为不可变的。

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

暂无
暂无

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

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