Exception: Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference
10,970
context
is null
. forget to initialize.do it as:
public CustomList(Activity context, ListItem li[]){
super(context, R.layout.rowlayout, li);
this.listItem = li;
this.context=context; //<< initialize here
}
Author by
Java Enthusiast
Updated on June 05, 2022Comments
-
Java Enthusiast almost 2 years
I get this exception
Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference
but I am able to find the reason.In the mainactivity I create a ListView element, the structure is:
<ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/list" />
And I create a custom Adapter class for the listview,
class ListItem { public String shortDescription; public String type; public String time; public int imageId; public ListItem(String sd, String type, String time, Integer imageId) { this.shortDescription = sd; this.type = type; this.time = time; this.imageId = imageId; } } public class CustomList extends ArrayAdapter<Object>{ private Activity context; private ListItem listItem[]; public CustomList(Activity context, ListItem li[]){ super(context, R.layout.rowlayout, li); this.listItem = li; } @Override public View getView(int position, View view, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.rowlayout, null, true); TextView sd = (TextView)rowView.findViewById(R.id.sd); TextView type = (TextView)rowView.findViewById(R.id.type); TextView days = (TextView)rowView.findViewById(R.id.days); ImageView icon = (ImageView)rowView.findViewById(R.id.icon); sd.setText(listItem[position].shortDescription); type.setText(listItem[position].type); days.setText(listItem[position].time); icon.setImageResource(listItem[position].imageId); return rowView; }
And I call this in my MainActivity class,
public class MainActivity extends ActionBarActivity { ListView listView; ListItem listItem[] = new ListItem[2]; Integer[] imageId = {R.drawable.ic_launcher}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listItem[0] = new ListItem("test", "test", "test", imageId[0]); listItem[1] = new ListItem("test1", "test1", "test1", imageId[0]); CustomList adapter = new CustomList(MainActivity.this, listItem); listView = (ListView)findViewById(R.id.list); listView.setAdapter(adapter); } }
I get the exception in the custom Adapter class , at LayoutInflater inflater = context.getLayoutInflater();. But the variable context is initialized in the constructor call itself. Why does it throw an Exception?