How to get data from Real-Time Database in Firebase - android

I've used the Real-Time Database with this setup:
->users
->uid
->name
->email
->other info
If I wanted to save the user data I would use my User class and then set the object in the database like this:
//assume variables have already been declared...
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
User user = new User(name, email, other values...);
mDBRef.child("users").child(mFirebaseUser.getUid()).setValue(user);
I tried it and it works fine.
But how can I retrieve these values from the database? For instance, once I set a User object as shown above, I may want to retrieve the user's email. I don't mean getting the email through the sign-in provider. I want the email through the real-time database. I've tried working this out for a while now but the documentation isn't helping much. All it shows is to setup listeners in order to wait for changes to the data. But I'm not waiting for changes, I don't want a listener. I want to directly get the values in the database by using the keys in the JSON tree. Is this possible via the real-time database? If so, how can it be done because either the documentation doesn't explain it or I'm just not understanding it. If not possible, am I supposed to be using the Storage database or something else? Thanks.

Firebase uses listeners to get data. That is just the nature of how it works. Although, you can use a single event listener (the equivalent of just grabbing the data once). It will fire immediately and get the data, and will not fire ever again. Here's a code example to get the current user's email:
//Get User ID
final String userId = getUid();
//Single event listener
mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
User user = dataSnapshot.getValue(User.class);
//user.email now has your email value
}
});

Related

how do i change data by custom key in firebase?

I am having an app which writes in firebase and I want my another app with admin privileges to read and edit the data present in the custom key
If this is the picture assume where a random key a my key and I want to edit the data or add new data with the present data in that particular custom key.
Any help will be appreciated
Not 100% sure what you're asking, but if you want to get all the children, do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("yourTable");
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// All your data is in dataSnapshot
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
);
If you want to set a specific child's value by the key do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("yourTable");
ref.child("mySpecificChildId").child("message").setValue("new value");
If these don't help, please add a more specific question!
If these keys are auto generated and you cannot get a hold of them, it does not matter what privligies you have you cannot get them.
However, if you do have the key, or getting it from a function, and you want to change the values at the specific node or just read them you can just query the database for that key and change it after wards something like this:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mRef = database.getReference().child("YOUR KEY");
and then you can access read and edit the values at the node
mRef.child("message") //Do Whatever you want
PS: just make sure you are checking if the dataSnapshot Exits!
EDIT:
if your first app is the one generating the keys, you can store them in a different node and access that node based on position to get the key and after you make sure you accessed that node just query for the key

Creating a new user and also add new data to the firebase database at every SignUp

I am new to Android programming. I am working on an app. When I signup in my app this shows the previously added data and does not ask me to add new user data to the database.
Even if I again login with a registered user then it again shows the previously added data.
I want that when I create a new user then a new node should create and then its child with data.
Database Picture
First of all, you need unique id to share your data in firebase. You can use user id for that. If you use firebase authentication. you can get user id from
FirebaseAuth.getInstance().getCurrentUser().getUid();
You can use this with email password firebase authentication. Likewise, you can get a unique id for authentication. Then u need to use that id as a key of your firebase database. Then your data structure should be changed like below. (key would be userids)
childsQuerity
|-------------adminInfo
|-------key1 -> value1
|-------asas1234 -> value2
|-------------childInfo
|-------key1 -> value1
|-------key2 -> value2
in your android activity use below command to push data to db
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("childInfo").child(userid);
ref.setValue(userDataUWant);
When creating a new user, get userid and update that firebase data like above-mentioned method. Then if an already registered user logged to the system. u can get user id using above mentioned method and you can get that user details as well.

Connect users and Firebase Database

So I am keeping track of a users taps on the screen and I have the user sign up with their email. However, when it comes to using the Firebase Database I am lost. I am not sure, how to save integers and then it load up when the user logs in. Can someone point me in the right direction?
I have watched a ton of videos and none show how to store information with an integer.
You don't need to do anything special for storing a integer or any other value in the Firebase DB.
You can use the uid of the current user and store the pojo/model directly into the the firebase DB.
For example, this can be your java model class:
public class Model {
private int tapCount=0;
public int getTapCount() {
return tapCount;
}
public void setTapCount(int tapCount) {
this.tapCount = tapCount;
}
}
When you want to insert the tap count into the Firebase db. You need to take the previous tap counts and add it with the current count update/create the Model object and set it into the Firebase db in the uid.
FirebaseDatabase.getInstance().getReference()
.child("user")
.child(FirebaseAuth.getInstance()
.getCurrentUser()
.getUid())
.setValue(model);
This code will insert the model under the user key and under user unique id.
Thanks,
Hope it helps.

How to store data each time a user presses a button in Firebase (Android)

I am an experienced MySQL user but I am a newbie to json and firebase. I am trying to make an activity where a user is able to enter data and I save it to my db in firebase. I achieved my goal but here is the problem. When I save it(I think) I need to specify a child element with a string. Since this child element is static,every time a user enters a question it overwrites the existing one in my database. How can I fix this and how can I get the data back? Here is that part of my code.
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
firebaseAuth=FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser()==null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
FirebaseUser user=firebaseAuth.getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference();
Info info=new Info(question,answer,a,b,c,d);
databaseReference.child("secondQuestion").setValue(info);
//info is a new object which takes 6 string as an input.
// As you can see, I declare a string inside .child and it overwrites the data stored in it
As Andrew commented, it is indeed normal to add items to a (semi-chronological) list using push.
They're logically similar to a auto-increment field in MySQL, but have a (very) different format. See this post about why Firebase doesn't use the +1 style increments and this post on the push IDs.
If your questions already have a property that uniquely identifies them, you should probably use that as the key. So say that you're storing a list of Firebase Authentication users, you'd store each user under their uid. Or if the question text must be unique, you should probably store each question under (a hashed derivative of) their text.

Firebase Android, get only one key value pair

I am using Firebase Database in Android. In my app there are three type of users. one of them is "Driver" as shown in json tree below, I want that when user sign in, it automatically gets the value from key value pair "Role" so that I can start the respective activity. is there any easy way to do it or any way to do it?
Assuming you have checked that user is logged in (by Firebase Authentication) and random key child of Driver Information is user uid, then it should be like this:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase.getInstance().getReference("Driver Information/" + user.getUid() + "/Role")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String role = dataSnapshot.getValue(String.class);
// do someting with role
}
...
});
Note: replace addValueEventListener with addListenerForSingleValueEvent if you want to get the data one time only and don't mind if that data get changed.

Categories

Resources