I got a ValueEventListener
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Intent intent = new Intent(BackgroundService.this, NextActivity.class);
Task<String> t=genrate();//not null
t.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (task.isSuccessful()) {
intent.putExtra("token",task.getResult());
}
} });
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(BackgroundService.this, 0, intent, 0);
mBuilder.setContentIntent(pendingIntent).setAutoCancel(true);
mBuilder.setVisibility(VISIBILITY_SECRET);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(BackgroundService.this);
notificationManager.notify(121, mBuilder.build());
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
The token
key is missing from NextActivity
.
getIntent().getExtras().getString("token")
return null
.
What could be the problem ?
addValueEventListener()
is asynchronous. You will get the result only inside onDataChange()
. Move the code to show notification into a separate method and call it inside onDataChange()
.
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Intent intent = new Intent(BackgroundService.this, NextActivity.class);
Task < String > t = genrate(); //not null
t.addOnCompleteListener(new OnCompleteListener < String > () {
@Override
public void onComplete(@NonNull Task < String > task) {
if (task.isSuccessful()) {
intent.putExtra("token", task.getResult());
//Show notification here
showNotification(intent);
}
}
});
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
});
Separate method to show notification.
private void showNotification(Intent intent) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(BackgroundService.this, 0, intent, 0);
mBuilder.setContentIntent(pendingIntent).setAutoCancel(true);
mBuilder.setVisibility(VISIBILITY_SECRET);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(BackgroundService.this);
notificationManager.notify(121, mBuilder.build());
}