How to fetch data on Firebase from time to time? - java

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

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 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 insert and retrieve Android code on this Firebase structure?

I am from PHP and MySQL background and I haven't worked with JSON based DB like Firebase.
I am looking for sample code to insert data in firebase "Realtime database". I am already done with authentication stage.
To insert some data in your Firebase Database, you have to set the reference to the node you want to insert the data to and then use setValue() method.
Suppose you want to change age of the admins node, in your database in the question.
In code it looks something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child("admins");
ref.child("age").setValue(76);
The above code will replace 42 with 76, in your admins node's age child.
Read more about this here.
Getting data from Firebase Database is a bit more work, as you have to use listeners for that. There are 3 different event listeners at your disposal, that are valueEventListener childEventListener and singleValueEventListener.
These three eventListeners have different properties and you can use them as you like.
Suppose you want to retrieve age of your admins node from your database, then you may use a code like this to help. Note ref in this code is same as in above code.
ref.addSingleValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int age = dataSnapshot.child("age").getValue(String.class);
// this will store value of age from database to the variable age
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.d("TAG:", "Couldn't read data ", error.toException());
}
});
Read more about this here.
Refer to this link, https://firebase.google.com/docs/database/android/start/
Write a message to the database
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Hello, World!");
Read a message from the database
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});

Implementing a Firebase server-side countdown timer for Android?

Is there a way to implement a Firebase server-side countdown timer in Android Studio?
I want the timer to be server side, meaning that whenever a user opens my app the counter will always be at the same time for all users.
I read the answers to this question, but they're 2+ years old and Firebase changed a lot since. It was acquired by Google in October 2014 and a significant number of new features were featured in May 2016 at Google I/O.
If Firebase can't provide that feature, is there another platform that can provide server-side countdown?
Create a server side timer that updates a value in your realtime database.
Firebase ref = new Firebase('/firebase/database/url/time');
new AnimationTimer(){
start(){...}
stop(){...}
handle(){...ref.addValue(time);}
};
That will update your real-time database every millisecond. To see it in your application just call it.
Firebase ref = new Firebase('/firebase/database/url/time/value')
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot ds) {
Platform.runLater(() -> {
label.setText(ds.getValue() + "");
});
}
#Override
public void onCancelled(FirebaseError fe) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
It will update in real-time on your application in milliseconds. I was able to get this running in Java
I dont have better idea for countdown only calculate on clientside.
What happen if you do it:
Get Server Time in timestamp (add to srvTime variable)
Create new record for "countdown" timer:
Start time: srvTime
End time: Time in ms when countdown ended for example (5min = 60000*5)
And you can calculate in client side.
Or create a listener, for ServerValue.TIMESTAMP
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
}
public void onCancelled(DatabaseError databaseError) { }
});
ref.setValue(ServerValue.TIMESTAMP);

Categories

Resources