Building a Joke App with Cloud Firestore using Kotlin part 2

Nwokocha Wisdom Maduabuchi
3 min readSep 19, 2020

--

Images by The Net Ninja

In this part of the tutorial, you will focus on coding the project so let's go down to business.

Follow the steps below

Step 1: Add the required dependencies and client libraries to your app.

implementation 'com.google.firebase:firebase-firestore-ktx:21.6.0'

Step 2: Initialize an instance of Cloud Firestore

val db = Firebase.firestore

Step 3: Add data from android app to Cloud Firestore

val user = hashMapOf(
"joke" to jokename,
)

db.collection("Jokes").add(user)
.addOnSuccessListener {

Toast.makeText(application, "Saved Successfully", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Toast.makeText(application, "Not Successful", Toast.LENGTH_SHORT).show()
}

Step 4: Retrieve data from Cloud Firestore

you will create a class with the field names that will correspond to the Cloud Firestore field names

Joke Model Class

class JokesModel(
var joke: String? = null
)
db.collection("Jokes").addSnapshotListener  { snapshot, e ->

val getjokes = ArrayList<JokesModel?>()

for (document in snapshot!!){

getjokes.add(
JokesModel(
document.getString("joke")
)
)
val ty = Adapter(getjokes, applicationContext)
recy.adapter = ty
ty.notifyDataSetChanged()

}

Create an Adapter Class

class Adapter(
private var dataList: ArrayList<JokesModel?>,
private val context: Context
) :
RecyclerView.Adapter<Adapter.ViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(context).inflate(
R.layout.list_of_jokes,
parent,
false
)
)

}

override fun getItemCount(): Int {
return dataList.size
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val dataModel = dataList.get(position)
holder.listj.text = dataModel?.joke

}

class ViewHolder(itemLayoutView: View) : RecyclerView.ViewHolder(itemLayoutView) {
var listj: TextView = itemLayoutView.findViewById(R.id.listjoke)

}


}

Finally, you can test your joke app now

Android Emulator

Cloud Firestore database

With Cloud Firestore you can build awesome projects not only for Android, but it also covers so many platforms like IOS, Web, Cross-platform( Flutter, React Native), and more.
Thanks for reading and I hope it will help you with your next project.
Github: https://github.com/wise4rmgod/JokeFirestoreExample

--

--

Nwokocha Wisdom Maduabuchi
Nwokocha Wisdom Maduabuchi

Written by Nwokocha Wisdom Maduabuchi

A software engineer with considerable experience in mobile development, native Android, and IOS development(Xcode), flutter dev, technical writing and community

No responses yet