How to use Firebase RealtimeDatabase like a common Database? - android

The Firebase RealtimeDatabase works with Listeners, when a event happen so the function is triggered, but I wants a option to update the data when a Button is clicked, for example. I learned about this and found the method DatabaseReference.addListenerForSingleValueEvent, but keeping be a listener. So, exists a way to solve my problem? I'm working with Android.

when a Button is clicked you can use method DatabaseReference.addValueEventListener() to get data from firebase.
And whenever you need cancel this listener: call DatabaseReference.removeEventListener(valueEvenListener);
Sorry my bad English :( :( :(

The main goal of Firebase databases is to work as Real-time databases and not to work as offline databases. Firebase applications work even if your app temporarily loses its network connection. Cached data is available while offline and Firebase resends any writes when network connectivity is restored.
When you enable disk persistence, your app writes the data locally to the device so your app can maintain state while offline. You can enable disk persistence like this:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
If you want to be compltely offilne you can use goOffline() method
This method shuts down our connection to the Firebase Database backend until goOnline() is called.
However, i don't recomand you using Firebase as an offline-only database. It is really designed as an online database that came work for short to intermediate periods of being disconnected. While offline it will keep queue of write operations. As this queue grows, local operations and app startup will slow down. Nothing major, but over time these may add up.
Hope it helps.

Related

How to know which offline data has been synced to firebase Realtime Database

I'm writing a chat application with the help of firebase.Here I have a problem , if the device is offline the data is stored in cache and when device is back online the cache will be synced , but how to know which data is synced and which not (User may have poor internet connection , so syncing may be delayed).How to notify user that message has been sent or sending , and that too we need to manage a huge list of messages
Thank you!
There are two ways:
Using a completion listener as shown here: Firebase Android - how to tell if node has been synced This approach works as long as the app stays active. Completion listener don't survive an app restart, so it won't work if the app is restarted.
Using a sentinel value. Writes to the database from a single client are guaranteed to be executed in order. Using this knowledge, you could write a sentinel (think: dummy) value when the app is restarted, or the connection is restored, and detect when that one is written. Once the sentinel value is confirmed, you can be certain that all older messages have also been handled by the server.
Also see:
Firebase synchronisation of locally-modified data: handling errors & global status

Maintaining connection to Firebase realtime database after app is closed if there is data that is still queued to be stored?

I'm using Firebase's realtime database on Android and the way I understand how it works is that even if the app disconnects from the network, Firebase will simply queue the transactions that the user has initiated and then perform then when connectivity is resumed. This works really well but if the app is closed then this queue seems to be discarded.
The Firebase docs on handling offline capabilities states the following:
Transactions are not persisted across app restarts
Even with persistence enabled, transactions are not persisted across
app restarts. So you cannot rely on transactions done offline being
committed to your Firebase Realtime Database. To provide the best user
experience, your app should show that a transaction has not been saved
into your Firebase Realtime Database yet, or make sure your app
remembers them manually and executes them again after an app restart.
But as far as I know, there is no way of knowing whether or not data has finished being written to the database.
How exactly would you go about making the app manually remembering what still needs to be written to the database? Is there some way of accessing the queue of transactions that is yet to be carried out? Or is there some way of keeping the app running in the background after being closed that could just sync the data when connectivity resumes?
Thanks in advance.
But as far as I know, there is no way of knowing whether or not data has finished being written to the database.
There actually is. The Transaction.Handler interface has a [onComplete method](https://firebase.google.com/docs/reference/android/com/google/firebase/database/Transaction.Handler.html#onComplete(com.google.firebase.database.DatabaseError, boolean, com.google.firebase.database.DataSnapshot)). The boolean that is passed to that argument is a flag to indicate if the transaction was committed:
committed
True if the transaction successfully completed, false if it was aborted or an error occurred
For more information, see the Firebase documentation on transactions.
I think I had the problem you are facing, in my case was a simple confusion. That Firebase warning is not about "transactions" in general, is about the "transaction" method provided by them.
In Android this is reference().runTransaction().
The "transaction" method is used to validate data first, by example, if more than one user can subscribe to an event simultaneously, you can make sure that the last vacant was available.
Since the "transaction" method query the database gives you the data, and the upload data, if there is no network connectivity there is no way to make sure that will work on app restart because there was never a first query to see the data you have to validate.
This seems logical to me, a "transaction" method will create a sort of bridge between the client and the database, this is not random, but because is part of the business logic, then you should warn the user visually that their changes might not be saved since it is offline, or even if it is sensitive not allow the user to do it.
In other cases, the data is indeed stored locally and then uploaded when the app is restarted. So if you do something like
reference.child(key).setValue(myObject);
Thant change will be local until the next time user has an internet connection.
You have to make sure to add the keepSynced to the references you actually need. Setting the syncing to the root, won't solve the problem as a waterfall, make sure to be specific with nodes you need to keep synced, this way the user will see the changed reflected visually in the app.
//Won't work
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
root.keepSynced(true);
//This will work
root.child("event_list").keepSynced(true);
root.child("user_events").child(uid)keepSynced(true);

Firebase database backgroundservice error [duplicate]

I'm considering the use of keepSynced() for some data from Firebase Realtime Database. I understand that it will automatically sync those paths. But how does that relate to Android lifecycle? If the user leaves all activities (and all normal listeners disconnect), will it stop syncing? I don't want the app to become data or battery hog.
On the other hand, I would like to update cached data when FCM notification arrives. I can launch some service which will connect to Firebase. I would like to sync all paths which are in keepSynced() and stop it when it's synced. I'm not sure how to achieve that. Create a listener to one of the paths and keep the service running for some time? After the service is finished, will it stop syncing?
firebaser here
Great question!
When there is no active activity, the operating system may close the connection to the Firebase database at any time. Our SDKs don't try to prevent that, but will reconnect when the app becomes active again.
What you're describing in your second paragraph is what we call "push to sync", where you send a push notification (typically a silent FCM data message) to trigger synchronizing of the data.
We did something like that in last year's I/O app and, while it was a bit more complex than we wanted it to be, it worked great. We explicitly managed the connection in that case, calling goOnline() and goOffline() (after 5 minutes iirc). The main sync code can be found in the IOSched github repo.

Does Firebase Realtime Database delays in sending values to listeners

I am using Firebase realtime database in my android app. And I have observed that if more than one phone is connected with database using value event listener, then the last connected phone receives data very late. Is it that firebase sends data to one by one client? then it will definitely cause delay.So how to cope with this?
No firebase database is realtime and all changes are reflected immediately all devices connected to a database gets data simultaneously. Check your network connectivity of device
I got it. Actually I got answer on Slack Firebase community from a helpful user, and my doubts are clear now. He explained that this behavior is normal and delays maybe be scaled or constant. And He also said that data will be guaranteed to be received by all listeners though the node is updated during delay period. And data is not lost but delay is certain.
I hope this may help somebody who faced same issue like me.

Firebase offline capabilities as cache

I am wondering whether it is a sound strategy to use the firebase offline capabilities as a "free" cache.
Let's assume that I am in activity A, I fetch some data from firebase, and then I move to activity B, which needs the same data. If the app is configured with setPersistenceEnabled(true) and, if necessary, also with keepSynced(true), can I just re-query the same data in activity B, rather that passing it around?
I understand that there is a difference between the two approaches regarding reading-from-memory and reading-from-disk (firebase offline cache). But do I really get rid of all the network overhead by using firebase offline?
Relevant links:
Firebase Offline Capabilities and addListenerForSingleValueEvent
https://groups.google.com/forum/#!msg/firebase-talk/ptTtEyBDKls/XbNKD_K8CQAJ
Yes, you can easily re-query your Firebase Database in each activity instead of passing data around. If you enable disk persistence, this will be a local read operation. But since you attach a listener (or keep it attached through keepSynced()), it will cause network traffic.
But don't use Firebase as an offline-only database. It is really designed as an online database that can work for short to intermediate periods of being disconnected. While offline it will keep queue of write operations. As this queue grows, local operations and app startup will slow down. Nothing major, but over time these may add up.

Categories

Resources