Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio displaying a warning unchecked call for the following code

what is wrong with this? see code and warning message, can anyone elaborate.

public void chooseBreakfast() {

            ArrayAdapter planAdapter1 = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, new Food[]{
            new Food(1, "Toast"),
            new Food(99, "Cereal"),
            new Food(53, "Fruit"),
            new Food(153, "Yogurt")
     });

WARNING MESSAGE - Unchecked call to 'ArrayAdapter(Context, int, T[])' as a member of raw type 'android.widget.ArrayAdapter' less... (Ctrl+F1)

JDK 5.0 only. Signals places where an unchecked warning is issued by the compiler, for example:

void f(HashMap map) {
      map.put("key", "value");
}
like image 843
ERN Avatar asked Feb 16 '15 12:02

ERN


1 Answers

The compiler is warning you about the usage of a raw ArrayAdapter. You should use a generic ArrayAdapter as

ArrayAdapter<Food> planAdapter1 = new ArrayAdapter<Food>(this,
        android.R.layout.simple_spinner_item, new Food[]{
        new Food(1, "Toast"),
        new Food(99, "Cereal"),
        new Food(53, "Fruit"),
        new Food(153, "Yogurt")
});

Notice, how the ArrayAdapter class and its constructor are defined.

public class ArrayAdapter<T> extends BaseAdapter ... { // T = generic type

    public ArrayAdapter(Context context, int resource, T[] objects) {
        init(context, resource, 0, Arrays.asList(objects));
    }
    ...
}

They use a generic type parameter T which the simple ArrayAdapter() initialization ignores to pass. Hence, the warning. The benefit of passing the type T is that you get rid of unnecessary casts and your code becomes more type safe.

For e.g., calling ArrayAdapter#getItem() on a raw adapter will return Object and require you to cast it into Food yourself. The generic adapter will return the actual type Food automatically.

like image 53
Ravi K Thapliyal Avatar answered Nov 11 '22 22:11

Ravi K Thapliyal