【问题标题】:Shared Preferences on Android DevelopmentAndroid 开发的共同偏好
【发布时间】:2017-03-16 07:49:06
【问题描述】:

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

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”的值。所以这就是我的问题,我看不出有什么问题。所以有人可以帮助我,我感谢您的 cmets 和建议谢谢!

【问题讨论】:

    标签: android login get set sharedpreferences


    【解决方案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";
    

    【讨论】:

    • 也在这里? return getSharedPreferences(ctx).getString(PREF_USER_NAME, "username"); return getSharedPreferences(ctx).getString(PREF_PROPIC, "propic");
    • @APX “也在这里”是什么意思?
    • 当我获取用户和个人资料的值时,在上面的 2 个返回行中,最后有“”我应该放什么?
    • @APX 当找不到与给定键对应的值时,将返回您放入其中的任何内容。基本上,如果没有找到值,则返回默认值。阅读文档:developer.android.com/reference/android/content/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2019-06-20
    • 2012-10-24
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多