ListView android and null pointer exception -
i'm trying show simple listview ,but have problems .it seems had nullpointerexception . here's xml :
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin" tools:context=".mainactivity"> <listview android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/listview" /> and main class :
public class mainactivity extends activity { private list<string> exemple; private listview liste=(listview) findviewbyid(r.id.listview); protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); exemple=new arraylist<string>(); exemple.add("item 1"); exemple.add("item 2"); exemple.add("item 3"); arrayadapter<string> adapter = new arrayadapter<string>(this, android.r.layout.simple_list_item_1, exemple); liste.setadapter(adapter); } } i got error :
07-07 11:59:27.024 2758-2758/tunisia_sat.com.essai e/androidruntime﹕ fatal exception: main process: tunisia_sat.com.essai, pid: 2758 java.lang.runtimeexception: unable instantiate activity componentinfo{tunisia_sat.com.essai/tunisia_sat.com.essai.mainactivity}: java.lang.nullpointerexception
move liste initialization after setcontentview:
setcontentview(r.layout.activity_main); liste = (listview) findviewbyid(r.id.listview); why nullpointerexception?
calling ssetadapter on null reference liste in following line:
liste.setadapter(adapter); liste null because being initialized before view up(binding activity view). so, findviewbyid returns null.
Comments
Post a Comment