In this Firebase Tutorial for Android you’ll discover ways to work with Reatime Databases and Authentication via creating a Joke Telling app.
Firebase Tutorial for Android, Nearly all initiatives we work on every day use a REST service. It’s a idea wherein you use a certain set of methods (GET, POST, DELETE…) to ship statistics, acquire information or both.
And REST is first-rate, but once in a while you just can’t find a (lower back)end to all the demanding situations! More frequently than not, the variable names are in a one-of-a-kind fashion than you select or the paths to the requests are puzzling…
Then comes Google, introducing Google Firebase and announcing: “Why would you figure with other people when you may write a backend of your own?” And you begin questioning: “IS THAT POSSIBLE??”, all at once you’re stimulated. You can not hold your thoughts straight, and all you want to do is create backends all day.
Firebase works much like website hosting, so to speak. You pick what services you like, join them on your utility and bam, you’re geared up to take over the arena. Firebase’s backend is simply some other provider. It provides a JSON like database in that you store and examine statistics. It doesn’t really observe the REST popular because it has no REST methods (GET, POST…). Here, you’re running directly with the database.
Firebase Tutorial for Android, You received’t be the usage of all of Firebase in this tutorial. Instead, we’ll recognition on Firebase’s Realtime Database to create a mobile friendly backend. Your goal for this tutorial is to build a funny story-sharing social community utility, the use of the Authentication and Realtime Database services. So allow’s warmth it up. :]
Note: This Firebase tutorial assumes which you’re familiar with the basics of Android improvement and REST offerings. If you’re new to Android, please test out the Beginner Android series and different Android tutorials.
Getting started
Firebase Tutorial for Android, Before doing anything, download the starter and very last projects by means of clicking on the Download Materials button at the top or the lowest of the academic. Once you’ve downloaded the starter challenge, open it up in Android Studio three.1.1 or later so we will do a top level view of the materials to get you caught up.
Most of the code is already pre-baked for you. It’s higher to focus absolutely on Firebase within the educational, instead of the relaxation of the software. Don’t worry, you’ll be guided via the whole lot inside the starter task.
Firebase Tutorial for Android, Tasting the pre-baked goodies\
The challenge setup is straightforward.
- The common bundle contains all of the extensions and global features you’ll use for displaying errors, validating records and coping with the UI occasions like clicks.
- The di bundle incorporates the Dependecy Injection setup. I’ve chosen Dagger because it’s the same old and the majority will sense at domestic using it. If you’re looking for a Kotlin alternative to Dagger, check out Koin. It’s easier than Dagger, but still not at its 1.Zero model milestone.
Note: If you need to study extra about Dagger and how it works, Ray Wenderlich has you covered. Checkout the this tutorial to analyze more about Dagger with Kotlin.
- The ui package deal carries all the Activities and Fragments you’ll use. And the version package deal has model classes for the app facts.
The presentation and firebase applications are those you’ll be working with. The tasks uses an MVP sample for the utility. Splitting the challenge with this package deal structure lets in you to attention on the Firebase implementation in this educational as a substitute of having misplaced within the pre-baked code.
Firebase Tutorial for Android, A hot package
Firebase Tutorial for Android, There are two components of the Firebase implementation you’ll be carrying out, the FirebaseAuthenticationManager and the FirebaseDatabaseManager. Both are in subpackages of the firebase bundle.
The former will deal with all-things-user, like logging a user in or out and registering a new user. The latter will be your man(ager) in the center, and could examine information from the database and save new statistics while it comes in.
Authentication can be finished the usage of an e-mail and a password. Reading the facts on the other hand can be done more than one methods. You’ll concentrate for single records occasions, for character updates and for wellknown updates. Don’t fear if that doesn’t make feel, it’ll be explained in similarly sections. :]
Firebase Tutorial for Android, Rev it up!
Firebase Tutorial for Android, In order to start operating, you want to feature Firebase particular dependencies. However, to be able to upload them you furthermore mght need something referred to as a google-services.Json file. It’s a JSON file which includes all the configuration information Firebase makes use of internally. To get it, you need a Firebase project, allow’s create one!
Visit the Firebase internet site. You must see something much like this:
Firebase Tutorial for Android, Login using a Google account if you haven’t already and if you need, take a brief excursion around the touchdown web page. When equipped, click on the Go to Console button within the higher right. You’ll now create a new Firebase venture. You can do it via clicking at the Add challenge card like below:
Choose your mission call. In this academic you’ll use the call “Why so extreme”, and select your current u . S . A . Like so:
Accept any terms if needed and click Create Project. After completing the first step, you must see a fulfillment message:
Click Continue.
Firebase Tutorial for Android, You ought to see the mission dashboard now. Next you want to add an Android utility to the project, so click on at the Add Firebase to your Android app card:
Firebase Tutorial for Android, Fill inside the bundle name com.Raywenderlich.Android.Whysoserious from the starter assignment and click Register app. The SHA key may be empty for now, you want it best while signing an APK.
Now observe the instructions on the Firebase page to feature the google-services.Json document to the challenge and click on Next.
Add the desired library dependencies on your app module build.Gradle file:
And add the following to the project-level build.gradle:
ext {
//Add the playServices version
playServices = "15.0.0"
}
dependencies {
//Add the following lines
implementation "com.google.firebase:firebase-core:$playServices"
implementation "com.google.firebase:firebase-auth:$playServices"
implementation "com.google.firebase:firebase-database:$playServices"
}
//Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
And add the following to the project-level build.gradle:
buildscript {
dependencies {
//Add this line
classpath 'com.google.gms:google-services:3.3.1'
}
}
Hit Sync Now to sync your Gradle files.
Finally you can Build and Run the project! You should see something like this:
Woohoo! Now you may begin running at the juicy elements of this app.
Firebase Tutorial for Android, Planning our stand-up
Firebase Tutorial for Android, By the stop of this tutorial you’ll have an app which serves different people the pleasant jokes the net has ever examine! To reap this, you first want in an effort to control customers. The first issue on your plate is to finish up the authentication a part of the app.
After the customers make their way to the app, you’ll start patching things collectively with the realtime database. You’ll keep the customers inside the database in order that each consumer can have a listing of his/her favorite jokes. Each funny story can have a title, description (the shaggy dog story itself), the author’s name and identity.
To version these entities, you’ll use the whole thing from the model bundle. You handiest want a few statistics instructions to reap this.
Firebase Tutorial for Android, So the consumer could be able to join up for the software, create jokes and like other jokes. It’s not lots, however it’s enough as a way to discover ways to use Firebase as a mini backend.
Firebase Tutorial for Android, Hiring comedians
What proper is a joke app if there are no comedians – really pun. Good component you aren’t hiring me! You actually need folks that truely have a humorousness. Recruit them and sign them up via Firebase Authentication!
Start by means of having a have a look at the RegisterActivity display and it’s content.
It has some input fields you want to create a completely unique user. Since you’re constructing an authentication carrier the usage of an electronic mail and a password, the consumer needs to offer them even as signing up. Additionally, each person will have a username which you’ll show next to each joke.
Firebase Tutorial for Android, In order in your software to use electronic mail registration, you need to allow the “electronic mail signal-in” method within the Firebase console.
Open up the Firebase Console, click on at the Authentication option on the left under Develop and choose the Sign-in Method tab. Now, pick out the Email/Password company and enable it.
Yay! You can now continue to the implementation. :]
Firebase Tutorial for Android, Preparing the stage
Firebase Tutorial for Android, To connect to Firebase’s authentication carrier, first, visit the di package deal and upload a category known as FirebaseModule.Kt to the module package deal and offer the FirebaseAuth and FirebaseDatabase dependencies inside the module:
@Module
@Singleton
class FirebaseModule {
@Provides
fun firebaseAuth(): FirebaseAuth = FirebaseAuth.getInstance()
@Provides
fun firebaseDatabase(): FirebaseDatabase = FirebaseDatabase.getInstance()
}
Next, add the module to the InteractionModule.kt list of includes, like so:
@Module(includes = [FirebaseModule::class])
@Singleton
abstract class InteractionModule { ...
Now, in case you’re the usage of either FirebaseAuth or FirebaseDatabase, you have got them provided in the Dagger graph.
Next, open up the FirebaseAuthenticationManager.Kt record within the firebase.Authentication bundle and upload a FirebaseAuth property to the constructor like this:
class FirebaseAuthenticationManager @Inject constructor(
private val authentication: FirebaseAuth) : FirebaseAuthenticationInterface
You’ve setup the whole lot to use Firebase-related services, manner to go! Next you’ll connect the real authentication technique, so keep up the good work. :]
Gathering the crowd
At ultimate, head over to the sign up approach in the FirebaseAuthenticationManager. It ought to appearance something like this:
override fun register(email: String, password: String, userName: String, onResult: (Boolean) -> Unit) {
}
The registration method will move like this: as soon as the user’s information is legitimate and they press the Sign up button, you’ll try to create a completely unique person with the provided e mail.
If the e-mail is already in use, Firebase will return an error. If it isn’t, an empty consumer will be created. Since you’re additionally amassing a username, you’ll need to create a UserProfileChangeRequest which edits a user to include a username.
After you finish all that, you continue to want to create a consumer within the database, since the Authentication and Realtime Database are separate offerings, and don’t percentage consumer objects. You’ll do this in a while in the educational.
Add the subsequent to the frame of your check in technique:
//1
authentication.createUserWithEmailAndPassword(email, password).addOnCompleteListener {
//2
if (it.isComplete && it.isSuccessful) {
authentication.currentUser?.updateProfile(UserProfileChangeRequest
.Builder()
.setDisplayName(userName)
.build())
//3
onResult(true)
} else {
onResult(false)
}
}
Taking every commented phase in turn:
- This approach, like maximum Firebase methods, returns a Task. A Task is some thing that you could listen to, for the very last end result.
- Inside the lambda block addOnCompleteListener, you can check whether the result of creating a user was a success and/or finished via using the lower back item’s residences.
- If the undertaking is successful, you’ll upload a username to the new user and contact the onResult callback, announcing the user has been efficaciously created. Any other case will just notify which you didn’t manage to create a consumer.
A session of comedy
Notice the way you’re using the authentication.CurrentUser belongings. It’s vital to recognise how the FirebaseAuth service works internal an Android utility. As soon as you register or log in, the currentUser is available for use. Basically, Firebase caches your login up till the point in which you log out or clear the utility’s data. This is called a Session. Although no longer visible thru code, it’ll be there until you close up it.
After logging in once, there may be no need to worry approximately the rest. If the currentUser doesn’t return null, you then’re logged in. It additionally carries information like the precise consumer identity, e-mail and username. Quite on hand when you want it.
Finish up FirebaseAuthenticationManager.Kt magnificence by means of filling within the rest of the implementation as follows:
override fun login(email: String, password: String, onResult: (Boolean) -> Unit) {
authentication.signInWithEmailAndPassword(email, password).addOnCompleteListener {
onResult(it.isComplete && it.isSuccessful)
}
}
override fun getUserId(): String = authentication.currentUser?.uid ?: ""
override fun getUserName(): String = authentication.currentUser?.displayName ?: ""
override fun logOut(onResult: () -> Unit) {
authentication.signOut()
onResult()
}
The code above is pretty easy. The getUserId and getUserName methods return the facts from the present day person. Furthermore, the logOut method closes the present day Session and the login technique attempts to log the person in.
After adding this, you’re capable of sign off of the app within the Profile tab. Moreover you’re capable of log back in at the login screen.
Breaking the ice
Build and Run the App. Open the register screen through clicking the Sign up button. Fill within the form and hit Sign as much as create a new person. If everything goes well you should see the subsequent display screen:
You managed to register! Quickly open up the Firebase console once more, navigate your way to the Authentication tab to look your new consumer on the Users tab. Right now there may be most effective one user within the software and that is you.
Making punnections
Only having an electronic mail issuer is very limiting in your app. Firebase, however, permits you to easily add a social provider as an authentication answer. It’s approximately as simple as flipping an additional transfer inside the console. In the identical location wherein you enabled e mail signal-in, you may enable numerous different companies like Github, Google, Facebook, Twitter and extra. This permits your customers to connect a couple of accounts to one FirebaseUser.
When a person connects more than one accounts, and logs in with any of them, they enter your application as a unmarried consumer within the Authentication carrier. It’s extremely good handy to your customers whilst your app aid more than one login platforms.
Check out this link to look the legit documentation for this manner.
That concludes the Authentication phase. Once again, good task! You’re ready for the next element – the Realtime Database.
Time to shine
Now which you have a line of comedians all waiting to do their own stand-ups, all you want is their jokes. Head over to the Firebase dashboard once more, this time to the Database alternative beneath Develop. When you open this feature, you should get to choose among the Cloud Firestore and Realtime Database like so:
The difference is inside the manner every shops information and works with information. On one hand the Firestore is like an actual database, it shops documents in files and lets in for efficient queries. On the alternative hand you have the Realtime Database which shops the whole lot as a huge JSON item that you read elements of.
For small programs, the latter is less complicated to apply. It also allows realtime updates (as the call says) that’s on hand when you’re building programs with feeds or chat rooms. This is the reason you may select it for this tutorial. It’s no longer a complex utility and it will benefit a lot from the realtime updates.
Blue pill or red pill?
As noted above, pick the Realtime Database. You must see a popup asking you for the type of security regulations:
Choose either one, it doesn’t actually be counted which, since you’ll trade the settings anyway. Head over to the Rules tab and paste this:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
What those policies mean is that only people who have been authenticated can study or write facts, i.E. Most effective your logged in users. Once you’ve copied and pasted the snippet above, click the Publish button to store the regulations. Once you turn lower back to the Data tab your database will be empty and appear to be this:
Press any key to continue
Right now there’s no records in the database as you’ve best created it. Once you begin pushing the jokes it will be a good deal higher. However, to shop statistics you want to apprehend how records is represented.
I’ve already noted that our database preference stores the whole thing in a JSON object. This method that every piece of statistics has it’s own key. Once you request information at a certain key or “listing” (for example key “person”), you’ll get hold of what’s referred to as a DataSnapshot. A image is the modern-day nation of that directory which holds the whole thing under the important thing “user” in this case. You parse that picture to get the fee, pretty straightforward! You’ll see a way to do this in the next segment whilst you start saving records.
The keys may be custom made or generated with the aid of Firebase. Usually you’d just let Firebase generate the keys so that you don’t need to fear about that. Once Firebase generates a key, and stores the information, the entire directory gets taken care of through a timestamp, beginning from the most modern items first.
Also ordering is constantly ascending while you query gadgets. Sadly, Realtime Database doesn’t assist descending ordering, as an instance for the number of likes. Firestore became built in reaction to this, and supports greater query alternatives and additionally an awful lot greater. However, that is probably any other educational!
Playing the game
You’ve sooner or later reached the part wherein you’ll work with data. You’ll start out via completing the consumer registration system. Remember how I stated you’d should save the person inside the database after registration? Well, open up the FirebaseDatabaseManager beneath the di/firebase/database folder.
Add a personal cost to the constructor named database and of the kind FirebaseDatabase. Your class definition need to appear like this:
class FirebaseDatabaseManager @Inject constructor(private val database: FirebaseDatabase) : FirebaseDatabaseInterface
And the following KEYS at the top above the class:
private const val KEY_USER = "user"
private const val KEY_JOKE = "joke"
private const val KEY_FAVORITE = "favorite"
You can now connect to the database and keep or study statistics.
Update the createUser() to be the following to complete up the person introduction:
override fun createUser(id: String, name: String, email: String) {
val user = User(id, name, email)
database
.reference // 1
.child(KEY_USER) // 2
.child(id) // 3
.setValue(user) // 4
}
You’ll call this approach right after signing up a user. Here’s what each line manner:
Get a reference to the database, which successfully factors to the foundation of the tree/directory.
From the basis directory, open up the “person” listing
Inside the “users” directory, open up the directory which matches the “identity” of this precise consumer
Store a new consumer in that listing by calling the setValue(person) method And that’s how you keep data! If you want to delete a price somewhere, simply call the setValue(null).
So the database is like a large circle of relatives. There are the dad and mom, and every parent may have a group of children.
Build and run the app, logout from the Profile tab in case you need to, and try and register a brand new consumer. You ought to see a new access in the database with the brand new user’s data, right-away and even with out fresh the Firebase web page! Now that’s Realtime! :]
I’ve created a couple of customers myself and right here is the result:
Have a observe the structure of the database. The “user” key has entries, every of that is a unique person. Each user on the other hand has a couple of fields, representing its statistics.
Loading Firebase…
Now which you have a consumer inside the database, why now not study it returned from the database and show it of their profile? To read records, and acquire snapshots, you want to apply Firebase’s Value Listeners. By including a listener to a reference you get the values from the database. You can pay attention to statistics in 3 ways.
First, by calling addListenerForSingleValueEvent, you read the data best as soon as. After you receive it, the listener is eliminated. This is first rate when you want to study something once to use it to your app.
Second, the use of the addValueEventListener method, you listen to a certain directory and all its modifications. Even if the smallest factor changes (like a person’s name) you get the complete snapshot again. This is exquisite for displaying information that isn’t massive however has a tendency to alternate and may gain from a realtime update, like a user’s profile.
Lastly, with the addChildEventListener technique you join adjustments for every baby in a listing. If you change any of them, eliminate them or flow them, you get an occasion for each of the cited instances. More importantly, it’ll emit every of the children one at a time, the primary time you attach the listener. It’s exceptional for such things as chats and feeds where new gadgets are brought often.
You’ll use the addChildEventListener for all jokes, addValueEventListener for favourite jokes and the person profile and the addListenerForSingleValueEvent for changing the funny story’s appreciated reputation.
The peak of the show
There are five strategies to complete up in the FirebaseDatabaseManager before your social network is ready!
Add the following code to study the jokes and the profile.
//1
override fun listenToJokes(onJokeAdded: (Joke) -> Unit) {
database.reference.child(KEY_JOKE)
.orderByKey()
.addChildEventListener(object : ChildEventListener {
override fun onCancelled(p0: DatabaseError?) = Unit
override fun onChildMoved(p0: DataSnapshot?, p1: String?) = Unit
override fun onChildChanged(p0: DataSnapshot?, p1: String?) = Unit
override fun onChildRemoved(p0: DataSnapshot?) = Unit
override fun onChildAdded(snapshot: DataSnapshot?, p1: String?) {
snapshot?.getValue(JokeResponse::class.java)?.run {
if (isValid()) {
onJokeAdded(mapToJoke())
}
}
}
})
}
//2
override fun getFavoriteJokes(userId: String, onResult: (List<Joke>) -> Unit) {
database.reference
.child(KEY_USER)
.child(userId)
.child(KEY_FAVORITE)
.addValueEventListener(object : ValueEventListener {
override fun onCancelled(error: DatabaseError?) = onResult(listOf())
override fun onDataChange(snapshot: DataSnapshot?) {
snapshot?.run {
val jokes = children.mapNotNull { it.getValue(JokeResponse::class.java) }
onResult(jokes.map(JokeResponse::mapToJoke))
}
}
})
}
//3
override fun getProfile(id: String, onResult: (User) -> Unit) {
database.reference
.child(KEY_USER)
.child(id)
.addValueEventListener(object : ValueEventListener {
override fun onCancelled(error: DatabaseError?) = Unit
override fun onDataChange(snapshot: DataSnapshot?) {
val user = snapshot?.getValue(UserResponse::class.java)
val favoriteJokes = snapshot?.child(KEY_FAVORITE)?.children
?.map { it?.getValue(JokeResponse::class.java) }
?.mapNotNull { it?.mapToJoke() }
?: listOf()
user?.run { onResult(User(id, username, email, favoriteJokes)) }
}
})
}
}
Let’s go through the logic behind the implementation:
When being attentive to jokes, add a child listener to the “funny story” listing. On each child, we parse the shaggy dog story and add it to the listing. Notice the way you parse the data, with the aid of calling getValue(magnificence) the picture is parsed to whatever facts version you want.
Favorite jokes might be stored on every user’s profile. Since the queries within the database are confined, you can not request all jokes by using ids. This is why jokes are stored on the consumer. You’ll study favourite jokes from each of the users’ profile listing. Every time that directory modifications, you get an occasion, since you need to recognize which jokes are appreciated in order to expose the best icon in the listing. The identical goes for the profile, as you’re displaying the number of favorite jokes there.
To look up a profile, you have to call the kid(KEY_USER) to enter the “customers” listing after which infant(id) to find a specific person. However there may be extra to a profile than simply the consumer component. Since lists are absolutely HashMaps in Firebase, you need to manually parse every object. For that motive there may be the quite ugly block of code for mapping all the children.
Closing up
In order to add a new comic story, create a child in the “jokes” directory, and set the cost to the joke item:
override fun addNewJoke(joke: Joke, onResult: (Boolean) -> Unit) {
val newJokeReference = database.reference.child(KEY_JOKE).push()
val newJoke = joke.copy(id = newJokeReference.key)
newJokeReference.setValue(newJoke).addOnCompleteListener { onResult(it.isSuccessful && it.isComplete) }
}
By calling push, you generate a brand new key like noted before. Set the price to the brand new funny story and add a listener to be notified about finishing touch.
Changing whether the comic story is for your favorites or no longer is a piece trickier. You first should recognize if it’s to your favorites, and then eliminate it if it already is, or add if it isn’t:
override fun changeJokeFavoriteStatus(joke: Joke, userId: String) {
val reference = database.reference
.child(KEY_USER)
.child(userId)
.child(KEY_FAVORITE)
.child(joke.id)
reference.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(error: DatabaseError?) {}
override fun onDataChange(snapshot: DataSnapshot?) {
val oldJoke = snapshot?.getValue(JokeResponse::class.java)
if (oldJoke!=null) {
reference.setValue(null)
} else {
reference.setValue(joke)
}
}
})
}
By listening for the value of a toddler, you may inform that the kid doesn’t exist if the price is null – or on your case, that a shaggy dog story isn’t a favorite. Same is going the other manner round, if it’s no longer null, you know the kid exists.
Build and Run the app. Go and add a brand new shaggy dog story. You should see it in the all jokes list:
It isn’t always but introduced on your preferred jokes, click at the heart icon to feature it to favorites. Go returned to the Firebase console and the Database/Data tab, and also you’ll see the favourite funny story inside the data. If you click on the heart icon once more and switch again to the console, it have to be gone. The electricity of realtime updates! :]
Take a take a look at the Firebase dashboard, your database need to have some facts in it now.
Where to go from here
Congratulations on creating your shaggy dog story-sharing social app! Wasn’t it simply puntastic! You can download the final project via the usage of the hyperlink at the pinnacle or bottom of this tutorial.
There is plenty more to Firebase than the Auth/Database offerings, attempt exploring every thing of it by means of following the documentation.
Also take a look at out the Firestore, the upgraded model of the database we used.
You can also study the Joe Birch article series about each of the services.
And most importantly, experience free to leave remarks and tips within the phase under! Your feedback means loads! :]