How to list the registered users names in Android (Firebase)?

这一生的挚爱 提交于 2019-12-31 05:36:39

问题


I am new to android and just learned to create a users profile like facebook or instagram, currently I have registered four users with email/password and in database am storing there email, name, phone. In another activity am trying to fetch only the names of the registered users like "People you may know" in facebook, but it is displaying nothing.

private void showData(DataSnapshot dataSnapshot) {

    for (DataSnapshot ds: dataSnapshot.getChildren()) {

        UserInformation userInformation = new UserInformation();

        userInformation.setName(ds.child("users").child("name").getValue(UserInformation.class).getName());

        ArrayList<String> array = new ArrayList<>();

        array.add(userInformation.getName());

        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);

        mListView.setAdapter(adapter);

    }

is this correct way of fetching it because am getting NullPointerException, UserInformation is model class containing getters and setters.

fire-18b42
           users
                KWE45gijkfJDK6782IBkjas(UID)
                    email: "@example.com"
                    name: "Example"
                    phone_num: 10000000

This is how I have stored the data to database once the user is registered, now like this I have four users and I want to extract every ones name in seperate listView.


回答1:


To display those names, please use this code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersdRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            Log.d("TAG", name);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersdRef.addListenerForSingleValueEvent(eventListener);

And the output will be in this case all your user names.




回答2:


Firebase is NoSql. You need to retrieve all users from myRef.child("users") and apply iterator to get names of all users.



来源:https://stackoverflow.com/questions/45082030/how-to-list-the-registered-users-names-in-android-firebase

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