Throwing null pointer exception

前端 未结 6 1556
别那么骄傲
别那么骄傲 2021-01-28 00:29

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

相关标签:
6条回答
  • 2021-01-28 00:52

    The method getEarliestConnection() makes a call to getConnections() which returns null.

    Since getConnections() is abstract in Call check the method you've provided in MyCall.

    0 讨论(0)
  • 2021-01-28 00:53

    Presumably getConnections() is returning null, so l is null, so trying to call l.size() is throwing the exception. We don't know what getConnections() does though.

    Note that this looks suspicious too:

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

    Why are you creating an instance of MyConn in the first line, only to throw it away again? Why not just use:

    Connection myConn = myCall.getEarliestConnection();
    

    In general, it's worth declaring local variables as late as you can, ideally when you have a useful value - so in your method, you could declare c within the loop, assign t a value in the declaration, declare l at the point of assignment, etc. You should also consider using generics where possible - e.g. List<MyConn> instead of just the raw List type.

    EDIT: In contrast to the accepted answer, I would suggest changing getConnections() to always return a non-null value, returning an empty list if there are no connections. That will be easier to work with.

    0 讨论(0)
  • 2021-01-28 01:05

    I think you forgot

    CallManager cm;    
    cm = new CallManager();
    
    0 讨论(0)
  • 2021-01-28 01:07

    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;
    }
    
    0 讨论(0)
  • 2021-01-28 01:08

    You method

    l = getConnections();
    

    returns null, so your line 10 should look like: if (l==null) {

    0 讨论(0)
  • 2021-01-28 01:18

    Your cm variable has been never initialized before getConnections() call. So, it is null and you get NullPointerException when trying to invoke cm.getActiveFgCall().

    0 讨论(0)
提交回复
热议问题