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;
}
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();
But It's throwing a NullPointerException
on line no:10 of above method and line no:3 of above code.
You method
returns
null
, so your line 10 should look like:if (l==null) {
I think you forgot
The method
getEarliestConnection()
makes a call togetConnections()
which returnsnull
.Since
getConnections()
is abstract inCall
check the method you've provided inMyCall
.Obviously
getConnections()
returns null here and you cannot get the size of the null-object.Here's how to fix it:
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 asYour cm variable has been never initialized before getConnections() call. So, it is null and you get NullPointerException when trying to invoke cm.getActiveFgCall().
Presumably
getConnections()
is returning null, sol
is null, so trying to calll.size()
is throwing the exception. We don't know whatgetConnections()
does though.Note that this looks suspicious too:
Why are you creating an instance of
MyConn
in the first line, only to throw it away again? Why not just use: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, assignt
a value in the declaration, declarel
at the point of assignment, etc. You should also consider using generics where possible - e.g.List<MyConn>
instead of just the rawList
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.