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

C# Android应用读取Firebase数据库data/test节点数据问题求助

无法读取Firebase Realtime Database中data/test子节点数据的问题

开发C# Android应用时,无法从Firebase Realtime Database读取data/test子节点的数据,网上找不到易懂的解决方法。

相关情况说明

  • 数据库结构:存在data节点,其下包含test子节点并存储了对应数据
  • 界面表现:初始显示"starting value",尝试读取后显示Firebase.Database.Query.childQuery,而非目标数据

已成功建立连接的代码

var options = new Firebase.FirebaseOptions.Builder()
    .SetApplicationId("1:191485419818:android:c3bef44f30f167e537be53")
    .SetApiKey("AIzaSyBwLcDZ3wGyzkwP6SobH8KDDsl5Vq227Vg")
    .Build();

if (fireApp == null)
    fireApp = FirebaseApp.InitializeApp(this, options);

auth = FirebaseAuth.GetInstance(fireApp);

string FirebaseURL = "https://plsbrothers-default-rtdb.firebaseio.com/";
FirebaseClient rootNode = new FirebaseClient(FirebaseURL);

dataNode = rootNode.Child("data");
userNode = rootNode.Child("users");

当前尝试读取的代码(存在问题)

// 问题:直接ToString()得到的是查询对象的字符串表示,而非实际数据
string testDisplay = dataNode.Child("test").ToString();
  
TextView currentCharacterName = FindViewById<TextView>(Resource.Id.test);
currentCharacterName.Text = testDisplay;

XML布局代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:layout_height="match_parent">


<Button
         android:layout_width="match_parent"
         android:layout_height="100dp"
         android:text="save"
         android:textSize="25dp"
         android:textColor="#000"
         android:id="@+id/Btn"
         android:layout_marginTop="280dp"
/>

<TextView
    android:text="starting value"
    android:textSize="30dp"
    android:textColor="#000"
    android:layout_marginTop="100dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/test" />
</RelativeLayout>

解决方法

1. 修正读取逻辑(异步获取数据)

Firebase Realtime Database的读取是异步操作,不能直接对查询对象调用ToString(),需要使用GetValueAsync()方法获取实际数据。修改读取代码为异步方法,示例如下:

// 确保在OnCreate中绑定按钮点击事件:Btn.Click += Btn_Click;
private async void Btn_Click(object sender, EventArgs e)
{
    // 异步获取test节点的数据
    var testDataSnapshot = await dataNode.Child("test").GetValueAsync();
    if (testDataSnapshot.Exists)
    {
        string testDisplay = testDataSnapshot.Value.ToString();
        TextView currentCharacterName = FindViewById<TextView>(Resource.Id.test);
        currentCharacterName.Text = testDisplay;
    }
    else
    {
        // 处理节点不存在的情况
        FindViewById<TextView>(Resource.Id.test).Text = "数据不存在";
    }
}

2. 检查数据库权限

确保Firebase Realtime Database的规则允许读取操作,测试阶段可临时设置为公开读写(生产环境需调整为安全规则):

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:05:24