简体   繁体   English

如何从 Android 中的 Firebase 实时数据库接收特定信息?

[英]How to receive specific information from Firebase Realtime db in Android?

I'm creating a loyalty application with Android Studio and Firebase Real time Database.我正在使用 Android Studio 和 Firebase 实时数据库创建忠诚度应用程序。

Each user registered with the application will have a unique QR Code assigned to their account.使用该应用程序注册的每个用户都将有一个唯一的二维码分配给他们的帐户。

When the user registers in the application, there information is stored in the database and will be called back into the application.当用户在应用程序中注册时,这些信息会存储在数据库中,并会被回调到应用程序中。 The database scheme can be seen below.数据库方案可以在下面看到。

在此处输入图片说明

I am trying to call back the user's email address from firebase using event listner :我正在尝试使用事件监听器从 firebase 回拨用户的电子邮件地址:

 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String email = dataSnapshot.child("email").getValue().toString();

            Toast.makeText(HomeScreen.this, email
                    , Toast.LENGTH_SHORT).show();


        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getCode());

        }
    });

Declared instances:声明的实例:

 FirebaseDatabase database = FirebaseDatabase.getInstance();
 databaseReference = database.getReference("Customers");
 firebaseAuth = FirebaseAuth.getInstance();
 firebaseUser = firebaseAuth.getCurrentUser();

When running I keep getting null pointer exception.运行时我不断收到空指针异常。

2019-12-04 12:45:47.714 25381-25381/com.example.alicearmstrong.coffeysloyalty E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.alicearmstrong.coffeysloyalty, PID: 25381 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference at com.example.alicearmstrong.coffeysloyalty.HomeScreen$1.onDataChange(HomeScreen.java:71) at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75) at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63) at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7356) at java.lang.reflect.Method.invoke(Na 2019 年 12 月 4 日 12:45:47.714 25381-25381/com.example.alicearmstrong.coffeysloyalty E/AndroidRuntime:致命异常:主进程:com.example.alicearmstrong.coffeysloyalty,PID:253388000 异常点在 com.example.alicearmstrong.coffeysloyalty.HomeScreen$1.onDataChange(HomeScreen.java:71) 在 com.google.firebase 的空对象引用上调用虚拟方法“java.lang.String java.lang.Object.toString()” .database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75) 在 com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase -database@@16.0.4:63) 在 com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55) 在 android.os。 Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread) .java:7356) 在 java.lang.reflect.Method.invoke(Na tive Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) tive Method) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Anyone able to help to resolve?有谁能帮忙解决吗?

You need to iterate inside the random id to be able to retrieve the email field:您需要在随机 id 内迭代才能检索email字段:

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
  for(DataSnapshot ds : dataSnapshot.getChildren()){
    String email = ds.child("email").getValue().toString();

    Toast.makeText(HomeScreen.this, email
            , Toast.LENGTH_SHORT).show();
    }
}

No, you're doing it wrong.不,你做错了。

Judging by your database schema, your databaseReference.addValueEventListener(...) call gives you access to a datasnapshot which is basically a list of all the uIDs.根据您的数据库架构判断,您的databaseReference.addValueEventListener(...)调用使您可以访问数据快照,它基本上是所有 uID 的列表。

Therefore, when you perform database.child("email").getValue().toString() , it is bound to be null because the datasnapshot only contains uId objects and no direct email property.因此,当您执行database.child("email").getValue().toString() ,它必然为 null,因为 datasnapshot 仅包含 uId 对象,而没有直接的 email 属性。 It'd always result in a NullPointerException.它总是会导致 NullPointerException。

Solution:解决方案:

Since you are trying to retrieve the email of a specific user, simply add the user's id into your databaseReference object, that way, you'd be able to get the email directly with the rest of your approach.由于您正在尝试检索特定用户的电子邮件,只需将用户的 id 添加到您的 databaseReference 对象中,这样,您就可以通过其余方法直接获取电子邮件。

Here's an illustration:这是一个插图:

// this variable represents the uId of specific user you want to retrieve the email of
String userId = "INSERT_USERID_HERE";

// add userId above as a child to your databaseReference object
databaseReference = database.getReference("Customers").child("userId");

// valueEventListener call
databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        String email = dataSnapshot.child("email").getValue().toString();
        Toast.makeText(HomeScreen.this, email, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Android Studio 中从实时 Firebase 中检索特定用户 - How to retrieve specific user from realtime Firebase in Android Studio 如何在android中使用firebase接收附加信息 - How to receive additional information by using firebase in android 无法在 Android Studio 中从 Firebase 实时数据库检索数据 - Can't retrieve data from Firebase Realtime db in Android Studio 使用Firebase的实时数据库-检索特定信息 - Realtime database using firebase - retrieving a specific information 如何在 Android 中实时检索 Firebase 中的图像? - How to retrieve images from Firebase in realtime in Android? Android Firebase数据库datasnapshot从错误的数据库目录中提取信息 - Android Firebase db datasnapshot pulling information from wrong db directory 如何使用 Android Studio 从 Firebase 实时数据库中的节点检索特定数据? - How to retrieve a specific data from a node in Firebase Realtime Database using Android Studio? 如何从包含唯一键的firebase实时数据库中获取字符串 - How to get string from firebase realtime db that contain in unique key 如何从 Firebase 实时数据库中检索特定数据? - How to retrieve Specific Data from Firebase Realtime Database? 如何从Android中的firebase实时数据库中获取最后一个数据 - How to get the last data from realtime database of firebase in Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM