Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View.findViewById() returning null

I have this code:

private void inflateMenu() {
    if (menu == null) {
        mFanView = (LinearLayout) findViewById(R.id.fanView);
        final View v = LayoutInflater.from(getContext()).inflate(
                R.layout.sidemenu, mFanView);
        menu = (MenuView) v.findViewById(R.id.listViewMenu);
    }
        menu.setColors(backgroundColor, selectedColor, unselectedColor);
}

When debugging, v contains a MenuView whose id equals R.id.listViewMenu + 1. Of course this will throw a NPE on menu.setColors.

Why does R.id.listViewMenu contain an ID that doesn't lead to the view with that ID in XML?

I've tried to clean my project but it still stays the same.

EDIT: Posting requested files.

sidemenu.xml

<com.ui.library.slidingmenu.MenuView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listViewMenu"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

EDIT: Problem solved.

To anyone coming here because findViewById returns null: Clean the project. If it doesn't work, clean the project again. If it doesn't work, clean ALL your projects. Until it works. If it doesn't work, then ask.

like image 212
Charlie-Blake Avatar asked Nov 16 '12 11:11

Charlie-Blake


People also ask

Why is findViewById returning NULL?

FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.

What does findViewById return?

findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .

Why do you use findViewById?

findViewById(R. id. some_id) to retrieve Views in code. ViewBinding works similarly, but, in addition to just adding the IDs into a global list, it parses more information from XML and generates code for each layout file.

What is Viewview findViewById?

view. findViewById() is used to find a view inside a specific other view. For example to find a view inside your ListView row layout.


1 Answers

Try this:

(In eclipse menu bar) Project > Clean

Explanation: sometimes during building, the R.java class messes up and causes wrong references to id's. Sometimes when I compile, an image suddenly changes because the id associated with it is changed too. This can happen with any resource, Layouts, Id's, etc.

A way to regenerate the R.java class and fix irregularities is by cleaning your project.

Hope that helps!

like image 193
Neilers Avatar answered Oct 13 '22 10:10

Neilers