Search code examples
javaandroidkotlinandroid-arrayadapter

When are constructors one and two used in the ArrayAdapter?


ArrayAapter Class have some constructors: enter image description here

When are constructors one and two used? Because we don't have data structure like input array or list at all in these constructors. If possible, explain with an example. Thank you


Solution

  • Those two constructors:

    public ArrayAdapter (Context context, 
                    int resource)
    
    
    public ArrayAdapter (Context context, 
                    int resource, 
                    int textViewResourceId)
    

    are used when you want to create an ArrayAdapter but you don't have the data at the moment of its creation. You can add data later on using methods like add(), insert(), etc. They actually internally call other constructors with empty collection as parameter:

    public ArrayAdapter(@NonNull Context context, @LayoutRes int resource) {
        this(context, resource, 0, new ArrayList<>());
    }
    
    public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
            @IdRes int textViewResourceId) {
        this(context, resource, textViewResourceId, new ArrayList<>());
    }
    

    As for example, you might want to create an ArrayAdapter for a ListView in your activity's onCreate() method, but the data to populate the ListView is fetched later from a network request. In this case, you can use the first or second constructor to create the ArrayAdapter and then add data to it once your network request is complete.

    Some useful links:

    https://developer.android.com/develop/ui/views/layout/declaring-layout#AdapterViews

    https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/widget/ArrayAdapter.javae

    [edit] If the first constructor is used, then text view resource will be 0, from the source code (link above) you can learn that in this case the whole resource is considered a TextView:

        if (mFieldId == 0) {
                //  If no custom field is assigned, assume the whole resource is a TextView
                text = (TextView) view;
            } else {