One of the services that I use to makeĀ app making easier isĀ Firebaseš„Ā . ItāsĀ backed by Google, and in a nutshell it lets you writeĀ software without having to deal with a lot of the complexities that would normally come with it. It handles your database, authentication, analytics, and a ton of other stuff that look like theyād be a pain to write. To give you an idea, last summer I spent a week tryingĀ to figure out how to use a local SQL database on Android. With Firebase, I set up a realtimeĀ database in the cloud, with local redundancy so the app would work without internet,Ā within just a few hours.
That being said, sometimes thereās a tradeoff for all of this simplicity. The offline redundancy of the database only takes one line of code to set up,Ā but erasing the cache is nearly impossible, and one of the most powerfulĀ features, the realtime part of the database, is not as simple asĀ it seems. For the past few months Iāve beenĀ trying off and on to fix the same stubborn bug. Iād press a button in my app to add to a listĀ of data,Ā which wouldĀ run methods to push it to Firebase (and theoretically detect a change in data and update the local list), then IādĀ run methods to update parts of the UI to reflect the new data.
// sets the positive button .setPositiveButton(dataPointMethods.getAddDataButtonText(), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // logs the data dataPointMethods.logData(); DistanceManager.calculateActiveDistances(); ((MainActivity)getActivity()).updateCompassDisplay(); closeDialog(); } })
// logs data to Firebase public void logData(){ // Creates new Water object int numberOfGlasses = 1; Water water = new Water(numberOfGlasses); DBManager.dbRef.child(DB_DATA_ROOT).push().setValue(water); }
All the data was stored properly, but the UI wouldnāt update how it was supposed toĀ unless I added some data again. Turns out, I was overestimatingĀ the ārealtimeā part.Ā Firebase has this really cool way to retrieve data using something called aĀ ValueEventListener.Ā It pulls what you want from the database, and then runs your code to put it wherever you decide. Whatās cool about it is that it will do thisĀ every single timeĀ the data changes! So keeping this in mind, I figured Iād avoid doubling my code by just counting on myĀ ValueEventListener to update my lists locally.
My ValueEventListener:
dbRef.child(WATER).addValueEventListener(new ValueEventListener(){ // some code that updates my local lists. }
What these three snippets wereĀ actuallyĀ doing:
Firebase saves you a lot of timeĀ by handling threading for you,Ā and it handles it so well that you kind of forget itās a thing you need to consider! Itās definitely worth using, especially since it lets you spend more time making theĀ interesting parts of your project, but it has its quirks sometimes.
Alright, lets get back to coding! š