How does Firebase Database Instances retrieve data in realtime? - android

I just built my first app. It's an Group Messaging App for which I used Firebase Realtime Database. I followed this tutorial to build my app.
The chat is working flawlessly and in realtime ie any changes into the Database are retrieved and reflected within seconds on my app. Actually, being bit curious, I didn't just copy paste all those code lines instead I'm trying to understand meaning behind each statement. So, I'm confused with one of my doubts:
How does this work in realtime (chats pop up immediately)? I was reading about Firebase Database here and they mention ValueEventListener is used to update app data in realtime but what's used here?

From the documentation:
Realtime: Instead of typical HTTP requests, the Firebase Realtime Database uses data synchronization—every time data changes, any connected device receives that update within milliseconds.
Network-wise this is achieved through WebSockets, which is used both on the server and in the client side Firebase library.
Additionally, the "Realtime Database API is designed to only allow operations that can be executed quickly".
Edit: The Firebase client library sets up one WebSocket to communicate with the Realtime Database, which is used for all the communication with the Realtime Database, both reading/subscribing and updating/pushing (unless you use the REST API).
Edit 2: In the tutorial you did you used the FirebaseListAdapter which abstracts away how the data synchronization is done. It's fourth parameter is a reference to a Realtime Firebase Database location that it will sync with (using WebSocktes), and populate the list for you. It takes each entry of the synced data and puts it into new Java objects of the model class you provide as second argument, namely ChatMessage.class.

Related

Android Room and Firebase in a MVVM Architecture - Offline First Application

Can Android Room Database be used as an (offline/local data source) and Firebase Database as the (online data source) in an MVVM repository (gluing the data together) refer to the figure below. Having the same database table and column setup. The application can be used and make changes offline and later sync the modified version on firebase when the internet is available.
Figure 1: MVVM ROOM FIREBASE FIGURE
Figure 2: Data Layer on Repository
Problem: I already have a room database following MVVM architecture but can't figure out how to integrate firebase as my online data source and synch to tables.
Knowing: Android's Room database is a SQL database, while Firebase's Realtime Database is a NoSQL database.
If this is possible, how firebase can be set on as an online data source connected to the repository in a simplified version or an article I can follow? Or is there an alternative wherein, a database is suggested instead?
Can Android Room Database be used as an (offline/local data source) and Firebase Database as the (online data source) in an MVVM repository?
For sure it can be, but I cannot see any reason why you would do that. Why? Because the Realtime Database has its own offline persistence mechanism. This means that your application will continue to work even if the user device temporarily loses its network connection. Besides that, all the cached data is available while the device is offline and Firebase resends any writes when the internet connectivity is restored.
The application can be used and make changes offline and later sync the modified version on firebase when the internet is available.
You're describing exactly how the Realtime Database works if you enable disk persistence using the following line of code.
FirebaseDatabase.instance.setPersistenceEnabled(true);
If this is possible, how firebase can be set on as an online data source connected to the repository in a simplified version or an article I can follow? Or is there an alternative wherein, a database is suggested instead?
I don't see why would you add an extra level of complexity when the Realtime Database already handles that for you. However, if you still want to do that, then you have to check inside the ViewModel class if the device is connected to the internet or not. And according to the connection state, you should request the data either from the Realtime Database or from Room.
Here are some useful links:
How to read data from Room using Kotlin Flow in Jetpack Compose?
How to read data from Firebase Realtime Database using get()?
If you consider at some point in time try using Cloud Firestore, then I also recommend you read the following resource:
How to read data from Cloud Firestore using get()?
Remember, that in Cloud Firestore, for Android and Apple platforms, offline persistence is enabled by default.

How to validate Offline cached data and data coming from API

I am trying to make an app in which I am going to use room database for offline data caching and using NodeJs and MongoDB as a backend service.
What I am going to do is when app first opens it fetches data from server and stores in room database from where it shows in database.
My problem is whenever some new data is updated on server how would I know whether it is available in room database and when to fire server request.
Someone please let me know how can achieve this any help would be appreciated.
THANKS
You are going to need to implement some sort of routine where you can check and validate (update) the data. However, this will depend on the importance of the data and rather if it should be updated and how often.
These are some of the solutions you can look at:
Long/short polling - Client Pull
WebSockets - Server Push
Server-Sent Events - Server Push
I would probably use some sort of real-time communication (web sockets) or use a real-time database to notify the app of changes when something needs to get updated. That said it would also depend on the technology, for instance, Firebase already offers offline caching.
You can achieve this functionality in multiple ways
Configure firebase notification in your app, whenever any server side data update happen just trigger a notification, based on that you can call api and store data in room.
Maintain some version code related to updated server side data in your api, based on that version code you can write logic for storing data in room.

How to send MySQL data To fire-base database?

I'm setting up a home security system using Arduino with some Sensors. I used C language to coding to get sensor data. I already sent that data to MySQL database hosted in 000webhost. now I want to send MySQL data to firebase. (to get real-time data). after I will show firebase data in android app.
so how to do it correctly?
If I get Jason format of Mysql data how to send it to firebase?
Does it need to be linked or just imported? In case of the latter, firebase's realtime database has an import option.
Go to the firebase console
Go to the database settings, initialize the realtime database if necessary
Click the 3 dots on the top right when you're viewing the database and click 'import JSON' and you're good to go
There is no magic process here. Both MySQL and Firebase have API's, so you'll have to write code that read from MySQL and writes to Firebase.
Alternatively you can write straight to Firebase from your C++ code using either the C++ SDK for Firebase, or (more likely) the REST API).

Need to transfer the Firebase data to MySQL and synchronize

I am creating an Android project and in our app, we are going to store the abstract user data and we are creating in Firebase because of its feature of real-time updating. But for doing data analysis we need to store the data in some database, for doing the query operation we have thought of MySQL but on searching regarding my query I have found it can be done but it requires NodeJS support on the server which is not provided by our hosting provider. Is there some other way to handle this problem?

Use Firebase DB with local DB

In my app I have SQLite db. I want to introduce sync between devices of my users. Firebase DB looks like an acceptable solution, but Firebase DB is cloud db at first. So, I can't use it as local db if user will reject auth dialog and let him use app, but without cloud-sync.
Now I think about combining my local SQLite db with cloud Firebase db.
For example, when user adds new row to local SQLite db, my app will also put data into Firebase DB. Other devices of this user will catch this event and update their local db. When the user uses authentification and installs app on new device, I want it to download all rows and put them into local SQLite db. That's my idea: use Firebase DB only for synchronizing data, not for storing it at device. Main reason for it is to let user use my app without authentification&synchonization. The second is that Firebase DB is not designed to be used as local db.
I'm right? Is it okay to use Firebase DB with another local DB?
Related question:
link He want the same as I want:
my plan is to offer the user the option to stay offline
If your firebase structure is not too complex you could also make a interface which defines methods like
void addData(Data data);
Data getData(long id);
void editData(Data data, long id);
void deleteData(long id);
then create 2 classes implementing that interface, one using Firebase the other using SQLite.
DatabaseImplementation
FirebaseImplementation
Inside your Firebase implementation, you would publish the data like normal, and publish one new node to something like root/requestUpdate/userId/push/ and push would contain information on where you request an update, and what deviceId published it.
Then have a ValueEventListener tied to that mentioned node, and if it gets a new child, have it look whether the deviceId is the same or not. If it is not, have the FirebaseImplementation getData using the information you got, and then use the DatabaseImplementation, to addData.
That would make sure that whenever a change is made, any other logged in client will know to update its firebase. If the client is not online, the next time he will be online he will do it as ValueEventListener triggers when it is attached. Make sure to loop through all the requested updates to make sure all are made. Also store the push keys of any updates you did complete on a local database that way you dont end up updating more than once.
Basically the firebase will always be up to date and store any changes a user made on a seperate node which is listened to by all clients.
Obviously this solution still has many problems you would need to fix, like figuring out when to delete the requestUpdate node. Logically after every user has synced but how do you determine this? ...
As for the first login, you would need to write a populateDatabaseFromFirebase() method which will do a whole lot of getDatas and addDatas. How you would do that will depend on how your DB looks. You then would store that the user has already logged in with SharedPreferences and the firebase UID.
That all being said, this will only work if your firebase is pretty flat. If you have a complex database, then everything becomes much more complicated and entangled and then it might be worth looking into an external library.
Some options for HTML5 hybrid apps
This is not what the OP asked about, but hopefully useful to some seekers.
You can use any combination of client and server database to implement storing remotely-maintained data in the device so it will be available when offline.
Some client options :
SQLite
(which is using the "native" browser database, works on iOS Safari
and Android webkit browsers)
IndexdDB
(another "native" option, but not supported in early Android, or
fully supported for iOS - so NOT a good option)
JayData
(which provides an abstraction layer from the underlying native implementation)
Lawnchair
(another popular client abstraction - I found the documentation lacking and have not used this for that reason)
Some server options :
MongoDB
RethinkDB
MySQL (for an SQL DB on the server)
and, of course there are many many more.

Categories

Resources