尝试从空对象引用上的字段'android.widget.TextView com.choudhary.numberreciever.MainActivity.IncomingNumber'读取



在我的应用程序中,我正在检测来电电话号码,一切正常,但当我试图在主活动的文本视图中设置电话号码时,我得到的错误低于

错误

java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.choudhary.numberreciever.MainActivity.IncomingNumber' on a null object reference
at com.choudhary.numberreciever.ServiceReceiver$1.onCallStateChanged(ServiceReceiver.java:30)
at android.telephony.PhoneStateListener$1.handleMessage(PhoneStateListener.java:347)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

我的广播接收器

public class ServiceReceiver extends BroadcastReceiver {
MainActivity mainActivity;
@Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);


Log.v("incomingNumber", incomingNumber);
Toast.makeText(context, "incoming number is "+ incomingNumber, Toast.LENGTH_LONG).show();
mainActivity.IncomingNumber.setText(incomingNumber);

}
},PhoneStateListener.LISTEN_CALL_STATE);
}
}

我的主要活动

public class MainActivity extends AppCompatActivity {
public TextView IncomingNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IncomingNumber =   (TextView)findViewById(R.id.id_number);
}
}

您永远不会初始化BroadcastReceiver中的变量mainActivity。这就是您得到NullPointerException的原因。

但是,您使用的方法并不好。您不应该直接从BroadcastReceiver访问UI组件(在本例中为TextView(。BroadcastReceiver应该将数据传递给Activity,然后Activity可以操作UI组件。如果您的BroadcastReceiverActivity的内部类,那么它可以简单地调用Activity上的方法来更新TextView

相关内容

  • 没有找到相关文章

最新更新