ListView listView1; String [] Title = {"one","two","four","five"}; int[] imgid = {R.drawable.dela, R.drawable.gnev, R.drawable.psy}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); listView1 = (ListView)findViewById(R.id.listview1); CustomAdapter customAdapter = new CustomAdapter(); listView1.setAdapter(customAdapter); } class CustomAdapter extends BaseAdapter{ @Override public int getCount() { return imgid.length; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { View view1 = getLayoutInflater().inflate( R.layout.title,null); ImageView imageView2 = (ImageView)findViewById(R.id.imageView2); TextView textView = (TextView)findViewById(R.id.textView1); imageView2.setImageResource(imgid[i]); textView.setText(Title[i]); return view1; } } } 
  • In the logs, he writes the following: E ​​/ AndroidRuntime: FATAL EXCEPTION: main Process: com.example.azot2, PID: 7738 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource (int)' on a null object reference at com.example.azot2.ListActivity $ CustomAdapter.getView (ListActivity.java:61) - Anton
  • Possible duplicate question: What is Null Pointer Exception and how to fix it? - Sergey Gornostaev

1 answer 1

Your adapter is defined in the class of activation, we take the string

ImageView imageView2 = (ImageView) findViewById (R.id.imageView2);

interpreted by the compiler in

 ImageView imageView2 = (ImageView)ActivityClassName.this.findViewById(R.id.imageView2); 

those. You are looking for an ImageView in the active markup, not the list item markup. This happens because the compiler sees the findViewById method and first tries to find it in the adapter class. But he has no such method. Whereupon the compiler is looking for this method in the enclosing class. Finds it, calls it on an instance of this class, but does not find a view there, it becomes null , after which you get an NPE . You would avoid this if you described your adapter in a separate class, as you should if you are writing a real application, rather than parsing an example.

You need to look for your view in the markup of a list item by calling a method on it like this:

 ImageView imageView2 = (ImageView) view1.findViewById(R.id.imageView2); 

Also, I advise you to switch to RecyclerView - a modern version of ListView .

  • Thank you for helping everything works - Anton
  • ViewHolder just caches the links to the widgets (stores the value obtained by the method findViewById() ) and in no way solves the problem of confusion in the list items when scrolling - pavlofff
  • @pavlofff, well, the main thing is, I'm right) I fixed it - Yuriy SPb