Search code examples
androidimageswitcher

android development if statement with images


i am trying to create a if statement which checks to see the "ratings" of a restaurant by "-1, 0, 1, 2, 3, 4 and 5". I need to then replace the rating number with a image. I have attempted to do this already but the app keeps crashing, app works fine without the if statement and shows 10 nearest locations as it should. here is the code:

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
}

Solution

  • UPDATE:

    In addition to the below code, you need to set up a view factory so that your image can be added to something.

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

    Then put your if statement below this code.


    You image switcher is null. You need to instantiate the image switcher before you can assign an image to it.

    ImageSwitcher imageView = new ImageSwitcher(context);