ViewStub NullPointerException
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"
/&g开发者_C百科t;
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:
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. .
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 :))
精彩评论