Reputation: 3225
I have this code:
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
}
}
}
But I'm always getting registered as "false" when I restart my app. I have tried to commit it on the onStop()
as well and got the same result. I have seen other topics with this problem here but none of them had the same problem as I do.
Any ideas?
Upvotes: 6
Views: 7445
Reputation: 46415
You can't do this:
settings.edit().putBoolean("registered", true);
settings.edit().commit();
You need to get the editor object, then make the changes:
Editor editor = settings.edit();
editor.putBoolean(...);
editor.commit();
Upvotes: 20
Reputation: 7708
The other answers are also correct.
You can also use this
settings.edit().putBoolean("registered", true).commit();
Upvotes: 0
Reputation: 10856
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
Editor edit = prefs.edit();
edit.putBoolean("registered", true);
edit.commit();
use this
Upvotes: 2