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

Android真机无法显示Firebase Realtime Database数据问题排查

问题:Firebase Realtime Database真机加载数据后页面空白,控制台可正常打印数据

已将Firebase Realtime Database集成到Android应用,模拟器上数据能正常加载展示;真机运行时页面空白,但控制台可正常打印Firebase返回的数据,怀疑是Android Manifest缺少权限标签,相关配置及代码如下:


Android Manifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.studydatascience">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission
        android:name="android.permission.READ_PHONE_STATE"
        tools:node="remove" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:requestLegacyExternalStorage="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/Theme.StudyDataScience">
        <activity
            android:name=".newActivity"
            android:exported="false" />

        <..  some activities  ..>

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-1234567891234567~0123456789" />


        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.StudyDataScience.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Build.gradle文件

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdkVersion 31
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.rajendra.studydatascience"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 12
        versionName "2.8"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation 'com.google.ads.mediation:facebook:6.3.0.0'
    implementation 'com.google.android.ads:mediation-test-suite:1.5.0'
    implementation 'com.facebook.android:audience-network-sdk:6.3.0'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.navigation:navigation-fragment:2.3.4'
    implementation 'androidx.navigation:navigation-ui:2.3.4'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'com.google.firebase:firebase-database:20.3.0'
    testImplementation 'junit:junit:4.13.2'
    implementation 'com.google.android.gms:play-services-ads:20.5.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.17'
    implementation 'com.davemorrissey.labs:subsampling-scale-image-view:3.10.0'
    implementation 'androidx.work:work-runtime-ktx:2.7.1'
    implementation 'com.android.volley:volley:1.2.1'
    implementation 'com.google.firebase:firebase-core:21.1.1'
}

Firebase数据获取代码

public void fetch(String keyValue){
    Adapter adapter1 = new Adapter(newActivity.this,arrayList);

    recyclerView = findViewById(R.id.view_recycler);
    recyclerView.setAdapter(adapter1);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    // Initialize Firebase
    DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("questions").child(keyValue);
    cartListRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        int questionCount = 0;
        for (DataSnapshot dataSnapshot:snapshot.getChildren()){
            String answer = dataSnapshot.child("answer").getValue(String.class);
            String question = dataSnapshot.child("question").getValue(String.class);
            answer = answer.replace("\\n", "\n").trim();
            arrayList.add(new QA(question,answer));
            Log.d("TAG", "onDataChange: "+answer);
}

Firebase数据库规则

Firebase数据库规则


示例Firebase数据库JSON

{ 
"questions": {
"machine learning": [
  {
    "answer": "Tensor has three indices where the first points to the row, the second to the column and the third one to the axis",
    "question": "What is a Tensor?"
  }
],
"python": [
  {
    "answer": "Different data structures in Python include \n Builtin Data Structures:\n List, Dictionary, Tuple, Set \n UserDefined Data Structure:\n Stack, Queue, Tree, Linked List, Graph, HashMap",
    "question": "What are the different data structures in Python?"
  }
],
"deep learning": [
  {
    "answer": "perceptron is a singlelayer neural network. It consists of input value, weight and bias, activation function. Input value is multiplies with weight and added to bias, then activation function is applied to it.",
    "question": "What is a perceptron?"
  }
]}}

解决方案

1. 核心修复:通知Adapter数据更新

控制台能打印数据说明Firebase请求正常,页面空白是因为RecyclerView的Adapter没有收到数据变化通知。修改数据获取代码,在添加数据后调用notifyDataSetChanged():

public void fetch(String keyValue){
    arrayList.clear(); // 清空旧数据,避免重复加载
    Adapter adapter1 = new Adapter(newActivity.this, arrayList);

    recyclerView = findViewById(R.id.view_recycler);
    recyclerView.setAdapter(adapter1);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    
    DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("questions").child(keyValue);
    cartListRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            arrayList.clear();
            for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                String answer = dataSnapshot.child("answer").getValue(String.class);
                String question = dataSnapshot.child("question").getValue(String.class);
                // 增加空值判断,避免无效数据
                if (answer != null && question != null) {
                    answer = answer.replace("\\n", "\n").trim();
                    arrayList.add(new QA(question, answer));
                    Log.d("TAG", "onDataChange: "+answer);
                }
            }
            adapter1.notifyDataSetChanged(); // 关键:通知RecyclerView刷新视图
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Log.e("TAG", "Firebase数据获取失败: " + error.getMessage());
        }
    });
}

2. 权限排查(非当前问题核心)

你的Manifest已添加INTERNET和ACCESS_NETWORK_STATE权限,且控制台能打印数据,说明权限无问题。若仍有疑虑,可确认:

  • 真机未禁用应用的网络权限
  • network_security_config.xml未限制Firebase域名访问(默认配置无需额外修改)

3. 其他可能排查点

  • 检查RecyclerView的宽高是否设置为match_parent,避免因布局尺寸为0导致空白
  • 确认Adapter的onBindViewHolder方法正确绑定数据到Item视图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:08:10