Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App keeps forgetting sharedpreferences on restart

I don't know what to do with it any more

Seems to be working fine with android 3.0 and higher, but on android 2.3.3 every time I launch the application it is asking for the username/password again.

I'm using the shared preferences.

Here is how I save preferences:

        SharedPreferences preferences = MyApplication.getAppContext().getSharedPreferences("athopbalance", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("username", username).commit();
        editor.putString("password", password).commit();

And here is how I read them:

    SharedPreferences preferences = MyApplication.getAppContext().getSharedPreferences("athopbalance", Context.MODE_PRIVATE);
    String username = preferences.getString("username", "");
    String password = preferences.getString("password", "");

I also tried to save preferences using this code:

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("username", username).commit();
        editor.putString("password", password).commit();

And the read them with this code:

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
    String username = preferences.getString("username", "");
    String password = preferences.getString("password", "");

But it doesn't work either.

The problem is before I restart the application I can see that they are still there. However as soon as I do the restart - I end up with getting "" (empty string) for username and "" for password.

Any ideas would be greatly appreciated

like image 337
Vlad Spreys Avatar asked Mar 03 '13 06:03

Vlad Spreys


1 Answers

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() called");
    }

    public MyApplication() {
        super();
        Log.d(TAG, "Constructor called");
        instance = this;
    }


    public static MyApplication getApplication() {
        if (instance == null) {
            instance = new MyApplication();
        }
        return instance;
    }
}

And usage:

MyApplication.getApplication().getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE)
like image 116
agamov Avatar answered Oct 06 '22 23:10

agamov