当前位置: 首页 > 知识库问答 >
问题:

无法读取或写入Firebase实时数据库

江奕
2023-03-14

首先,我很抱歉我的英语,我希望你能理解。这是我的第一个android应用程序,我尝试使用Firebase进行身份验证和数据库。身份验证工作正常,但我不能读写实时数据库。以下是我的数据库规则和结构:

{
  "rules": {
    ".read": true,
    ".write": true,
  }
}  
{
  "dovelobutto" : {
    "carta" : {
      "cassonetto" : "carta",
      "descrizione" : "bla bla bla",
      "rifiuto" : "carta",
      "valutazione" : 0
    }
  },
  "prova" : {
    "rndm" : "prova"
  }
}

我试图将数据库中的数据添加到reclyclerview中,但我的代码止步于AddValueEventListener。然后我尝试添加一个简单的数据到数据库,但它也不起作用。我也尝试将相同的代码放入一个活动中,但它也不起作用。

package com.example.genovagreen;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SearchView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;


import java.util.ArrayList;
import java.util.List;

public class ButtoFragment extends Fragment {
    private AdapterClass adapter;
    private List<Oggetto> list = new ArrayList<>();
    private DatabaseReference ref;
    private View view=null;
    Button button;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_butto, container,  false);
        button=view.findViewById(R.id.prova);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ref=FirebaseDatabase.getInstance().getReference("prova");
                ref.push().setValue("prova");
                Toast.makeText(getContext(),"ok",Toast.LENGTH_LONG).show();
            }
        });
        fillList();
    return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        fillList();
    }

    public void fillList() {


        FirebaseDatabase db=FirebaseDatabase.getInstance();
        ref=db.getReference("dovelobutto");
        ref.addValueEventListener(new ValueEventListener() {
            //Never run this part
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                Toast.makeText(getContext(), "fillList", Toast.LENGTH_LONG).show();
                for (DataSnapshot ds : snapshot.getChildren()) {
                    String rifiuto = ds.child("rifiuto").getValue(String.class);
                    String cassonetto = ds.child("cassonetto").getValue(String.class);
                    Oggetto ogg = new Oggetto(rifiuto, cassonetto);
                    list.add(ogg);

                }
                RecyclerView recyclerView = view.findViewById(R.id.rv);
                recyclerView.setHasFixedSize(true);
                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
                adapter = new AdapterClass(list);
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(adapter);
                Toast.makeText(getContext(), "adapter settato", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getContext(), "errore db", Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        search();
    }

    public boolean search() {
        SearchView searchView=view.findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                adapter.getFilter().filter(s);
                return false;
            }
        });
        return true;
    }

}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'


android {
    compileSdkVersion 29
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.example.genovagreen"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        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 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'net.sourceforge.jtds:jtds:1.3.1'
    implementation 'com.xwray:groupie:2.1.0'
    implementation 'com.google.android.gms:play-services-basement:17.5.0'
    implementation 'com.google.android.gms:play-services-flags:17.0.0'
    implementation platform('com.google.firebase:firebase-bom:26.1.1')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-core'
    implementation 'com.google.firebase:firebase-database:19.5.1'
    implementation 'com.google.firebase:firebase-auth'
    implementation 'androidx.navigation:navigation-fragment:2.3.2'
    implementation 'androidx.navigation:navigation-ui:2.3.2'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.1"
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
        classpath "com.google.gms:google-services:4.3.4"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

我也有互联网许可在清单`。这是我的LogCat,但是来自我运行Firebase代码的片段的消息是从RecyclerView错误开始的。该错误是因为适配器附加在OnDataChange之后。

2020-12-18 00:04:42.535 29813-29859/com.example.genovagreen D/HostConnection: HostConnection::get() New Host Connection established 0xcade35a0, tid 29859
2020-12-18 00:04:42.537 29813-29859/com.example.genovagreen D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
2020-12-18 00:04:42.537 29813-29859/com.example.genovagreen E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
2020-12-18 00:04:42.688 29813-29859/com.example.genovagreen D/EGL_emulation: eglMakeCurrent: 0xe657f280: ver 2 0 (tinfo 0xe654a130)
2020-12-18 00:04:42.911 29813-29854/com.example.genovagreen D/FA: Connected to remote service
2020-12-18 00:04:42.912 29813-29854/com.example.genovagreen V/FA: Processing queued up service tasks: 5
2020-12-18 00:04:48.097 29813-29813/com.example.genovagreen W/ple.genovagree: Accessing hidden field Landroid/view/View;->mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate; (light greylist, reflection)
2020-12-18 00:04:48.175 29813-29854/com.example.genovagreen V/FA: Inactivity, disconnecting from the service
2020-12-18 00:04:48.190 29813-29854/com.example.genovagreen W/ConnectionTracker: Exception thrown while unbinding
    java.lang.IllegalArgumentException: Service not registered: lu@ed11e26
        at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1562)
        at android.app.ContextImpl.unbindService(ContextImpl.java:1692)
        at android.content.ContextWrapper.unbindService(ContextWrapper.java:717)
        at ci.f(:com.google.android.gms.dynamite_measurementdynamite@204516068@20.45.16 (100700-0):1)
        at ci.d(:com.google.android.gms.dynamite_measurementdynamite@204516068@20.45.16 (100700-0):2)
        at lv.E(:com.google.android.gms.dynamite_measurementdynamite@204516068@20.45.16 (100700-0):9)
        at lf.a(:com.google.android.gms.dynamite_measurementdynamite@204516068@20.45.16 (100700-0):3)
        at ef.run(:com.google.android.gms.dynamite_measurementdynamite@204516068@20.45.16 (100700-0):3)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at iy.run(:com.google.android.gms.dynamite_measurementdynamite@204516068@20.45.16 (100700-0):5)
2020-12-18 00:04:52.301 29813-29813/com.example.genovagreen E/RecyclerView: No adapter attached; skipping layout
2020-12-18 00:04:55.957 29813-29859/com.example.genovagreen D/EGL_emulation: eglMakeCurrent: 0xe657f280: ver 2 0 (tinfo 0xe654a130)
2020-12-18 00:04:55.971 29813-29859/com.example.genovagreen D/EGL_emulation: eglMakeCurrent: 0xe657f280: ver 2 0 (tinfo 0xe654a130)
2020-12-18 00:04:58.210 29813-29859/com.example.genovagreen D/EGL_emulation: eglMakeCurrent: 0xe657f280: ver 2 0 (tinfo 0xe654a130)
2020-12-18 00:04:58.222 29813-29859/com.example.genovagreen D/EGL_emulation: eglMakeCurrent: 0xe657f280: ver 2 0 (tinfo 0xe654a130)
2020-12-18 00:04:59.718 29813-29859/com.example.genovagreen D/EGL_emulation: eglMakeCurrent: 0xe657f280: ver 2 0 (tinfo 0xe654a130)
2020-12-18 00:04:59.733 29813-29859/com.example.genovagreen D/EGL_emulation: eglMakeCurrent: 0xe657f280: ver 2 0 (tinfo 0xe654a130)
2020-12-21 22:30:21.031 30890-30890/com.example.genovagreen V/AudioManager: querySoundEffectsEnabled...
2020-12-21 22:30:21.069 30890-30974/com.example.genovagreen D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-12-21 22:30:21.075 30890-30890/com.example.genovagreen I/HwViewRootImpl: removeInvalidNode all the node in jank list is out of time
2020-12-21 22:30:24.548 30890-30974/com.example.genovagreen W/libEGL: EGLNativeWindowType 0x71c3397e10 disconnect failed
2020-12-21 22:31:46.137 30890-30890/com.example.genovagreen V/AudioManager: querySoundEffectsEnabled...
2020-12-21 22:31:46.165 30890-30974/com.example.genovagreen D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2020-12-21 22:31:46.171 30890-30890/com.example.genovagreen I/HwViewRootImpl: removeInvalidNode all the node in jank list is out of time
2020-12-21 22:31:49.650 30890-30974/com.example.genovagreen W/libEGL: EGLNativeWindowType 0x71b12424d0 disconnect failed

共有1个答案

丌官晨
2023-03-14

将此添加到您的构建中。分级依赖项:

dependencies {
implementation 'com.google.android.gms:play-services-basement:17.4.0'
implementation 'com.google.firebase:firebase-analytics:18.0.0'
}
 类似资料:
  • 我正在尝试用Firebase制作一个简单的Android应用程序。 目前,我只是试图从Firebase实时保存用户数据库。但由于某种原因它不起作用。另一方面,身份验证工作完美。 数据库本身没有显示任何内容。它总是显示“null” 我一直在关注这个YouTube教程,并一直在做一些类似的事情。 当我尝试创建一个用户并将其发送到数据库时,运行的程序没有给出任何答案。我有一个进度条,一旦setValue

  • 我已经花了几个小时阅读产品分支中的0和1。请在Firebase数据库有经验的人帮助我:(

  • 我正在尝试获取我的用户名,并在应用程序打开时向他/她问好。但我无法根据某个用户的uid获取数据。当我运行应用程序时,祝酒词从未真正出现。 数据库结构 密码

  • 我设法将数据插入身份验证,但无法插入数据库: 代码: 错误: E/AndroidRuntime:致命异常:主进程:com。实例budgetingapp,PID:11507 java。lang.RuntimeException:在类androidx上找到了名称getText的冲突获取程序。appcompat。小装置。AppCompativeText位于com。谷歌。火基。消防商店。util。Cust

  • 我正在一个聊天应用程序,其中消息存储在firebase实时数据库。现在,如果我创建一个如下所示的节点(Chats-Better-A-ID和-B-ID是自动生成的聊天室密钥),那么我想知道当用户S在聊天应用程序中打开与用户T聊天时,so数据库将只读取存储在Chats-Better-S-T-ID中的消息,而不会读取其他聊天室消息!?我说的对吗?如果是,那么它会降低定价吗? 或 如果我存储如下所示的数据

  • 我正在尝试将有关集合用户中注册用户的数据写入我的Cloud Firestone用户,当然它必须与授权中的UID代码相关联(注册/登录系统正常工作并在我的Firebase中编写auth)。 XML注册按钮: JAVA寄存器: 。。。 。。。 在Cloud Firestone中,我刚刚创建了集合用户。我注意到在工具中 ✓ 已连接 但即使我已经点击并似乎构建正确,底部的“将云Firestone添加到你的