首页 > 解决方案 > Firebase realtime database is not connecting

问题描述

Iam trying to use firebase real-time database. I have set rules to true and in my project added all required dependencies and also internet permission. My mobile is very well connected to the wifi.

When I tried to use write the data then it's not working. So I checked the status as per documentation and it's showing dB is not connected to my app.

DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        boolean connected = snapshot.getValue(Boolean.class);
        if (connected) {
            Log.d(TAG, "connected");
        } else {
            Log.d(TAG, "not connected");
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        Log.w(TAG, "Listener was cancelled");
    }
});

Am I doing anything wrong hwre?

Appreciate help.

PD

标签: androiddatabasefirebasefirebase-realtime-database

解决方案


您应该添加查询

DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference();
Query query = connectedRef.child("info/connected");
query.addValueEventListener(new ValueEventListener() { 
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        boolean connected = snapshot.getValue(Boolean.class);
        if (connected) {
        Log.d(TAG, "connected");
        } else {
        Log.d(TAG, "not connected");
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        Log.w(TAG, "Listener was cancelled");
    }
});

推荐阅读