java null指针异常但已初始化

时间:2016-12-28 05:56:00

标签: java android

stacktrack:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean' java.util.ArrayList.add(java.lang.Object)' on a null object reference  
at android.net.LinkProperties.<init>(LinkProperties.java:159)
at com.android.server.ConnectivityService.getUnfilteredActiveNetworkState(ConnectivityService.java:957)
at com.android.server.ConnectivityService.getActiveNetworkInfo(ConnectivityService.java:1024)
at android.net.ConnectivityManager.getActiveNetworkInfo(ConnectivityManager.java:696)
at 

linkproperties.java:

public final class LinkProperties implements Parcelable {
// The interface described by the network link.
private String mIfaceName;
private ArrayList<LinkAddress> mLinkAddresses = new ArrayList<LinkAddress>();
private ArrayList<InetAddress> mDnses = new ArrayList<InetAddress>();
private String mDomains;
private ArrayList<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
...
public LinkProperties(LinkProperties source) {
    if (source != null) {
        mIfaceName = source.getInterfaceName();
        for (LinkAddress l : source.getLinkAddresses()) mLinkAddresses.add(l);
        for (InetAddress i : source.getDnsServers()) mDnses.add(i);
        mDomains = source.getDomains();
        for (RouteInfo r : source.getRoutes()) mRoutes.add(r);
        mHttpProxy = (source.getHttpProxy() == null)  ?
                null : new ProxyInfo(source.getHttpProxy());
        for (LinkProperties l: source.mStackedLinks.values()) {
            addStackedLink(l);
        }
        setMtu(source.getMtu());
        mTcpBufferSizes = source.mTcpBufferSizes;
    }
}  

在stacktrace中我们可以在init方法中发现这个异常,这意味着在构造这个数据时,在执行ArrayList.add方法时,抛出一个NullPointerException。因此在构造函数方法中,只有 mLinkAddresses mDnses MRoutes 这三个ArrayLists,但它们都已初始化。所以我对此感到困惑。

所有Arraylist在创建前都已初始化,但仍然获得NullPointerException,此问题仅发生在MTK平台上。

1 个答案:

答案 0 :(得分:0)

方法参数LinkProperties source不为空,但是当调用source.getLinkAddresses(),source.getDnsServers(),source.getRoutes()可能具有空值时。您必须检查此内容。