Chris
Chris

Reputation: 4364

SharedPreferences returning empty string

In my LoginActivity I'm setting a preference to identify the user is logged in and then I switch to the WelcomeActivity.

            Log.v("onPostExecute", "Login successful");
            // save login session in SharedPreferences
            SharedPreferences settings = getSharedPreferences("LOGIN", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("email", email);
            editor.commit();

            Intent welcomeIntent = new Intent(getApplicationContext(), WelcomeActivity.class);
            startActivity(welcomeIntent);

In my launcher activity (RegisterActivity) I'm checking in onCreate for possible settings, so that the user is redirect automatically.

    // redirect to welcomeActivity if user is logged in
    SharedPreferences settings = getSharedPreferences("EMAIL", 0);
    String email = settings.getString("email", "");
    if (!email.isEmpty()) {
        Intent welcomeIntent = new Intent(getApplicationContext(), WelcomeActivity.class);
        startActivity(welcomeIntent);           
    }

email is always empty, so the user, who logged in before and restarted the app is not automatically redirected. Any idea why?

Upvotes: 0

Views: 1305

Answers (4)

engr. Sheraz Khan
engr. Sheraz Khan

Reputation: 54

Replace this line

SharedPreferences settings = getSharedPreferences("LOGIN", 0);

with this

SharedPreferences settings = getSharedPreferences("LOGIN", MODE_PRIVATE);

and use same name to get it Like

Replace this line

SharedPreferences settings = getSharedPreferences("EMAIL", 0);

with this

SharedPreferences settings = getSharedPreferences("LOGIN", MODE_PRIVATE);

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157487

you are writing in two different files

SharedPreferences settings = getSharedPreferences("LOGIN", 0);
 SharedPreferences settings = getSharedPreferences("EMAIL", 0);

those two line will create two different xml files, one called LOGIN and the other EMAIL

Upvotes: 2

tyczj
tyczj

Reputation: 74066

because this

getSharedPreferences("LOGIN", 0);

is not this

getSharedPreferences("EMAIL", 0);

you are using 2 different sharedpreferences

Upvotes: 1

Christopher Francisco
Christopher Francisco

Reputation: 16298

In LoginActivity you're using "LOGIN":

SharedPreferences settings = getSharedPreferences("LOGIN", 0);

In RegisterActivity you're using "EMAIL":

SharedPreferences settings = getSharedPreferences("EMAIL", 0);

Use the same on both

Upvotes: 1

Related Questions