sharedpreferences得到错误的布尔值

时间:2016-01-29 07:48:50

标签: android android-sharedpreferences

我想为布尔值检查创建一个sharedpreferences,但该值总是返回false。如何为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));
         } 

3 个答案:

答案 0 :(得分:1)

您正在将两个String变量与==运算符进行比较,而不是使用.equals()方法。

if(favUrl.equals(text)) {
    switchState=true;
}

它会起作用。

请参阅== equals() <?php header('Content-Type: application/json'); $lala = 'gender_male'; $lele = 'gender_female'; $con = mysqli_connect("127.0.0.1","root","imnoob","csv_db"); // Check connection if (mysqli_connect_errno($con)) { echo "Failed to connect to DataBase: " . mysqli_connect_error(); }else { $data_points = array(); $data_points1 = array(); $result = mysqli_query($con, "SELECT * FROM centurysq2012"); while($row = mysqli_fetch_array($result)) { $point = array("x" => $row['weekid'] , "y" => $row[$lala]); $point1 = array("x" => $row['weekid'], "y" => $row[$lele]); array_push($data_points, $point); array_push($data_points1, $point1); } echo json_encode($data_points, JSON_NUMERIC_CHECK); echo json_encode($data_points1, JSON_NUMERIC_CHECK); } mysqli_close($con); ?>

答案 1 :(得分:0)

使用

if(favUrl.equals(text)){
    switchState = true;
}

而不是

if(favUrl == text) {
    switchState=true;
}

答案 2 :(得分:0)

您可以将代码简化为:

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
}