Search code examples
androidbroadcastreceiver

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


In my app I m detecting the incoming calls phone number , everything working fine but when I m trying to set the phone number in the textview of main activity I m getting below errors

Errors

 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)

my Broadcast reciever

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);
}
}

my main 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);

}
}

Solution

  • You never initialize the variable mainActivity in your BroadcastReceiver. That is why you are getting a NullPointerException.

    However, the approach you are using is not good. You should never access UI components (in this case a TextView) from a BroadcastReceiver directly. The BroadcastReceiver should pass the data to your Activity and the Activity can then manipulate the UI components. If your BroadcastReceiver is an inner class of the Activity, it can simply call a method on the Activity to update the TextView.