calling broadcast receiver class multiple times with different intent showing "null pointer error"

StackOverflow https://stackoverflow.com/questions/23382043

  •  12-07-2023
  •  | 
  •  

Pergunta

my app has a BroadcastReciving and mainactivity class. from mainactivity I am calling broadcast receiving class 3 times with different intent from different places.

what i want is to execute different codes in broadcast receiving class when found different intent.

eg: 
   when intent contains string it execute a() function
   when intent is int it executes b() function

but when i am fetching data in on receive it crashes my app showing "null pointer Exception" how to solve this

Foi útil?

Solução

Define a different action string for each different operation. Set the action for each Intent appropriately and check the action in onReceive of the BroadcastReceiver.

/* when sending a broadcast */
Intent intent = new Intent("action_a");
context.sendBroadcast(intent);

/* in the BroadcastReceiver */
@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if (TextUtils.isEmpty(action)) {
        // intent didn't have an action
        return;
    }

    if ("action_a".equals(action)) {
        // do function A
    } else if ("action_b".equals(action)) {
        // do function B
    } // and so on
}

In your AndroidManifest, add the following as a child element of the <receiver> tag:

<intent-filter>
    <action name="action_a" />
    <action name="action_b" />
    <!-- and so on -->
</intent-filter>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top