Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences doesn't save value

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?

like image 939
João Menighin Avatar asked Nov 08 '12 11:11

João Menighin


People also ask

Is shared preference deprecated?

Yes, many preferemces-related areas were fragmented so it makes sense to move them to a support library. getDefaultSharedPreferences() implementation itself is still the same in both Android platform and AndroidX libraries, so that function did not really need deprecation.

How do you retrieve a value from SharedPreferences?

getAll(): This method is used to retrieve all values from the preferences. getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences. getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences.

Is SQLite better than SharedPreferences?

With SQLite you use SQL language to create tables and then do insert, delete, update operations just like in any other database. But in case of shared preference you use just normal APIs provided by Android to write, read and update these values to a XML file.


1 Answers

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();
like image 51
cjk Avatar answered Oct 17 '22 01:10

cjk