2011-05-10 82 views
1

我對這個共享首選項的工作原理有點困惑。我有一個基於共享偏好的網站示例代碼。我的問題是,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'相同的默認值。所以,如果我重新啓動應用程序,兩個文字瀏覽都會更新。 如何解決這個問題。任何幫助表示讚賞。

回答

0

試試這個 在sharePreferences儲值..

SharedPreferences prefs = getSharedPreferences("Share", Context.MODE_PRIVATE); 
Editor editor = prefs.edit(); 
editor.putInt("Value", 1); 
editor.commit(); 

爲獲取價值

prefs.getInt("Value",0); 
+0

謝謝,我錯過了這行'prefs.getInt(「Value」,0); ' – 2011-05-10 04:47:22

+0

最受歡迎,親愛的 – 2011-05-10 04:48:31

0

只需更換

editor.putInt("counter", counter+2); 

counter+= 2; 
editor.putInt("counter", counter); 
0

您需要再次獲取計數器!

讓你從喜好

再次獲得價值反正apply()方法是基本相同commit()方法,所以你只需要調用它一次!區別僅在於apply方法是在後臺線程中提交更改的新方法,而不是主線程!

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.commit(); // Very important 
counter = app_preferences.getInt("counter", 0); //ADD THIS LINE! 
text1.setText("This app has been started " + counter + " times."); 
} 
+0

謝謝,我錯過了這條線prefs.getInt( 「值」,0) ; – 2011-05-10 05:06:06