简体   繁体   中英

Firebase Realtime database read not working (Android Java)

I am using realtime database in order to transfer information from a Windows computer to an Android phone. I am able to write data from the Windows PC to the database, but for some reason I am not able to read it off of the database to the Android. I am using Android studio Java. Here is the code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference userRef = rootRef.child("users");
    userRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String name = ds.getKey();
                PCs.add(new PC(name));
            }
            for (int i = 0; i < PCs.size(); i++) {
                PCs.get(i).setIp(dataSnapshot.child(PCs.get(i).getName()).child("ip").getValue(String.class));
                PCs.get(i).setConnected(dataSnapshot.child(PCs.get(i).getName()).child("status").getValue(Boolean.class));
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });

It just doesn't go into the onDataChange method, but also doesn't go to the onCancelled method.

If it goes into neither of the callbacks, you may not have configured the connection to the database correctly. An easy way to fix that is to pass the database URL in the code, rather than depending on the google-services.json file:

DatabaseReference rootRef = FirebaseDatabase.getInstance("your database URL").getReference();

In general, you should never ignore possible errors, and implement onCancelled . At its minimum that should look like:

public void onCancelled(@NonNull DatabaseError error) {
    throw error.toException();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM