我對這個共享首選項的工作原理有點困惑。我有一個基於共享偏好的網站示例代碼。我的問題是,editor.commit()不會立即更新。下面是我的示例代碼,共享首選項的問題
public class PreferencesDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);
// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
TextView text1 = (TextView) findViewById(R.id.text1);
text.setText("This app has been started " + counter + " times.");
// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", counter+2);
editor.apply();
editor.commit(); // Very important
text1.setText("This app has been started " + counter + " times.");
}
}
正如你所看到的,我有計數器,它的值,我將在第一的TextView和COMMIT語句之後我打印在接下來的TextView更新後的值。但是這兩個文本瀏覽器仍然打印出與'0'相同的默認值。所以,如果我重新啓動應用程序,兩個文字瀏覽都會更新。 如何解決這個問題。任何幫助表示讚賞。
謝謝,我錯過了這行'prefs.getInt(「Value」,0); ' – 2011-05-10 04:47:22
最受歡迎,親愛的 – 2011-05-10 04:48:31