简体   繁体   English

Android:从Firebase数据库检索特定用户的数据

[英]Android: Retrieve data of a specific user from a Firebase database

I am trying to read "specific" data from my firebase realtime database. 我正在尝试从firebase实时数据库中读取“特定”数据。 I have seen examples of getting all data from a table and going through it to find the data record you want, but that is definitly not a recommended safe practice. 我已经看到了一些示例,这些示例从表中获取所有数据并遍历该表以查找所需的数据记录,但这绝对不是推荐的安全做法。

Below is how I save my data 以下是我保存数据的方式

private void saveInDatabase(String email)
    {
        // Write a message to the database
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("user");
        String key = myRef.push().getKey();

        User user = new User();
        user.setCountry("United States");
        user.setEmail(email);
        user.setFirstName("John");
        user.setLastName("Doh");
        user.setGender("Male");

        myRef.child(key).setValue(user);

    }

Well that works great. 很好,效果很好。 But now I need to retrieve the data record from the user table, that is only belong to John . 但是现在我需要从user表中检索数据记录,该数据记录仅属于John If I do this with MySQL, it will be smething like select * from user where primaryKey =JOHN_PRYMARY_KEY 如果我使用MySQL执行此操作,将会像select * from user where primaryKey =JOHN_PRYMARY_KEY

I gave it a try, check below. 我尝试了一下,请在下面检查。

database.getReference("user" + FirebaseAuth.getInstance().getCurrentUser().getUid());

I am really not sure how I can proceed from here, I see no method to go forward. 我真的不确定如何从这里继续前进,我看不到前进的方法。 Please advice. 请指教。

UPDATE UPDATE

I tried the answers from peter haddad and others. 我尝试了彼得·哈达德和其他人的答案。 When I try to get the data from DataSnapshot, it throws a NullPointerException. 当我尝试从DataSnapshot获取数据时,它将引发NullPointerException。 The OnDataChanged is getting fired. OnDataChanged被解雇了。 Below is my database. 下面是我的数据库。

在此处输入图片说明

I tried to get data in 3 different ways, check below. 我尝试以3种不同的方式获取数据,请检查以下内容。

----No 1---- ----没有1 ----

private void getUserData()
    {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("user");

        reference.orderByChild("email").equalTo(FirebaseAuth.getInstance().getCurrentUser().getEmail()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot datas: dataSnapshot.getChildren()){
                    String familyname=datas.child("familyName").getValue().toString();
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }

----No 2---- ----没有2 ----

private void getUserData()
{
    FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
    String userid=user.getUid();
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("user");
    reference.child(userid).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String email = dataSnapshot.getValue(User.class).getEmail();
            String firstName = dataSnapshot.getValue(User.class).getFirstName();
            Log.d("Datasnapshot",email+" "+firstName);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

----No 3---- ----没有3 ----

private void getUserData() {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("user");

    Query specific_user = myRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
    specific_user.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //here you will get the data
                    String email = dataSnapshot.getValue(User.class).getEmail();
                    String firstName = dataSnapshot.getValue(User.class).getFirstName();
                    Log.d("Datasnapshot", email + " " + firstName);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {



                }
            });
}

This is the error I get. 这是我得到的错误。 Based on the codeset I use, the place where the Null pointer trigger get different, the normal behavior. 根据我使用的代码集,空指针触发的位置会有所不同,这是正常行为。

rebaseauth D/NetworkSecurityConfig: No Network Security Config specified, using platform default
04-25 11:49:46.340 31202-31271/com.example.yohan.firebaseauth V/FA: Inactivity, disconnecting from the service
04-25 11:49:47.793 31202-32166/com.example.yohan.firebaseauth W/PersistentConnection: pc_0 - Using an unspecified index. Consider adding '".indexOn": "email"' at user to your security and Firebase Database rules for better performance
04-25 11:49:47.794 31202-31202/com.example.yohan.firebaseauth D/AndroidRuntime: Shutting down VM
04-25 11:49:47.794 31202-31202/com.example.yohan.firebaseauth E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.yohan.firebaseauth, PID: 31202
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                                    at com.example.yohan.firebaseauth.MainActivity$6.onDataChange(MainActivity.java:249)
                                                                                    at com.google.firebase.database.Query$1.onDataChange(Unknown Source)
                                                                                    at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
                                                                                    at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                                                                                    at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

You need to do the query: 您需要执行查询:

 orderByChild("FirstName").equalTo(name); 
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("user");

reference.orderByChild("firstName").equalTo(name).addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
   String familyname=datas.child("familyName").getValue().toString();
    }
 }
   @Override
public void onCancelled(DatabaseError databaseError) {
  }
 });

Assuming you have this database: 假设您有此数据库:

user
  randomid
     firstName: John
     familyName: familyName_here

Another way is to use the userid to be able to retrieve the data, but as I see in the question you are saving a random id using push() . 另一种方法是使用用户ID来检索数据,但是正如我在问题中看到的那样,您正在使用push()保存随机ID。

You need to retrieve the userid: 您需要检索用户标识:

FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();

then add it to the database: 然后将其添加到数据库中:

 myRef.child(userid).setValue(user);

then to retrieve data only for John: 然后仅检索John的数据:

FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("user");
reference.child(userid).addListenerForSingleValueEvent(new ValueEventListener() {..}
Query specific_user = myRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
      specific_user.addListenerForSingleValueEvent(
              new ValueEventListener() {
              @Override
              public void onDataChange(DataSnapshot dataSnapshot) {
                     //here you will get the data
                  }

              @Override
              public void onCancelled(DatabaseError databaseError) {    
                                           }
                           });

You have to collect the response from firebase to somePOJO Class 您必须收集从firebase到somePOJO类的响应

follow link : https://firebase.google.com/docs/database/admin/retrieve-data 跟随链接: https : //firebase.google.com/docs/database/admin/retrieve-data

As you can see in onDataChange() the response is collected in Post.class which is POJO class. 如您在onDataChange()中所见,响应是在POJO类Post.class中收集的。

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

相关问题 从Firebase数据库中检索特定用户的数据 - Retrieve data of a specific user from a Firebase database 如何从 Firebase 实时数据库中检索具有 UID 的特定用户的特定数据 - How to retrieve specific data of a specific user with UID from a Firebase realtime database 从 firebase 数据库 Android 保存和检索数据 - Save and retrieve data from firebase database Android 如何在firebase数据库中检索特定孩子的数据 - android studio/java? - How to retrieve data for a specific child in firebase database - android studio/ java? 如何使用 Android Studio 从 Firebase 实时数据库中的节点检索特定数据? - How to retrieve a specific data from a node in Firebase Realtime Database using Android Studio? 如何使用 Android 在 Firebase 实时数据库中检索经过身份验证的用户的用户数据 - How to retrieve user data of authenticated users in Firebase Realtime Database with Android 如何在 Android Studio 中从实时 Firebase 中检索特定用户 - How to retrieve specific user from realtime Firebase in Android Studio 从 Firebase 实时数据库中检索特定数据的最快方法? - Quickest way to retrieve specific data from Firebase realtime database? 如何从 Firebase 实时数据库中检索特定数据? - How to retrieve Specific Data from Firebase Realtime Database? 如何仅为特定用户检索firebase数据库? - How to retrieve firebase database for specific user only?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM