0

I am doing some threading. In the postExecute I need to perform an iterator task. I check if the iterator() is null, but it's still producing this error:

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
        at co.appname.app.Fragments.F_EditPhoto$FiltersAsyncTask.onPostExecute(F_EditPhoto.java:772)

Here is my code, Im checking for what I think is every possible null scenario. Can you advise what I am doing wrong?

@Override
        protected void onPostExecute(Void aVoid)
        {
            List<K_FilterPreview> filtersCache = _positionToFiltersCacheMap.get(_selectedEditImage.position);
            if (filtersCache == null || filtersCache.iterator() == null)
            {
                System.err.println("Filter cache was null");
            }

            // THIS IS THE LINE THROWING THE ERROR!
            Iterator<K_FilterPreview> i = filtersCache.iterator();
            while (i.hasNext())
            {
                //Do stuff
            }
        }

This only occurs if I try to start this event as soon as the current event is done processing. If I wait a few seconds before invoking this it works fine. So there is something going on with the threading but I'm not sure what.

Aggressor
  • 13,323
  • 24
  • 103
  • 182

2 Answers2

3
if (filtersCache == null || filtersCache.iterator() == null)
{
     System.err.println("Filter cache was null");
}

Well if filtersCache is null, you just print an error statement, and then the program continues to call iterator on the null filtersCache. You probably wants to just return from the method in that case. Further, normally when you get an Iterator on a list, it doesn't return null so I don't think there is a need for the second part in the condition:

if (filtersCache == null)
{
     System.err.println("Filter cache was null");
     return;
}
M A
  • 71,713
  • 13
  • 134
  • 174
1

Check to make sure that filtersCache is not null, then call .iterator()

    protected void onPostExecute(Void aVoid)
    {
        List<K_FilterPreview> filtersCache = _positionToFiltersCacheMap.get(_selectedEditImage.position);
        if (filtersCache == null || filtersCache.iterator() == null)
        {
            System.err.println("Filter cache was null");
        }

        // THIS IS THE LINE THROWING THE ERROR!
        if(filtersCache != null && filtersCache.iterator() != null){
            Iterator<K_FilterPreview> i = filtersCache.iterator();

            while (i.hasNext())
            {
                //Do stuff
            }
        }
    }
Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36