即使放置了Null Check,我仍会得到null指针异常:

@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;
            }
        }
}


例外:

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)

最佳答案

还需要在将元素添加为之前初始化cacheOf ArrayList:

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));
     }
}

关于java - Arraylist中的空指针异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21531174/

10-10 11:56