Android开发中的共享首选项

时间:2017-03-16 07:49:06

标签: android login get set sharedpreferences

我的共享首选项有问题,我有两个活动,这是我的共享首选项的代码。

public class SaveSharedPreferences {

static final String PREF_USER_NAME= "";
static final String PREF_PROPIC= "";

static SharedPreferences getSharedPreferences(Context ctx) {
    return PreferenceManager.getDefaultSharedPreferences(ctx);
}

public static void setUserName(Context ctx, String userName)
{
    SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
    editor.putString(PREF_USER_NAME, userName);
    editor.commit();
}

public static String getUserName(Context ctx)
{
    return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}

public static void setProfile(Context ctx, String profile)
{
    SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
    editor.putString(PREF_PROPIC, profile);
    editor.commit();
}

public static String getProfile(Context ctx)
{
    return getSharedPreferences(ctx).getString(PREF_PROPIC, "");
}

public static void clearPrefs(Context ctx){
    SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
    editor.clear();
    editor.commit();
}

}

每当我登录我的主要活动到下一个活动时,我总是会将字符串值添加到“PREF_USER_NAME”并按照您的上面所示进行存储。因此,当我成功登录时,我称之为“PREF_PROFILE”没有任何价值。但是当我打电话给它时,我获得的值是“PREF_USER_NAME”的值。这就是我的问题,我没有看到任何错误。所以有人可以帮助我,感谢您的意见和建议,谢谢!

1 个答案:

答案 0 :(得分:1)

SharedPreferences的工作方式是它使用键来标识您存储的不同值。在您的情况下,密钥为PREF_USER_NAMEPREF_PROPIC。问题是它们具有相同的值:

static final String PREF_USER_NAME= "";
static final String PREF_PROPIC= "";

这意味着它们本质上是相同的键。这就是您在使用PREF_PROPIC密钥时获得用户名的原因。

解决方案很简单。只需让它们成为不同的钥匙!

static final String PREF_USER_NAME= "username";
static final String PREF_PROPIC= "propic";
相关问题