Dusan Dimitrijevic Dusan Dimitrijevic - 2 months ago 6
Android Question

Missing return statement in method with if conditions in recyclerview adapter

I really don't know why i'm getting in this method an error for not returning any value. It's about method

getItemViewType()
in
RecyclerView.Adapter
. I'm checking for some condition inside.

@Override
@ViewType
public int getItemViewType(int position) {
if (!mResults.isEmpty()) {
if (position < mResults.size()) {
if (itemList.get(position) instanceof Categorizable) {
return TYPE_ITEM;
} else if (itemList.get(position) instanceof SectionHeader) {
return TYPE_SECTION_HEADER;
}
} else {
return FOOTER;
}
} else {
if (mFilterOption == Filter.COMPLETE ||
mFilterOption == Filter.INCOMPLETE) {
if (position == 0) {
return NO_ITEM;
} else {
return FOOTER;
}
} else {
if (itemList.get(position) instanceof Categorizable) {
return TYPE_ITEM;
} else {
return TYPE_SECTION_HEADER;
}
}
}
}

Answer

I think I got it, one of your conditions is not covered. Look at the first if, and look where I added return 1;, you were missing a return statement in case it enters there but it does not fulfill any of the above 2 conditions:

if (!mResults.isEmpty()) {
        if (position < mResults.size()) {
            if (itemList.get(position) instanceof Categorizable) {
                return TYPE_ITEM;
            } else if (itemList.get(position) instanceof SectionHeader) {
                return TYPE_SECTION_HEADER;
            }
            return 1; // adding this will fix it
        } else {
            return FOOTER;
        }
    } else {
        if (mFilterOption == Filter.COMPLETE ||
                mFilterOption == Filter.INCOMPLETE) {
            if (position == 0) {
                return NO_ITEM;
            } else {
                return FOOTER;
            }
        } else {
            if (itemList.get(position) instanceof Categorizable) {
                return TYPE_ITEM;
            } else {
                return TYPE_SECTION_HEADER;
            }
        }
    }

Of course, replace 1 with the actual value it's supposed to return there. Also, when you have returns you don't actually need elses most of the time. Take a look at this example:

if (a > b) return a;
else return b;

And compare it to this (just to get the idea):

if (a > b) return a;
return b;

So the second one may be a bit more readable, and it does the same thing. If the if condition was fulfilled, it would've returned a. If not, no need for else, it's obsolete. Maybe removing some elses in your code may make it more clear and readable.

Comments