androidandroid-fragments

Android - Why does UI Object reference becomes null when returning from adapter call?


Consider the following code snippet in an Android fragment:

Adapter adapter = new Adapter(getActivity(), points_array_list);

listView.setAdapter(adapter);

//When returning from adapter a particular UI object(ie. a TextView) becomes //null

for(Point p : points_array_list) {
if (p.getTextView() == null) {
                Log.wtf("WTF","Why is it NULL ?");
            }
}

In the adapter the code is as follows:

TextView view = (TextView) view.findViewById(R.id.point_textview);

point.setView(view);

Both the adapter and fragment share the same ArrayList<Point> reference.

Now the reason I am doing this is because I have to update the TextView on an event. Why does it become null after it returns from the adapter call?

Also, I have added the following check to make sure it is not null there:

if(point.getCoordView() != null) {
                Log.wtf("WTF", "Its not null");
            }

And the above sanity check works as expected, but the object still becomes null when I return from the adapter.


Solution

  • The results in adapter need to a few milliseconds for initializing. You can use this

    new Handler().postDelayed(new Runnable() {
    
                @Override
                public void run() {
                   for(Point p : points_array_list) {
                    if (p.getTextView() == null) {
                      Log.wtf("WTF","Why is it NULL ?");
                      }
                    }
                 }
            }, 500);