Can not get element from layout

14,599

Solution 1

I'm guessing this is happening in your Activity's onCreate() method because you are calling findViewById() before you have called setContentView(). If that's not the case then please show more of your code.

Solution 2

If findViewById() is failing to find your target id, here are some reasons this may happen:

[[ In your case, I suspect #1 or #2.]

  1. SetContentView() (or inflate) hasn't been called yet to associate a layout to search yet.

  2. SetContentView() (or inflate) was called with a layout that does not contain the target id, e.g. you specified the wrong layout.

  3. There's a typo in the id in the layout or in the code.

  4. You've imported the wrong R file (like a library component's R file) and coincidentally the same id was also used in the other R file).

  5. You're searching the wrong view, e.g. you inflated a menu layout and did not attach it to the root layout and then you attempted to search for an id in the root layout (findBiewById(..)) when you meant to search the inflated menu layout (menu.findBiewById(..)).

Share:
14,599
artem
Author by

artem

Updated on June 06, 2022

Comments

  • artem
    artem about 2 years

    I have 2 activities. The 2nd .xml looks like:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <ListView 
                android:id="@+id/TrainsListView"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" 
            />
    </LinearLayout>
    

    Part of manifest:

    <activity android:name="TrainsActivity">
    
    </activity>
    

    And I'm trying to get TrainsListView:

    mListView = (ListView) findViewById(R.id.TrainsListView);
    

    But after this mlistView is null. Why?