How to retrieve firebase database for specific user only?

拟墨画扇 提交于 2020-01-06 05:22:17

问题


I am using Firebase Database for my android application. Login feature is available. There is a bookmark/favourite option in the app. After pressing the bookmark button the data are saving with the user id separately. Exactly what I want. But the problem is when I am trying to retrieve the saved data in recycleview they are showing all user's data instead of the user logged in. Please help me. I am using cardview in recycleview.

 mUserDatabase = FirebaseDatabase.getInstance().getReference("Bookmarks");
        mUserDatabase.keepSynced(true);

It is my Database for Idiom Phrase

And it is the data added by user by pressing bookmark button


回答1:


You need to access the user uid, so only that user's data will be shown:

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

//String.valueOf(int)
mUserDatabase = FirebaseDatabase.getInstance().getReference("Bookmarks").child(String.valueOf(10)).child(userId);

getUid() will retrieve the id of the current logged in user.




回答2:


To retrieve specific users data you need to provide that user's id, try this code it might help you

mUserDatabase = FirebaseDatabase.getInstance().getReference("Bookmarks").child("10");

Query query = mUserDatabase.child(userid);
query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //your code
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });



回答3:


This is not a good way of storing the favorites for each user. Instead, change your database structure to:

BookMarks   
    |UserUID
        |10
        |3
    |UserUID2
        |6
        |10

This structure will help you to view all the favorites of one user at a particular time. Your current structure will limit you to viewing one favorited item for one user or all users who have favorited that item



来源:https://stackoverflow.com/questions/51454417/how-to-retrieve-firebase-database-for-specific-user-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!