TheBlueCat
TheBlueCat

Reputation: 1195

SharedPreferences not working

I'm saving two strings fro another activity, when the user logs in, so I can save their data to use another time (Ease of use for the end user). Anyway, I've set up the code and ran it and the strings are not being passed. To make sure, the sharedPreferences are working, I've set up a toast, to see if it matches the info I imputed.

1 Class:

uname = (EditText) findViewById(R.id.txt_username);
        String username = uname.getText().toString();

        pword = (EditText) findViewById(R.id.txt_password);
        String password = pword.getText().toString();

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("key1", username);
        editor.putString("key2", password);
        editor.commit();

2nd class:

private void Test() {
        // TODO Auto-generated method stub
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        String username = settings.getString("key1", null);
        String password = settings.getString("key2", null);
         if(username.equals("irock97")) {
            Toast.makeText(getApplicationContext(), "yaya", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
        }
}

Upvotes: 0

Views: 233

Answers (3)

Marcos
Marcos

Reputation: 4643

Remember:

== tests for reference equality.

equals tests for value equality.

so change

if(username =="irock97")

and use:

if(username.equals("irock97")) 

But beware of nulls!

"==" handles null strings fine, but calling ".equals" from a null string will cause an exception:

String s1 = null;
String s2 = null;

s1 == s2; // ok, it's true
s1.equals(s2); // throws an exception !

EDIT: You need to call show()

Toast.makeText(getApplicationContext(), "yaya", Toast.LENGTH_SHORT).show();

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117589

Replace:

username == "irock97"

with:

username.equals("irock97")

== is used to check if the 2 string references refer to the same object in the memory.

equals() is used to check if the 2 string references refer to the same object or 2 different objects with the same string value.

Besides that, you need to check if the string reference is not null first:

if(username != null && username.equals("irock97"))

EDIT:

Also, you forgot to call show() method to show the Toast:

Toast.makeText(getApplicationContext(), "yaya", Toast.LENGTH_SHORT).show();

Upvotes: 1

user
user

Reputation: 87064

Instead of :

if(username =="irock97")

use:

if(username.equals("irock97"))

to test for String equality. With == you are testing for object reference equality.

Upvotes: 1

Related Questions