1

I am using SharedPreference in one of my activity and I want to reference the same in another activity and fetch its value. I am doing so as follows:

Class 1

Class Level Variables:

String PREFS_NAME = "Login"; 
SharedPreferences sp;

Setting a value to the SharedPreference

public void savePref(String key, boolean value) {
        SharedPreferences sp = getSharedPreferences(PREFS_NAME,0);
        Editor edit = sp.edit();
        edit.putBoolean("loggdin", value);
        edit.commit();
        Toast.makeText(getApplicationContext(), "Login = " + value,
                Toast.LENGTH_LONG).show();

    }

Class 2

Class level Variables:

SharedPreferences sp;
String PREFS_NAME = "Login"; 

In onCreate: (Please also check the comments)

SharedPreferences sp = getSharedPreferences(PREFS_NAME,0);
        boolean channel = (sp.getBoolean("loggdin", true));// I get the value true or false depending on what I pass as a second argument here, pretty confused! 
        if (channel == true){
            Toast.makeText(getApplicationContext(), "true"+channel, 10000).show(); 
        }else {
            Toast.makeText(getApplicationContext(), "false"+channel, 10000).show(); 
        }

Unable to understand where I am going wrong, any hints?

4

2 回答 2

1

您是否尝试通过调试应用程序进行检查?

于 2013-10-08T07:32:08.420 回答
0

试试这个我的工作代码..

public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
    SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
    return preferences.getBoolean(key, false);
}//getPWDFromSP()


public static void saveBooleanInSP(String key, boolean value){
    SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor =      preferences.edit();
    editor.putBoolean(key, value);
    editor.commit();
}//savePWDInSP()
于 2013-10-08T07:18:49.850 回答