DatabaseHelper DatabaseHelper - 1 month ago 7
Java Question

How to get value of all textView inside Listview?

I am trying to get all the values of a TextView and an EditText inside a ListView but I am having a weird issue. Here is my sample code, I removed the EditText to keep it simple:

lv = (ListView) findViewById(R.id.person_details_lv);
Integer x = lv.getAdapter().getCount();
for (int i = 0; i < lv.getAdapter().getCount(); i++) {
View viewRow = lv.getChildAt(i);
//this next condition get the index of the view visible only
if (viewRow != null) {
TextView NameEditText = (TextView) viewRow.findViewById(R.id.detail_name);
Log.d("hello", "Anything detected onscreen:" + NameEditText.getText().toString() + ");
}}


The issue is that it only return the View visible on screen. However, the
getCount
counts everything. As a results, I am getting this error


java.lang.NullPointerException


I added this condition:
if (viewRow != null)
to remove the error but it keeps showing only the View visible on screen. When I scroll the listView, the results change as well. What I want to do is to get the value of the TextViewe in the ListView whether seen onscreen or not.

Answer

I think you should implement this method:

 public View getViewByPosition(int pos, ListView listView) {
        final int firstListItemPosition = listView.getFirstVisiblePosition();
        final int lastListItemPosition = firstListItemPosition
                + listView.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition) {
            return listView.getAdapter().getView(pos, null, listView);
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listView.getChildAt(childIndex);
        }
    }

And then call this method by remplacing your:

View viewRow = lv.getChildAt(i);

with:

viewRow= getViewByPosition(i, lv);

And that's it! you don't need to change the rest. Just remove this if (viewRow != null) . I hope it helps!