0

I am getting null pointer exception even though I have placed the Null Check:

@Override 
    public ArrayList<DataCache> getData()   
    { 
        if(contentOf != null)
        {
            StoreData data = new StoreData(this);
            if(data!=null)
            {
                ArrayList<DataCache> cacheOf = null;
                System.out.println("Size of ContentOf"+contentOf.size());
                for (int i=0;i<contentOf.size();i++)
                {
                    System.out.println("Value of ContentOf"+contentOf.get(i).mFeed);
                    ArrayList<DataCache> cache = contentOf.get(i).mFeed.getData();
                    if (cache != null)
                        cacheOf.add(cache.get(i));
                }
                return cacheOf;
            }
        }
}

Exception:

02-03 10:19:18.770: E/AndroidRuntime(8680): FATAL EXCEPTION: main
02-03 10:19:18.770: E/AndroidRuntime(8680): java.lang.NullPointerException
02-03 10:19:18.770: E/AndroidRuntime(8680): at 
com.activity.MainFragmentActivity.getData(MainFragmentActivity.java:198)
Pete B.
  • 3,188
  • 6
  • 25
  • 38
Sweety Bertilla
  • 972
  • 10
  • 35

2 Answers2

3

Also need to initialize cacheOf ArrayList before Adding elements as:

ArrayList<DataCache> cacheOf = new ArrayList<DataCache>(); //initialize here
System.out.println("Size of ContentOf"+contentOf.size());  //This will be zero.
for (int i=0;i<contentOf.size();i++) {
      //..your code here...
    if (cache != null){
       if(i<=cache.size())
         cacheOf.add(cache.get(i));
     }
}
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • Even after initializing I am getting the same error – Sweety Bertilla Feb 03 '14 at 15:40
  • I removed cacheOf = null after initializing and I got the below error:02-03 10:41:53.640: E/AndroidRuntime(9143): FATAL EXCEPTION: main 02-03 10:41:53.640: E/AndroidRuntime(9143): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 02-03 10:41:53.640: E/AndroidRuntime(9143): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) 02-03 10:41:53.640: E/AndroidRuntime(9143): at java.util.ArrayList.get(ArrayList.java:308) – Sweety Bertilla Feb 03 '14 at 15:43
  • I changed the condition check to cache.size() >i and it worked. if i=0, size of the cache should be at least 1. – Sweety Bertilla Feb 03 '14 at 15:54
0

Did you read the error?

The key here is: com.activity.MainFragmentActivity.getData(MainFragmentActivity.java:198)

What line is 198?

I suspect it is either one of these:

System.out.println("Value of ContentOf"+contentOf.get(i).mFeed);
ArrayList<DataCache> cache = contentOf.get(i).mFeed.getData();

You have memory that is uninitialized.

Pete B.
  • 3,188
  • 6
  • 25
  • 38