I am using Firebase Job Dispatcher to execute a periodic task that will execute every 15 mins and check for data in the firebase database and display a notification about the latest data.
The issue I am facing is that, the listener isn't getting attached properly in onStartJob
, i.e. the logging statements inside onDataAdded
is never called.
I've linked my code below,
public class FetchInfoService extends JobService {
InfoObject note;
NotificationCompat.Builder notificationBuilder;
private static final String TAG = "SyncService";
public FetchInfoService() {
}
@Override
public boolean onStartJob(com.firebase.jobdispatcher.JobParameters job) {
Log.e(TAG, "Executing job id: " + job.getTag());
DatabaseReference dbReference = FirebaseDatabase.getInstance().getReference().child(CONTENT);
Log.e(TAG,dbReference.getKey());
dbReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG,"OnDataChanged Called"); //----Never Called
for (DataSnapshot infoDataSnapshot : dataSnapshot.getChildren()) {
note = infoDataSnapshot.getValue(InfoObject.class);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG,"Listener Cancelled");
}
});
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_delete_black_48dp)
.setContentTitle(note.getTitle())
.setContentText(note.getDescription());
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notificationBuilder.build());
return false;
}
@Override
public boolean onStopJob(com.firebase.jobdispatcher.JobParameters job) {
Log.e(TAG, "Finished job: " + job.getTag());
return false;
}
}
Thanks
Apparently the reason as to why the listener was never called was that my code kept throwing a null pointer exception where I was displaying the Notification and hence it never got to the point where I was attaching listener and listening for changes in the Database. Moving the code to display the notification inside
onChildAdded
fixed it for me.