Android端Firebase连接失败求助:无法写入数据
问题情况
尝试将Android Studio项目与Firebase后端连接,已创建约30个项目,严格按照Tools>Firebase指引操作始终无法成功连接。写入数据时,监听器无任何错误提示,写入步骤直接被跳过,既不触发成功回调也不触发失败回调。
已尝试的解决方法
- 添加网络权限
- 改用Firestore替代实时数据库
- 仅尝试写入简单字符串"Hello world"和包含姓名、身高的User对象,均无效
- 已配置Firebase客户端助手及所有依赖,
google-services.json文件验证无误
相关代码
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); System.out.println("-----------"); myRef.setValue("Hello World").addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void unused) { System.out.println("WRITING DATA"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { System.out.println("NOT WRITING DATA"); System.out.println(e.getMessage()); } }); System.out.println("-----------"); }
Logcat输出
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/.firebasepresto: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/.firebasepresto: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10160; state: ENABLED
W/ziparchive: Unable to open '/data/data/com.example.firebasepresto/code_cache/.overlay/base.apk/classes3.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~UEPoBOUjRRSFIS2ZrGSd6w==/com.example.firebasepresto-CKvpL_AgSxGH5wAa2Mm8FQ==/base.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~UEPoBOUjRRSFIS2ZrGSd6w==/com.example.firebasepresto-CKvpL_AgSxGH5wAa2Mm8FQ==/base.dm': No such file or directory
D/nativeloader: Configuring classloader-namespace for other apk /data/app/~~UEPoBOUjRRSFIS2ZrGSd6w==/com.example.firebasepresto-CKvpL_AgSxGH5wAa2Mm8FQ==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~UEPoBOUjRRSFIS2ZrGSd6w==/com.example.firebasepresto-CKvpL_AgSxGH5wAa2Mm8FQ==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.firebasepresto
V/GraphicsEnvironment: ANGLE Developer option for 'com.example.firebasepresto' set to: 'default'
V/GraphicsEnvironment: ANGLE GameManagerService for com.example.firebasepresto: false
V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/CompatibilityChangeReporter: Compat change id reported: 183155436; UID 10160; state: ENABLED
I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
I/FirebaseInitProvider: FirebaseApp initialization successful
D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
W/ziparchive: Unable to open '/data/user_de/0/com.google.android.gms/app_chimera/m/0000000b/DynamiteLoader.dm': No such file or directory
W/ziparchive: Unable to open '/data/user_de/0/com.google.android.gms/app_chimera/m/0000000b/DynamiteLoader.dm': No such file or directory
D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:88 and remote module com.google.android.gms.measurement.dynamite:88
I/DynamiteModule: Selected local version of com.google.android.gms.measurement.dynamite
V/FA: onActivityCreated
W/.firebasepresto: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
W/.firebasepresto: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
D/CompatibilityChangeReporter: Compat change id reported: 210923482; UID 10160; state: ENABLED
V/FA: App measurement collection enabled
V/FA: App measurement enabled for app package, google app id: com.example.firebasepresto, 1:325373313014:android:dbb374537f8f82e24f11d7
I/FA: App measurement initialized, version: 76003
I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.example.firebasepresto
D/FA: Debug-level message logging enabled
I/System.out: -----------
I/System.out: -----------
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x76befcc19990, tid 17826
D/FA: Resetting session stitching token to not null
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
W/OpenGLRenderer: Failed to initialize 101010-2 format, error = EGL_SUCCESS
D/EGL_emulation: eglCreateContext: 0x76befcc19a50: maj 3 min 0 rcv 3
D/TrafficStats: tagSocket(78) with statsTag=0xffffffff, statsUid=-1
D/EGL_emulation: eglMakeCurrent: 0x76befcc19a50: ver 3 0 (tinfo 0x76c12462e080) (first time)
V/FA: Connecting to remote service
V/FA: Detected application was in foreground
V/FA: Session started, time: 4685124
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x76befcc18550, tid 17826
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3f3ffe000 size 0x2000
V/FA: Connection attempt already in progress
I/FA: Tag Manager is not found and thus will not be used
W/Gralloc4: allocator 4.x is not supported
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
W/Parcel: Expecting binder but got null!
V/FA: Connection attempt already in progress
V/FA: Activity resumed, time: 4684802
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 7
V/FA: Inactivity, disconnecting from the service
可能的解决方法
1. 检查Firebase实时数据库规则
默认规则下未登录用户无法读写数据,暂时修改为公开读写(仅测试用,上线前需改回安全规则):
{ "rules": { ".read": true, ".write": true } }
修改后等待5分钟左右让规则生效,再测试写入。
2. 启用Firebase实时数据库调试日志
在代码中添加日志开关,查看底层连接细节:
FirebaseDatabase.getInstance().setLogLevel(Logger.Level.DEBUG);
添加到FirebaseDatabase.getInstance()之前,运行后查看Logcat中FirebaseDatabase相关日志,确认是否有连接失败、权限拒绝等信息。
3. 统一Firebase依赖版本
确保项目中所有Firebase相关依赖版本一致,避免版本不兼容:
// 项目根目录build.gradle classpath 'com.google.gms:google-services:4.4.1' // app模块build.gradle implementation 'com.google.firebase:firebase-database:20.3.0' implementation 'com.google.firebase:firebase-analytics:21.5.0'
4. 验证设备网络连接
模拟器可能存在网络异常,尝试用真机测试,或检查模拟器能否正常访问外网。
5. 重新下载google-services.json
从Firebase控制台重新下载最新配置文件,替换项目中的旧文件,然后执行Clean Project再Rebuild。
6. 暂时禁用离线持久化
如果启用了离线持久化但网络未连接,数据会存在本地,不会触发远程回调,可暂时关闭测试:
FirebaseDatabase.getInstance().setPersistenceEnabled(false);
内容的提问来源于stack exchange,提问作者Alvaro G.

