2017-03-16 123 views
-1

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

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

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"; 
+0

也在这里?返回getSharedPreferences(ctx).getString(PREF_USER_NAME,“username”); return getSharedPreferences(ctx).getString(PREF_PROPIC,“propic”); – APX

+0

@APX你是什么意思“也在这里?” – Sweeper

+0

在我上面的2条返回线上,当我得到用户和配置文件的值时,theres“”在最后我应该放哪里? – APX