简体   繁体   English

Arraylist中的空指针异常

[英]Null Pointer exception in Arraylist

I am getting null pointer exception even though I have placed the Null Check: 即使放置了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;
            }
        }
}

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)

Also need to initialize cacheOf ArrayList before Adding elements as: 还需要在将元素添加为之前初始化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));
     }
}

Did you read the error? 你读错了吗?

The key here is: com.activity.MainFragmentActivity.getData(MainFragmentActivity.java:198) 此处的关键是:com.activity.MainFragmentActivity.getData(MainFragmentActivity.java:198)

What line is 198? 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. 您有未初始化的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM