Implementing a Firebase server-side countdown timer for Android? - java

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);

Related

Accessing real-time firebase database in Android Studio

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

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.

Firebase Realtime Database Listener in Java Application doesn't work(Not Android) [duplicate]

I'm trying to update parts of a WebView in my Android app with data I'm getting from a peer connected via Firebase. For that, it could be helpful to execute blocking operations that will return the needed data. For example, an implementation of the Chat example that will wait until another chat participant writes something before the push.setValue() to return.
Is such a behavior possible with Firebase?
import com.google.android.gms.tasks.Tasks;
Tasks.await(taskFromFirebase);
On a regular JVM, you'd do this with regular Java synchronization primitives.
For example:
// create a java.util.concurrent.Semaphore with 0 initial permits
final Semaphore semaphore = new Semaphore(0);
// attach a value listener to a Firebase reference
ref.addValueEventListener(new ValueEventListener() {
// onDataChange will execute when the current value loaded and whenever it changes
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// TODO: do whatever you need to do with the dataSnapshot
// tell the caller that we're done
semaphore.release();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
// wait until the onDataChange callback has released the semaphore
semaphore.acquire();
// send our response message
ref.push().setValue("Oh really? Here is what I think of that");
But this won't work on Android. And that's a Good Thing, because it is a bad idea to use this type of blocking approach in anything that affects the user interface. The only reason I had this code lying around is because I needed in a unit test.
In real user-facing code, you should go for an event driven approach. So instead of "wait for the data to come and and then send my message", I would "when the data comes in, send my message":
// attach a value listener to a Firebase reference
ref.addValueEventListener(new ValueEventListener() {
// onDataChange will execute when the current value loaded and whenever it changes
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// TODO: do whatever you need to do with the dataSnapshot
// send our response message
ref.push().setValue("Oh really? Here is what I think of that!");
}
#Override
public void onCancelled(FirebaseError firebaseError) {
throw firebaseError.toException();
}
});
The net result is exactly the same, but this code doesn't required synchronization and doesn't block on Android.
I came up with another way of fetching data synchronously.
Prerequisite is to be not on the UI Thread.
final TaskCompletionSource<List<Objects>> tcs = new TaskCompletionSource<>();
firebaseDatabase.getReference().child("objects").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Mapper<DataSnapshot, List<Object>> mapper = new SnapshotToObjects();
tcs.setResult(mapper.map(dataSnapshot));
}
#Override
public void onCancelled(DatabaseError databaseError) {
tcs.setException(databaseError.toException());
}
});
Task<List<Object>> t = tcs.getTask();
try {
Tasks.await(t);
} catch (ExecutionException | InterruptedException e) {
t = Tasks.forException(e);
}
if(t.isSuccessful()) {
List<Object> result = t.getResult();
}
I tested my solution and it is working fine, but please prove me wrong!
Here's a longer example based on Alex's compact answer:
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
final FirebaseFirestore firestore = FirebaseFirestore.getInstance();
final CollectionReference chatMessageReference = firestore.collection("chatmessages");
final Query johnMessagesQuery = chatMessageReference.whereEqualTo("name", "john");
final QuerySnapshot querySnapshot = Tasks.await(johnMessagesQuery.get());
final List<DocumentSnapshot> johnMessagesDocs = querySnapshot.getDocuments();
final ChatMessage firstChatMessage = johnMessagesDocs.get(0).toObject(ChatMessage.class);
Note that this is not good practice as it blocks the UI thread, one should use a callback instead in general. But in this particular case this helps.
If anyone is also thinking about how to use Kotlin's coroutine you can use kotlinx-coroutines-play-services.
Add to your app build.gradle file:
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.1.1"
Then simply:
suspend fun signIn(email: String, password: String) {
try {
val auth: FirebaseAuth = FirebaseAuth.getInstance()
auth.signInWithEmailAndPassword(email, password).await()
} catch (e: FirebaseAuthException) {
println("${e.errorCode}: ${e.message}")
}
}
I made a simple class to call tasks synchronously in Android.
Note that this is similar to Javascript's async await function.
Check my gist.
Here's a sample code to use it.
TasksManager.call(() -> {
Tasks.await(AuthManager.signInAnonymously());
// You can use multiple Tasks.await method here.
// Tasks.await(getUserTask());
// Tasks.await(getProfileTask());
// Tasks.await(moreAwesomeTask());
// ...
startMainActivity();
return null;
}).addOnFailureListener(e -> {
Log.w(TAG, "signInAnonymously:ERROR", e);
});

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

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