抛出空指针异常 [英] Throwing null pointer exception

查看:263
本文介绍了抛出空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做Android的一个应用程序为我需要访问com.android.internal.telephony的API。现在我能够访问这些API,但问题是,无论我打电话类Call.java的 getEarliestConnection()方法,我自己的类它抛出一个 NullPointerException异常。 你可以找到Call.java这里的http:// HI- android.info/src/com/android/internal/telephony/Call.java.html 。在这个类有以下方法:

I am doing one application in android for that I need to access com.android.internal.telephony APIs. Now I am able to access those APIs but problem is wherever I call the getEarliestConnection() method of Class Call.java in my own class it's throwing a NullPointerException. You can find Call.java here http://hi-android.info/src/com/android/internal/telephony/Call.java.html. In this class there is the following method:

1.    public Connection
2.        getEarliestConnection() {
3.            List l;
4.            long time = Long.MAX_VALUE;
5.            Connection c;
6.            Connection earliest = null;
7.    
8.            l = getConnections();
9.  
10.            if (l.size() == 0) {
11.                return null;
12.            }

        for (int i = 0, s = l.size() ; i < s ; i++) {
            c = (Connection) l.get(i);
            long t;

            t = c.getCreateTime();

            if (t < time) {
                earliest = c;
                time = t;
            }
        }

        return earliest;
    }

我想在我的课调用此方法。该类Call.java保险业监督一个抽象类,我创建的调用类的子类,这样调用上面的方法:

I want to call this method in my class. the class Call.java ia an abstract class I created subclass of Call class and called the above method like this:

Call myCall = new MyCall();
Connection myConn = new MyConn();
myConn = myCall.getEarliestConnection();  

但它在网上抛出一个 NullPointerException异常 NO:10以上方法和行号:3以上code。

But It's throwing a NullPointerException on line no:10 of above method and line no:3 of above code.

推荐答案

显然 getConnections()返回null这里,你无法得到空对象的大小。

Obviously getConnections() returns null here and you cannot get the size of the null-object.

下面是如何解决这个问题:

Here's how to fix it:

if (l == null || l.size() == 0) 
{
    return null;
}

因此​​,如果由于某种未知的原因,也没有连接,列表或列表是空的,将被退回。使用操作 || 会做一样的

So, if for some unknown reason, there is no Connection-List or the list is empty, null will be returned. Using the operator || will do the same as

if (l == null)
{
    return null;
}
else if ( l.size() == 0)
{
    return null;
}

这篇关于抛出空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆