Reputation: 167
The value for myRange is always 1, 2 or 3.
It is giving a nullpointer exception error.pending must be specified.
If I do not check myRange value inside if statement, it does not give an error but it does not create pendingIntent2 and pendingIntent3.
I tried sending different Request code but it did not work.
private PendingIntent createGeofencePendingIntent(int myRange) {
Log.d(TAG, "createGeofencePendingIntent");
Toast.makeText(getContext(),"creating intent function" + myRange ,Toast.LENGTH_SHORT).show();
if ( geoFencePendingIntent1 != null && myRange == 1)
return geoFencePendingIntent1;
if ( geoFencePendingIntent2 != null && myRange == 2 )
return geoFencePendingIntent2;
if ( geoFencePendingIntent3 != null && myRange == 3)
return geoFencePendingIntent3;
if(myRange == 1)
{
Toast.makeText(getContext(),"creating intent 1",Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent( getContext(), GeofenceTransitionService.class);
intent1.putExtra("region",inString[0]);
geoFencePendingIntent1 = PendingIntent.getService(
getContext(), GEOFENCE_REQ_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT );
return geoFencePendingIntent1;
}
else if (myRange ==2)
{
Toast.makeText(getContext(),"creating intent 2",Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent( getContext(), GeofenceTransitionService.class);
intent2.putExtra("region",inString[1]);
geoFencePendingIntent2 = PendingIntent.getService(
getContext(), 5, intent2, PendingIntent.FLAG_NO_CREATE );
return geoFencePendingIntent2;
}
else if (myRange == 3)
{
Intent intent3 = new Intent( getContext(), GeofenceTransitionService.class);
return PendingIntent.getService(
getContext(), GEOFENCE_REQ_CODE, intent3, PendingIntent.FLAG_UPDATE_CURRENT );
}
geoRange++;
// Toast.makeText(getContext(), "leaving my geofence", Toast.LENGTH_SHORT).show();
return null;
}
Upvotes: 1
Views: 403
Reputation: 95578
You have several problems here. The first one is this:
geoFencePendingIntent2 = PendingIntent.getService(
getContext(), 5, intent2, PendingIntent.FLAG_NO_CREATE );
This will probably always return null
as you you've specified FLAG_NO_CREATE
. This will only return a non-null
result if a matching PendingIntent
already exists (which it probably doesn't). Use FLAG_UPDATE_CURRENT
instead.
The second problem is that you need to make sure that each of your 3 different PendingIntent
s are unique. To do this you need to provide either a unique requestCode
in the call to PendingIntent.getService()
OR you need to provide a unique ACTION in the Intent
that you pass to PendingIntent.getService()
. Otherwise, when you call PendingIntent.getService()
, you will just keep getting the same PendingIntent
returned (and a new one will not be created).
There are about a million questions on Stackoverflow about this and in most of them there is a detailed explanation of how PendingIntent
creation and matching works.
Upvotes: 1