我有这段代码:
public class Register extends Activity {
private LinearLayout layout;
private TextView debug;
public static final String USER_CONFIG = "UserConfigs";
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
SharedPreferences settings = getSharedPreferences(USER_CONFIG, MODE_PRIVATE);
boolean registered = settings.getBoolean("registered", false);
layout = (LinearLayout) findViewById(R.id.layoutRegister);
if (!registered) {
debug = new TextView(this);
debug.setText("You have to register");
layout.addView (debug);
//TO DO user registration
settings.edit().putBoolean("registered", true);
settings.edit().commit();
} else {
debug = new TextView(this);
debug.setText("You have already registered");
layout.addView (debug);
//TO DO skip to next screen
}
}
}
但是当我重新启动应用程序时,我总是被注册为“false”。我也尝试在onStop()
上提交它并获得相同的结果。我在这里看到了这个问题的其他主题,但没有一个与我有同样的问题。
有什么想法吗?
答案 0 :(得分:20)
你不能这样做:
settings.edit().putBoolean("registered", true);
settings.edit().commit();
您需要获取编辑器对象,然后进行更改:
Editor editor = settings.edit();
editor.putBoolean(...);
editor.commit();
答案 1 :(得分:2)
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
Editor edit = prefs.edit();
edit.putBoolean("registered", true);
edit.commit();
使用此
答案 2 :(得分:0)
其他答案也是正确的。
您也可以使用此
settings.edit().putBoolean("registered", true).commit();