Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intent.getAction() is throwing Null + Android

Tags:

android

I have written BroadcastReceiver for sort of Alarm application. In onReceive method I am reading Intent.getAction(). It is running well in all of the versions *except in SDK version 1.5 where it throws null pointer exception*. I am setting the action in another activity where I am calling broadcastReceiver. Please help me out with this. Below is the code snippet for both receiver and activity classes,

ProfileActivity.java


public static final String STARTALARMACTION = "android.intent.driodaceapps.action.STARTPROFILE";

public static final String STOPALARMACTION = "android.intent.driodaceapps.action.STOPPROFILE";

AlarmManager alarmMan = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent startIntent = new Intent(this,AlarmReceiver.class);

startIntent.setAction(STARTALARMACTION);

Intent stopIntent = new Intent(this,AlarmReceiver.class);

stopIntent.setAction(STOPALARMACTION+intentposition);

AlarmReceiver.java

@Override
public void onReceive(Context context,Intent intent){

    String intentAction = intent.getAction(); 

    Log.d(TAG,"Intent:"+intentAction); **//throwing null**

After getting the error I tried my luck by giving the actions in of .manifest file. But no use.

Please help me.

Thanks.

like image 988
poddroid Avatar asked Mar 06 '11 20:03

poddroid


1 Answers

From the docs for BroadcastReceiver.onReceive()...

The Intent filters used in registerReceiver(BroadcastReceiver, IntentFilter) and in application manifests are not guaranteed to be exclusive.

For this reason, onReceive() implementations should respond only to known actions, ignoring any unexpected Intents that they may receive.

I don't fully understand the implications of either of the statements above but it seems the second of the two is that an onReceive() handler should be written to cope with the unexpected.

Remember that Intents don't need to have an associated 'action' (they can be used simply to pass data between differnt entities). Intent.getAction() will return null if the Intent has no action set and attempting to Log intentAction will call an NPE.

Are you sure the Intent is one of your own and not another which has found it's way to your receiver? I'm not familiar with v1.5 but it's possible things may have worked a different way - unlikely perhaps but possible.

I think the simple thing to try is to simply test intentAction to see if it is null and ignore it if it is (i.e., exit the onReceive() handler assuming the intent isn't one of your own). Worth a try.

like image 142
Squonk Avatar answered Sep 29 '22 03:09

Squonk