Broadcast Receiver error Null pointer expection

70 views Asked by At

In my Main Activity I have a broadcast Receiver

    public static class the_receive extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            if(extras.containsKey("retvalue")){
                test.setText(extras.get("retvalue").toString());
            }
        }
    }
};

and in my Android manifest

 <receiver
        android:name=".MainActivity$the_receive"
        android:enabled="true">
        <intent-filter>
            <action android:name="ax.androidexample.mybroadcast" />
        </intent-filter>
    </receiver>

This works perfectly fine and receives incoming values.

However when I want another broadcast receive in another Activity

public static class b_receive extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            if(extras.containsKey("retvalue")){
                text.setText(extras.get("retvalue").toString());
            }
        }
    }
};

And in my Android Manifest

    <receiver
        android:name=".MainActivity$the_receive"
        android:enabled="true">
        <intent-filter>
            <action android:name="ax.androidexample.mybroadcast" />
        </intent-filter>
    </receiver>
    <receiver
        android:name=".testService$b_receive"
        android:enabled="true">
        <intent-filter>
            <action android:name="ax.androidexample.mybroadcast" />
        </intent-filter>
    </receiver>

I start getting this error:

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

In my MainActivity

Any help would be appreciated. Thank you heaps

1

There are 1 answers

0
Alex Nikiforoff On

Consider registering and unregistering your receiver by overriding methods of the lifecycle of the activity or fragment you use your receiver in.

Activity Live Cycle here: https://developer.android.com/guide/components/activities/activity-lifecycle.html

Fragment Live Cycle here: https://developer.android.com/guide/components/fragments.html

  • You must unregister your receiver before your activity becomes inactive.
  • You have to register it again when your activity becomes active.