0

I have this code in my Android app:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if(viewType == POST_VIEW_TYPE){
        View view = LayoutInflater.from(App.instance).inflate(R.layout.item_post, parent, false);
        return new PostViewHolder(view);
    }else{
        View view = LayoutInflater.from(App.instance).inflate(R.layout.item_user, parent, false);
        return new UserViewHolder(view);
    }
}

The code basically gets a constant named viewType, and inflates the correct view accordingly. My constant POST_VIEW_TYPE is equal to 1:

enter image description here

So far so good. I am passing viewType as 1 to my handler, but the code is somehow evaluating the else branch even though the (extremely simple) expression in if evaluates to true (obviously):

enter image description here

How is this even possible?

UPDATE: I've cleaned the project and rebuilt, but nothing has changed. I've put a breakpoint on the if statement. Here is a GIF demonstrating as I step through the debugger:

enter image description here

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389

1 Answers1

0

I've figured out the problem, thanks to Mike M. pointing out to a similar issue at Android Studio debugger highlights the wrong lines.

Apparently, correct code was executing, but because a completely irrelevant bug was present in my code somewhere else, it was masking the issue, and because debugger was behaving incorrectly, I've simply thought there was something going on related to this issue. I've fixed the other bug, and changed my code in onCreateViewHolder to this:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    RecyclerView.ViewHolder holder = null;
    if(viewType == POST_VIEW_TYPE){
        View view = LayoutInflater.from(App.instance).inflate(R.layout.item_post, parent, false);
        holder = new PostViewHolder(view);
    }else{
        View view = LayoutInflater.from(App.instance).inflate(R.layout.item_user, parent, false);
        holder = new UserViewHolder(view);
    }
    return holder;
}

It now works (and debugs) correctly. It's interesting to see Google's own IDE for Android can't step through (and doesn't even display a warning telling that debugging may step incorrectly due to multiple return paths) the code that Dalvik produces. I wish ART has solved this issue.

Community
  • 1
  • 1
Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389