当我拨打手机时出现空指针异常

时间:2012-01-16 14:58:39

标签: java android nullpointerexception

清单:

     <receiver  android:name=".CallReceiver">
        <intent-filter  android:priority="100" >
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

代码:

   public void onReceive(Context context, Intent intent) {
      .
      .
      .
  Bundle b = intent.getExtras();
  String incommingNumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
  if(incommingNumber.length()!=0)
    {. . . . .}

如果我输入

,NullPointer错误消失了
      String incommingNumber = "123";

任何想法?

1 个答案:

答案 0 :(得分:-1)

问题是这些问题:

String incommingNumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
  if(incommingNumber.length()!=0)

b.getString返回null并且null.length()抛出错误。您需要添加这样的支票。

if (incomingNumber == null) {
  // do something
}

这就是getString的工作原理:

Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key.
Parameters
key     a String, or null
defaultValue    Value to return if key does not exist
Returns
    a String value, or null 

- &GT; http://developer.android.com/reference/android/os/Bundle.html#getString%28java.lang.String,%20java.lang.String%29 - &GT; http://developer.android.com/reference/android/telephony/TelephonyManager.html