Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView findViewById returning null

I'm not using a ListActivity because I want to extend FragmentActivity. Instead I'm trying to use:

ListView lv = (ListView) findViewById(R.id.mainListView);

Unfortunately lv is null.

In my xml I have:

 <ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
</ListView>

I've also tried using different android id's for the list view such as the one you have to use when you use ListActivity, but it's always Null.

Edit: I was trying to call findViewById before calling setContentView. Calling setContentView first fixed it.

like image 924
Andy Avatar asked Dec 19 '25 03:12

Andy


2 Answers

As JRaymond mentioned in a comment awhile ago, I needed to call setContentView before using findViewById.

like image 117
Andy Avatar answered Dec 20 '25 16:12

Andy


You should put setContentView on top of findViewById.

like image 25
Pedram Avatar answered Dec 20 '25 18:12

Pedram