[英]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.