I'm new to Android development and Firebase. I am making an app in Java.
I've used Firebase Auth for sign-in and sign-up of a user. There are other variables I want to associate with each user (e.g. max squat, it's a fitness app) however, I saw a YT video that said you cannot do this with Firebase Auth. I will need to create a second array/ database to store this user information...if I were to use Firebase DB am I able to easily reference the variables/info stored for my methods?..e.g. If a user's max squat is stored can I easily reference it/assign it to a local variable so I could calculate how many reps they should do? Finally, if the user signs in using Firebase Auth, how do I link this with their info/variables stored in Firebase DB?
Apologies if my use of proper terminologies is lacking, as I said I'm relatively new.
Thanks
Firebase Auth is used only for users to SignIn and SignUp. You should continue using Firebase Auth for that part of your application. There is something called Uid and this is created during registration of a user with Firebase Auth. You can get this with (if user is logged in):
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
Then you can use this uid as an ID for your database item. When creating a new user in Firebase Realtime Database. Let's say you have a Model class named User.class.
public class User {
public String username;
public String email;
public int squats;
...
...
public User() { //Default constructor required for calls to DataSnapshot.getValue(User.class)
public User(String username, String email) {
this.username = username;
this.email = email;
}
And so on, you need getters and setters I guess you know that part. Then you can do this:
User user = new User(username, email);
user.setSquats(10);
...
...
//Add all data you need to add
Then you can set this value to Database under "users" reference which you need to create earlier like this:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
This will create a new child under "users" inside Realtime database with all the values you have inside User.class. If you want to get those values back, just use this:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference databaseUsers = database.child("users");
User myUser = null;
Query usersQuery = databaseUsers.orderByChild("username").equalTo(uid); //you can use any value to order as you want, or you don't have to, there is many options for this query
usersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChanged(#NonNull DataSnapshot snapshot) {
try {
for (DataSnapshot user : snapshot.getChildren()) {
myUser = user.getValue(User.class);
}
} catch (Exception e) {
e.printStackTrace();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Related
I've implemented firebase authentication where users can register with email id and password now in my app i'm providing custom plans to a user i.e when a user selects a plan from a list of plans that select plan should be assigned to the current logged in user and whenever user logs back in only that plan should be visible to him how can i do that?
You can make separate nodes for each of your users. What I mean is when they sign up, you can store them in a node named, common_users and when they select a plan, you can take their name out from the common_users and store them in a new node with name planName_users.
I'm not giving the code for authenticated users being stored in your database under node like common_users here, as you must have implemented that already.
When a user from the app, selects a plan, you may use a code like this to take him out of the list of common_users.
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String curUid = mAuth.getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("common_users");
ref.orderByChild("uid").equalTo(curUid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//remove this user
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Now you can just put him in your new node like planeName_users and then use that to further determine how your user should see things in the app.
One of my routines in my main activity's onCreate() method is to communicate with the Firebase database to do one of three things:
1) If the user is a returning user, update all of their preferences on Firebase stored using SharedPreferences locally.
2) If the user is new and has no data stored on the cloud (they've never downloaded the app), do nothing.
3) If the user is new but has preferences stored under their unique Facebook profile ID, download their preferences and apply them to the SharedPreferences instance.
I must be missing some key, probably basic, piece of insight into how DataSnapshot works, because I can't get my following code to work:
private void initializeFirebase(){
my_db = FirebaseDatabase.getInstance();
DatabaseReference my_ref = my_db.getReference();
Map<String, ?> values = sharedPreferences.getAll();
if (values.isEmpty()){
final String id = Profile.getCurrentProfile().getId();
my_ref = my_ref.child("userid");
my_ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getKey().equals(id)){
data = (Map<String, Object>)dataSnapshot.getValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else {
for (Map.Entry<String, ?> entry : values.entrySet()) {
my_ref.child("userid").child(Profile.getCurrentProfile().
getId()).child(entry.getKey()).setValue(entry);
}
}
}
data is a global Map variable that is always null after getValue() is executed.
My JSON tree is organized as: root -> users -> userid -> each preference as a child node to the userid node. Any help would be appreciated!!
According to the API docs for getValue(), it can return null:
The data contained in this snapshot as native types or null if there is no data at this location.
So, the location you're querying has no data.
I'm going to guess that you didn't want to hard code a value of "userid" in your reference. I bet you mean to use the user's id from the previous line:
final String id = Profile.getCurrentProfile().getId();
my_ref = my_ref.child(id); // id instead of "userid"
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"
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.
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) {
}
});
String userID = user.getUid();
mFirebaseDatabase = FirebaseDatabase.getInstance();
I have userId of the user so when I'm opening my app for the 2nd time(after signing in) I should not show the select user type layout. So I ve to check whether the use is Customer or Staff internally. So the problem is I ve to check the User Id is there . I couldn't find any method to get whether user Id is there or not! There is method called addListenerForSingleValueEvent but that won't help me in my scenario. Pic of the database is given here
I don't know how to continue after this
mFirebaseDatabase.getReference().child("Users").child("Customers")
To check if an user exists in a particular section of your Firebase database, first you need to add a listener and then use exists() method directly on the dataSnapshot object. So, asumming that Users node is a direct child of the Firebase-database root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference customersRef = rootRef.child("Users").child("Customers").child(userID);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//do somethig
} else {
//do something else
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
customersRef.addListenerForSingleValueEvent(eventListener);
I am new to Firebase and I am planning to switch from SQLite to Firebase.
I have 2 tables in SQLite.
First one is NAME OF REPOSITORIES. This will will be general for all users which is accessible to all the users of the application.
Second one is BOOKMARKS. This will be specific to a particular user . I know that there is no table structure in Firebase .
Question is, how can I structure this type of data in Firebase? I have tried understanding tree structure of Firebase, but didn't get help for this type of scenario.
To create two tables you have to create object of DatabaseReference for second table. Also you have to create second node.
public class MainActivity extends AppCompatActivity {
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
//Create an object of DatabaseReference to create second table
private DatabaseReference mFirebaseDatabase1;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'RepositoryName' node
mFirebaseDatabase = mFirebaseInstance.getReference("RepositoryName");
// get reference to 'Bookmarks' node
mFirebaseDatabase1 = mFirebaseInstance.getReference("Bookmarks");
// Save / update the user
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = inputName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String confirmPassword = inputConfirmPassword.getText().toString();
// Check for already existed userId
if (TextUtils.isEmpty(userId)) {
createUser(name, email, password, confirmPassword);
}
}
});
}
/**
* Creating new user node under 'users'
*/
private void createUser(String name, String email, String password, String confirmPassword) {
// TODO
// In real apps this userId should be fetched
// by implementing firebase auth
if (TextUtils.isEmpty(userId)) {
/*userId store the unique key like KYNGnlMMIf3w11VukqD
in this key store usename and email as JSON format in firebase cloud database*/
// "mFirebaseDatabase" is for table1(i.e RepositoryName)
//userId = mFirebaseDatabase.push().getKey();
// "mFirebaseDatabase1" is for table2(i.e Bookmarks)
userId = mFirebaseDatabase1.push().getKey();
}
User user = new User(name, email, password, confirmPassword);
//insert data in firebase database RepositoryName
mFirebaseDatabase.child(userId).setValue(user);
//insert data in firebase database Bookmarks
mFirebaseDatabase1.child(userId).setValue(user);
}
}
Hope this helps you :)
Hello at the first you should try with understanding the basic concept of denormalizing data. You can check one of the blog post.
Again, for more information of stucturing data in detail is here.
You can start structuring data using these links again. You have to have denormalised structure to developer best experience in firebase.
Coming to you point, Two tables.
You need to create 2 nodes in firebase. First one is with NAME OF REPOSITORIES and BOOKMARKS. If you are having any relations for both the table create a new node with that relation lets say USERBOOKMARK and try adding reference to the node.