Android - Two types of users in Firebase

大城市里の小女人 提交于 2019-12-31 07:06:21

问题


I am developing a simple android application with Firebase. I want to save the users in the real time database without using authentication with email and password. I simply want their name and their role (eg. teacher and student) picked by radiobuttons. Later I want to display all users in a list, but I was wondering how the database should be set up and how to display the right activity based on their role

Should it be:

User
 "something"
   username: "name"
   role: "Teacher"

or

User
  "KA2aslkdajsdlsad"
    username: "name"
    role: "teacher"

回答1:


Definitely you need to use the second option. You need to use a unique identifier for all those users. For achieving a new unique key (based on time), i recomand you using push() method. It's also generated entirely on the client without consultation with the server.

On the other hand i recomand you using Firebase Anonymous Authentication.

Hope it helps.




回答2:


First, make a POJO java object as per your user infos.

public class User{
        String username;
        int roleId; // 1 for student, 2 for teacher
        public User(String username, int roleId){
            this.username = username;
            this.roleId = roleId;
        }
    }

Now Store your User inside your realtime database like:

FirebaseDatabase.getInstance()
            .getReference()
            .child("users")
            .push()
            .setValue(new User("John", 1));

If you need to fetch all your users, you can do in this way:

final List<User> userList = new ArrayList<>();
FirebaseDatabase.getInstance()
            .getReference()
            .child("users")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                        User user = snapshot.getValue(User.class); // this is your user
                        userList.add(user); // add to list
                    }
                    // Now may be display all user in listview
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });


来源:https://stackoverflow.com/questions/46444028/android-two-types-of-users-in-firebase

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