Question:
I have a problem with clicking in a Listview
after scrolling. That is, if I click on the content that was originally visible, then everything is OK. But if I click while scrolling through the list (that is, I click on a position that was not visible), then the program crashes with the following 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());
}
});
Answer:
Your mistake is that you are trying to get a View
from a ListView
. So it is not necessary.
The View
you need, i.e. the list item markup – already passed as the second argument to the onItemClick(AdapterView<?> parent, View itemClicked, int position, long id)
method. 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());
}
});
Even better – hang the listener inside the adapter. Better yet – rewrite under RecyclerView