Reputation: 437
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"
Upvotes: 0
Views: 778
Reputation: 2195
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) {
}
});
Upvotes: 2
Reputation: 138824
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.
Upvotes: 2