共享偏好问题

时间:2011-05-10 04:30:33

标签: android sharedpreferences

我对此共享偏好的工作原理感到困惑。我根据共享偏好从网站上获得了示例代码。我的问题是,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中打印更新的值。但仍然两个textviews都打印相同的默认值为'0'。因此,如果我重新启动应用程序,则会更新两个文本视图。 如何解决这个问题呢。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

只需替换

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

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

答案 1 :(得分: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.");
}

答案 2 :(得分:0)

试试这个 对于sharedPreferences中的商店值..

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

获取价值

prefs.getInt("Value",0);