sharedpreferences 得到错误的布尔值
sharedpreferences getting wrong boolean value
我想为布尔值检查创建一个 sharedpreferences,但值总是 return false。如何 return sharedpreferences 的正确布尔值?
下面是我的代码
public boolean getBtnState(Context context,String text)//edit to store url here and check the boolean here
{
SharedPreferences prefs;
prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String favUrl = getPrefsFavUrl(context);
boolean switchState = false;
if(favUrl == text) {
switchState=true;
}
return switchState;//always return false here
}
这是获取 sharedpreferences 值的代码
@Override
public Object instantiateItem(final ViewGroup container, final int position) {
showProgress();
imageView = (ImageView) findViewById(R.id.btn_favourite);
Boolean stateBtnNow=sharedPreference.getBtnState(context,mUrl);
if(stateBtnNow) {
imageView.setColorFilter(Color.argb(255, 249, 0, 0));//red
}
else
{
imageView.setColorFilter(Color.argb(255, 192, 192, 192));
}
使用
if(favUrl.equals(text)){
switchState = true;
}
而不是
if(favUrl == text) {
switchState=true;
}
您正在使用 ==
运算符比较两个 String
变量,而不是使用 .equals()
方法。
if(favUrl.equals(text)) {
switchState=true;
}
它会起作用。
==
和 equals()
参考 This Question。
您可以将代码简化为:
public boolean getBtnState(Context context,String text) { //edit to store url here and check the boolean here
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
return getPrefsFavUrl(context).equals(text); // fixed and simplified code
}
我想为布尔值检查创建一个 sharedpreferences,但值总是 return false。如何 return sharedpreferences 的正确布尔值?
下面是我的代码
public boolean getBtnState(Context context,String text)//edit to store url here and check the boolean here
{
SharedPreferences prefs;
prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String favUrl = getPrefsFavUrl(context);
boolean switchState = false;
if(favUrl == text) {
switchState=true;
}
return switchState;//always return false here
}
这是获取 sharedpreferences 值的代码
@Override
public Object instantiateItem(final ViewGroup container, final int position) {
showProgress();
imageView = (ImageView) findViewById(R.id.btn_favourite);
Boolean stateBtnNow=sharedPreference.getBtnState(context,mUrl);
if(stateBtnNow) {
imageView.setColorFilter(Color.argb(255, 249, 0, 0));//red
}
else
{
imageView.setColorFilter(Color.argb(255, 192, 192, 192));
}
使用
if(favUrl.equals(text)){
switchState = true;
}
而不是
if(favUrl == text) {
switchState=true;
}
您正在使用 ==
运算符比较两个 String
变量,而不是使用 .equals()
方法。
if(favUrl.equals(text)) {
switchState=true;
}
它会起作用。
==
和 equals()
参考 This Question。
您可以将代码简化为:
public boolean getBtnState(Context context,String text) { //edit to store url here and check the boolean here
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
return getPrefsFavUrl(context).equals(text); // fixed and simplified code
}