ViewStub NullPointerException

4.2k views Asked by At

I have a problem with the view stub.

This is the ViewStub in my java file

ViewStub stub = (ViewStub) findViewById(R.id.stub1);
ArrayAdapter<String> content=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,files);
View inflated=stub.inflate();
ListView people=(ListView)inflated.findViewById(R.id.friends);
people.setAdapter(content);

This is the xml where I initialize the Viewstub

    <?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/linear_details" >
    <include layout="@layout/home_back_next_bar" />
    <ViewStub android:id="@+id/stub1" android:inflatedId="@+id/showlayout"
android:layout="@layout/layout1" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>  

</LinearLayout>
</merge>

my layout file inflated in the view stub is as follows:

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

This code gives me a NullPointerException when creating instance of the listview to fill it. Any Ideas what causes this problem and how to solve.

Thanks alot in advance

Error in Log cat: enter image description here

2

There are 2 answers

0
petey On

The reason it didnt work: According to the docs : http://developer.android.com/reference/android/view/ViewStub.html#inflate()

You are doing a findViewById on "The inflated layout resource" which is the very listview you are looking for. .

0
Salma Hamed On

Instead of using

ListView people=(ListView)inflated.findViewById(R.id.friends);

I used

ListView people=(ListView)stub.inflate();

And it worked no idea why??. but it did :))