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

无法从Android Studio向Firebase推送数据,实时数据库配置受阻

问题描述

我在Firebase Realtime Database入门流程中,无法完成第2步“将实时数据库添加到应用”,怀疑这是导致Android Studio无法向Firebase推送数据的原因。

执行以下代码时,try-catch块和监听回调中的日志均无输出:

try {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("foodAccount");
    myRef.setValue("heloooo");
    if (myRef == null) {
        System.out.println("faillll");
    }
    myRef.setValue("foodAccountData")
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    System.out.println("Worked");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    System.out.println("Not worked");
                }
            });
} catch (Exception e) {
    e.printStackTrace();
}

AndroidManifest.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">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Test"
        tools:targetApi="31">
        <activity
            android:name=".WorkerOrderDetailActivity"
            android:exported="false" />
        <activity
            android:name=".WorkerOrderNoActivity"
            android:exported="false" />
        <activity
            android:name=".WorkerMainActivity"
            android:exported="false" />
        <activity
            android:name=".LocationActivity"
            android:exported="false" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyCt0I6k3QLaB3XQrNZE9uAae6kXKnoLg4M" />

        <activity
            android:name=".MapsActivity"
            android:exported="false"
            android:label="@string/title_activity_maps" />

        <meta-data
            android:name="com.google.gms.version"
            android:exported="true"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".ProfileActivity"
            android:exported="false" />
        <activity
            android:name=".SetProfileActivity"
            android:exported="false" />
        <activity
            android:name=".HomeActivity"
            android:exported="false" />
        <activity
            android:name=".SignUpActivity"
            android:exported="false" />
        <activity
            android:name=".SummaryActivity"
            android:exported="false" />
        <activity
            android:name=".infoActivity"
            android:exported="false" />
        <activity
            android:name=".SignInActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

build.gradle(Module级别)配置

plugins {
    id 'com.android.application'
    id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    id 'com.google.gms.google-services'
}

android {
    namespace 'com.example.test'
    compileSdk 33

    dataBinding {
        enabled = true
    }

    buildscript {
        repositories {
            google()
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:7.0.4'
        }
    }


    defaultConfig {
        applicationId "com.example.test"
        minSdk 28
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildFeatures{
        viewBinding true
    }

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


}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.8.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.android.car.ui:car-ui-lib:2.4.0'
    implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    implementation "androidx.cardview:cardview:1.0.0"
    implementation "com.google.android.material:material:1.9.0-beta01"
    implementation "androidx.recyclerview:recyclerview:1.3.0"
    implementation "com.google.android.material:material:1.8.0"
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    implementation 'com.google.android.gms:play-services-maps:18.1.0'
    implementation 'com.google.maps:google-maps-services:0.2.5'
    implementation 'com.google.maps.android:android-maps-utils:2.3.0'
    implementation 'com.google.android.libraries.places:places:3.0.0'
    implementation 'com.google.firebase:firebase-database'

}
解决方案
  1. 解决Realtime Database添加失败问题

    • 确认Firebase控制台已创建Realtime Database实例,且实例处于“运行中”状态。
    • 检查google-services.json文件是否正确放置在app/目录下,且文件内的数据库URL与控制台实例URL一致。
    • 重新执行Firebase Assistant中的“添加实时数据库到应用”流程,确保所有配置步骤完成。
  2. 排查数据推送无日志问题

    • 替换System.out.println为Android官方日志工具Log.d/Log.e,System.out输出可能不会显示在Logcat中。修改后代码示例:
      try {
          FirebaseDatabase database = FirebaseDatabase.getInstance();
          DatabaseReference myRef = database.getReference("foodAccount");
          Log.d("FirebaseDB", "数据库引用初始化完成: " + myRef.toString());
          
          myRef.setValue("foodAccountData")
                  .addOnSuccessListener(new OnSuccessListener<Void>() {
                      @Override
                      public void onSuccess(Void aVoid) {
                          Log.d("FirebaseDB", "数据写入成功");
                      }
                  })
                  .addOnFailureListener(new OnFailureListener() {
                      @Override
                      public void onFailure(@NonNull Exception e) {
                          Log.e("FirebaseDB", "数据写入失败", e);
                      }
                  });
      } catch (Exception e) {
          Log.e("FirebaseDB", "初始化异常", e);
      }
      
    • 检查Firebase数据库安全规则,开发阶段可临时设置为允许读写:
      {
        "rules": {
          ".read": true,
          ".write": true
        }
      }
      
    • 移除重复依赖:build.gradle中同时引入了firebase-database-ktx和firebase-database,保留其一即可(推荐保留ktx版本)。
    • 确认设备网络正常,能访问Firebase服务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:44:59