SharedPreferences in Android

2019-09-07 15:37发布

问题:

I have used SharedPreferences to save some details in the Main Activity .Now i want to get the details in some other activity but i am not able to get them .

Code to save

public void saveInformation(String username,String password) {
        SharedPreferences shared = getSharedPreferences("shared", MODE_PRIVATE);
        SharedPreferences.Editor editor = shared.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        editor.commit();
    }

Code to get

SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String username = prefs.getString("username", null);

But this is not working for me . How could I get his?

回答1:

Code to get should be

SharedPreferences prefs = getSharedPreferences("shared", MODE_PRIVATE);


回答2:

May this help you:

Buddy Change these lines in your code to get:

SharedPreferences prefs = getSharedPreferences("shared", MODE_PRIVATE); 
String username = prefs.getString("username","");