Reading Firebase Data, OnDataChange Is Never Called
Solution 1:
There are multiple problems. The most significant is that this processing is not occurring "in the background" as you think. It is running on the main thread. This is a common misunderstanding with Services as described in the documentation:
What is a Service?
Most confusion about the Service class actually revolves around what it is not:
- A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
- A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
An IntentService is a convenient Service subclass for doing work off the main thread.
The while(true)
loop in startTimer()
runs endlessly. The call to addValueEventListener()
in onStartCommend()
is never executed because startTimer()
never returns.
Database change listeners run on the main thread. Because the main thread is blocked by the call to wait()
, the onDataChange()
callback would not be able to run (if the listener were successfully added).
Also, to see if your write to the database in startTimer()
is failing, add a CompletionListener
. The most common reason for failure is permission denied caused by incorrect security rules.
UsersData user1 = new UsersData(castleclash, "name");
databaaseUsers.child("user1").setValue(user1, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Log.d(TAG, "onComplete: success");
} else {
Log.e(TAG, "onComplete: failed", databaseError.toException());
}
}
});
Solution 2:
Have you check out this video from David East? https://youtu.be/lpFDFK44pX8 I follow his method and it helps a lot.
The first line, you should write it like this,
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference
Then, you gonna need to declare another DatabaseReference for each db in console.
DatabaseReference moooww = dbRef.child("nameOfYourDbValue");
The rest shown in the video.
Post a Comment for "Reading Firebase Data, OnDataChange Is Never Called"