android 带有图像的开发if语句

android development if statement with images

我正在尝试创建一个 if 语句,该语句通过“-1、0、1、2、3、4 和 5”检查餐厅的 "ratings"。然后我需要用图像替换评级数字。我已经尝试这样做,但应用程序一直崩溃,应用程序在没有 if 语句的情况下工作正常,并显示 10 个最近的位置。这是代码:

JSONObject jo = (JSONObject) ja.get(i);
String name = jo.getString("BusinessName");
String rating = jo.getString("RatingValue");
String address1 = jo.getString("AddressLine1");
String address2 = jo.getString("AddressLine2");
String postcode = jo.getString("PostCode");

ImageSwitcher imageView = null;
if(rating.equalsIgnoreCase("-1")){
    imageView.setImageResource(R.drawable.rating0);
}else if(rating.equalsIgnoreCase("0")){
    imageView.setImageResource(R.drawable.rating0);
}else if(rating.equalsIgnoreCase("1")){
    imageView.setImageResource(R.drawable.rating0);
}else{
    //default case, if above all conditions will become false then this will call
}
ImageSwitcher imageView = null;

为空。

使其不为空。

更新:

除了下面的代码,您还需要设置一个视图工厂,以便您的图像可以添加到某些东西中。

ImageSwitcher imageView = new ImageSwitcher(context);
imageView.setFactory(new ViewSwitcher.ViewFactory() {
        @Override
        public View makeView() {
            ImageView view = new ImageView(Location_assignment.this);
            return view;
        }
    });

然后把你的 if 语句放在这段代码下面。


您的图像切换器为空。您需要先实例化图像切换器,然后才能为其分配图像。

ImageSwitcher imageView = new ImageSwitcher(context);

您必须检查两件事:

首先需要初始化imageView(因为它是null)。 这就是 AS 对您的代码所说的内容:

Method invocation 'imageView.setImageResource(R.drawable.rating0)' may produce 'java.lang.NullPointerException'

其次,检查变量 "rating" 是否不为空是个好主意,因为它来自 JSON.