You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Java调用Firebase查询返回null问题求助

Firebase Realtime Database Query Returns Null (Android)

Your Firebase Database Structure

"look-twopointo": {
  "0": {
    "comment": "Hi",
    "Text1": "Hello",
    "Text2": "Bonsoir",
    "type": "Bonjour",
    "version": "4.0.6"
  }
}

Your Current Code

button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        mDatabase = FirebaseDatabase.getInstance().getReference().child("0");// pay attention to the this path reference
        // Read from the database
        Query query = mDatabase.child("version")/*.orderByChild("Text1")*/.equalTo("4.0.6")/*.startAt("d")/*.endAt("Dude")*/;
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                //String value = dataSnapshot.getValue(String.class);
                //these three lines below are probably the problem
                String value = (String) dataSnapshot.getValue();
                System.out.println(value);
                Text.setText(value);
            }

            // Likely omitted in your code, but critical for error handling
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w("Firebase", "Query cancelled", databaseError.toException());
            }
        });
    }
});

Why You're Getting Null

Let's break down the key issues:

  1. Incorrect Database Path
    Your top-level node is look-twopointo, but your code skips this and directly references child("0") from the root. Firebase can't find a node 0 at the root, so it returns null immediately.

  2. Misstructured Query
    Even if you fixed the path, your query targets mDatabase.child("version").equalTo("4.0.6")—this would only check if the version node itself equals "4.0.6", but it doesn't align with how you want to fetch data (either reading the known "0" node's version or querying for nodes with that version).

  3. DataSnapshot Handling
    You're trying to cast the entire snapshot to a String directly. This only works if the snapshot points to a raw string value; for node objects, this approach will fail.

Fixes to Resolve the Issue

Step 1: Fix the Core Database Path

First, point to the correct top-level node:

mDatabase = FirebaseDatabase.getInstance().getReference().child("look-twopointo");

Step 2: Adjust the Query (Two Common Scenarios)

Scenario 1: Read the version value from the known "0" node
If you just need the version string from the specific "0" node, you don't need a query—reference it directly:

DatabaseReference versionRef = mDatabase.child("0").child("version");
versionRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String version = dataSnapshot.getValue(String.class);
        if (version != null) {
            System.out.println(version);
            Text.setText(version);
        } else {
            System.out.println("Version value is missing or null");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e("Firebase", "Failed to fetch version", databaseError.toException());
    }
});

Scenario 2: Query all nodes under look-twopointo with version "4.0.6"
If you have multiple nodes (like "0", "1", etc.) and want to find any with the target version, use orderByChild and equalTo:

Query query = mDatabase.orderByChild("version").equalTo("4.0.6");
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (!dataSnapshot.exists()) {
            System.out.println("No nodes found with version 4.0.6");
            return;
        }
        // Loop through matching nodes (even if only one exists)
        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
            String version = snapshot.child("version").getValue(String.class);
            System.out.println(version);
            Text.setText(version);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e("Firebase", "Query failed", databaseError.toException());
    }
});

Step 3: Verify Database Rules

Ensure your Firebase Realtime Database rules allow read access (for development, you can use temporary open rules—never leave this for production):

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Step 4: Real Device vs. Simulator Check

Using a real device shouldn't cause this issue as long as:

  • The device has a stable internet connection
  • You've added the google-services.json file correctly to your Android project
  • If using authentication, the device is signed into the correct Google account linked to your Firebase project

内容的提问来源于stack exchange,提问作者Jose Salgado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:05:16