如何比较保存到共享首选项中的Int值

时间:2015-02-15 15:25:24

标签: android sharedpreferences

我试图创建等级评论并在等级图像旁边完成后显示等级评级。我的代码准备就绪并在完成级别后显示评级 我将得分值保存到共享首选项并检查值 这是代码

// adding value to cookies from First Activity 
Editor editor = sharedpreferences.edit(); editor.putInt("level1_rating",AllGlobalVariables.level_score ); editor.putInt("level2_rating",AllGlobalVariables.level2_score );
editor.commit(); 

// calling function in Second Activity
rating(AllGlobalVariables.level1);	


//------ function defination --------//

private void rating(String l) {
	// TODO Auto-generated method stub
		
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

		int left = 15;
		int top = 65;
		int right=0;
		int bottom=0;
		lp.setMargins(left, top, right, bottom);
if(l.equals("1")){
if (sharedpreferences.contains("level1_rating"))
  {
if(AllGlobalVariables.level_score <= 50){
			
Bitmap goodbmp = BitmapFactory.decodeResource(getResources(), R.drawable.fail);
String goodimagecode = BitMapToStringgood(goodbmp);
Bitmap goods = StringToBitMapgoods(goodimagecode);
Drawable verticalImage = new BitmapDrawable(getResources(), goods);
AllGlobalVariables.Rimagel1 = (ImageView) findViewById(R.id.imageView6); AllGlobalVariables.Rimagel1.setImageDrawable(verticalImage);
	      }
}
}
}

但问题是:我能够获得价值形式密钥,但无法比较共享偏好键的值以显示评级。请建议如何比较密钥的值

或者还有其他想法可以做这项工作,建议将非常感激

谢谢

1 个答案:

答案 0 :(得分:1)

如果首选项包含首选项true,则

SharedPreferences.contains返回false

使用SharedPreferences.getInt获取整数值,然后与其他值进行比较:

if (sharedpreferences.contains("level1_rating"))
{
   int level1_ratingValue=sharedpreferences.getInt("level1_rating",0);;
    if(level1_ratingValue==70){
      // do work if condition true
    }else{
      // do work if condition false
    }
}