Accessing real-time firebase database in Android Studio - java

I am currently working on a project where we have to access the real-time firebase database data in Android Studio. The data stored in the real-time denter image description hereatabase is in this Format.
How do we access this data in Android Studio Continuously?

For Continuously observe data firebase is refer to use addValueEventListener()
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
// ..
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
mPostReference.addValueEventListener(postListener);
Documentation Reference also There are many video tutorial available on youtube

Related

Firebase for android studio reading not working

FirebaseDatabase fb = FirebaseDatabase.getInstance();
DatabaseReference IDrefs = fb.getReference("ID_Numbers");
IDrefs.addListenerForSingleValueEvent(new ValueEventListener(){
String name;
#Override
public void onDataChange(#NotNull DataSnapshot shot){
Toast toasty = Toast.makeText(getApplicationContext(),"name",Toast.LENGTH_LONG);
toasty.show();
for(DataSnapshot ds : shot.getChildren()) {
name = ds.child("First_Name").getValue(String.class);
}
TextView txtName = findViewById(R.id.lblName);
txtName.setText(name);
}
#Override
public void onCancelled(#NotNull DatabaseError err){
throw err.toException();
}
});
Hi so I am new to firebase in general. I am trying to read data from the real time database when the application loads in. This code works sometimes. For some reason the ValueEventListener does not run and the results come out as blank. What I want it to do is extract the First_Name fields value from my database to display it in my application. There are no errors provided it just doesn't seem to work.
Image of my firebase database
EDIT:
So its working now turns out I was using the wrong event listener
I was using addListenerForSingleValueEvent not addValueEventListener. The former calls the values from the devices local cache instead of going straight to the database (At least that is what I can understand from the documentation) while the latter goes straight to firebase to get the data. It works now consistently. With no issues from what I can see.

How to show each users' data based on their Google account - Firebase

I'm currently building a to-do app on Android Studio. I'm facing an issue with my Firebase database. What I'm trying to do is, each user to have a unique id based on their google sign in, in order to see only their own data. Currently, on my app, everyone can see anyone's' tasks. On Firebase I'm using the Realtime Database, specifying it by one child of "Users" and another one of Task + a random number. Also, I've already added the google sign in button on the launch of my app.
Current Database:
enter image description here
Example of how my hierarchy wants to be:
enter image description here
According to your comments, to get only the Task objects the correspond to a particular user, please use the following lines of code:
String userId = "User-13294";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tasksRef = rootRef.child("Users").child(userId).child("Tasks");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot taskSnapshot : dataSnapshot.getChildren()) {
String title = taskSnapshot.child("title").getValue(String.class);
Log.d("TAG", title);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
tasksRef.addListenerForSingleValueEvent(valueEventListener);
Because User-13294 has only one Task, the result in the logcat will be only one title:
Swimming

How can I get data from firebase in android and set it to my model?

I was creating an app and connect it to firebase and I have successfully uploaded the data by firebase documentation, and now I can't get it, I couldn't find any documentation about it.
Can you please show me the code of how to get my data AND set it to my model like for example:
Model.setTitle(firebase.collection.get("Title"));
Get your database and then use a ValueEventListener :)
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
HERE GET THE VARIABLE AND SET TO YOUR TITLE :)
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
mPostReference.addValueEventListener(postListener);
In some cases you may want a callback to be called once and then immediately removed, such as when initializing a UI element that you don't expect to change. You can use the addListenerForSingleValueEvent() method to simplify this scenario: it triggers once and then does not trigger again.
https://firebase.google.com/docs/database/android/read-and-write

Firebase authentication - Display user info

I use the firebase realtime database to store user information.
Here is a picture of the database:
screenshot of the database
For example, how can I get the value "nombre_dons" according to the connected user to display it in the application ? I use android studio in java.
Thank you in advance for your help
Those parent strings of the user data in Users node in your database look like the uids. If they indeed are, then all you need to do is to retrieve data from those uids for the particular user.
What I am saying looks something like this in code:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
ref.child(mAuth.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String data = dataSnapshot.child("nombre_dons").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled", databaseError.toException());
}
});
One flaw I can see in your database image is that nombre_dons child in second user in your Users node has capital N, which would be a problem, because Firebase is case sensitive. I'd advise you to keep it same as others.
Assuming the keys inside 'Users' in your database are Firebase Authentication UserId(s), you can follow these steps-
1. Get UID of the current user.
2. Fetch data for the same.
Using Javascript -
var uid = firebase.auth().currentUser.uid;
firebase.database().ref('/Users/' + uid).once('value').then(function(snapshot){
var nombre_dons = snapshot.val().nombre_dons;
});

How to fetch data on Firebase from time to time?

I am fetching data on Firebase from time to time because I am tracking someone's GPS. That someone is saving his location in an interval of 5 minutes so that I can track his GPS. But my problem is how do I fetch data from Firebase with an interval of 5 minutes too?
Or is there any possible way other than this?
Thanks in advance. :)
So if someone is updating his/her location in every five minutes, then you really don't have to run a CounterDownTimer in your side to track the location in every five minutes. So I think you just need to add a listener to that node at Firebase that you want to track.
So here's a simple implementation for you. Copied from Firebase Tutorial
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
// Attach an listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
I'm copying quotes from there too. So that you know it serves your purpose.
This method will be called anytime new data is added to our Firebase
reference, and we don't need to write any extra code to make this
happen.
So each time the person you want to track will update his/her location, you'll get a callback in the method stated above and will take necessary action. You really don't have to implement a polling mechanism to do the tracking. That's the way Firebase works actually.
No Needs to put any kind of service of Scheduler to retrieve data from firebase.
As Firebase provide realtime database .. whenever you push your data on Firebase Database the listener will trigger and you can retrieve your data..
Implement following Listener, using this you can retrieve your data whenever database get update.
DatabaseReference mDatabase =FirebaseDatabase.getInstance().getReference();
ValueEventListener yourModelListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get YOURMODEL object and use the values to update the UI
YourModel mModel = dataSnapshot.getValue(YourModel.class);
Log.e("Data : ",""+mModel);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
mDatabase.addValueEventListener(yourModelListener);
For More Info about Listeners .. https://firebase.google.com/docs/database/android/retrieve-data

Categories

Resources