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

Attempt to read from field 'android.widget.TextView com.choudhary.numberreciever.MainActivity.IncomingNumber' on a null object reference

在我的应用程序中,我正在检测来电 phone 号码,一切正常,但是当我尝试在主 activity 的文本视图中设置 phone 号码时,我低于错误

错误

 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.onCallStateChanged(ServiceReceiver.java:30)
    at android.telephony.PhoneStateListener.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);
}
}

我的主要Activity

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 的内部 class,它可以简单地调用 Activity 上的方法来更新 TextView.