我試圖將新值寫入共享首選項,似乎不工作,我錯過了什麼。Android共享首選項不更新
// this tests output
System.out.println("This OLD ID : "+oldPost+ " - NEW ID :"+postID);
// output : This OLD ID : 5233 - NEW ID :5216
///get old id
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String oldPost = prefs.getString("newsId", null);
if (oldPost.equals(postID))
{
System.out.println("This has been alerted : ");
}
else
{
System.out.println("This is something new : ");
//set old post to new post - does not seem to work
SharedPreferences.Editor editor = getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
editor.clear();
editor.putString("newsId", "" + oldPost);
editor.commit();
}
}
希望這是一個明顯的答案...在此先感謝。
檢查此問題[答案](http://stackoverflow.com/questions/18793903/android-sharedpreferences-update-does-not-work) –
如果不會有如果(oldPost.equals(postID))'會給你nullPointerException,所以你想要檢查它是否爲null,或者設置'oldPost'的默認值。 – miljon
當你第一次提供代碼newsId到您的SharedPreference。在上面的代碼中,您甚至在放置字符串之前應用了getString。 – tahsinRupam