I have a problem with clicking in Listview after scrolling. That is, if I click on the content that was initially visible, then everything is ok. But if I click scrolling the list (that is, I click on a position that was not visible), then the program crashes with this text in the logs:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById (int)' on a null object reference

Who faced?

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) { TextView tp = (TextView)listView.getChildAt(position).findViewById(R.id.userid); Log.v("mes",tp.getText().toString()); } }); 
  • four
    @DezarEvm, for some reason you are trying to get a View from a ListView. This is not necessary. The twist you need has already been passed as an argument. Do this: TextView tp = (TextView)itemClicked.findViewById(R.id.userid); Log.v("mes",tp.getText().toString()); TextView tp = (TextView)itemClicked.findViewById(R.id.userid); Log.v("mes",tp.getText().toString()); . Better yet, hang the listener inside the adapter. Better yet - rewrite under RecyclerView - YuriiSPb
  • You carefully read what advises @ YuriiSPb He is like Jesus! always helps correctly :) - iFr0z

1 answer 1

Your mistake is trying to get a View from a ListView . This is not necessary.
The View you need, i.e. list item markup - already passed as the second argument of the onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) method onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) . Do this:

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) { TextView tp = (TextView)itemClicked.findViewById(R.id.userid); Log.v("mes",tp.getText().toString()); } }); 

Better yet, hang the listener inside the adapter. Better yet - rewrite under RecyclerView