Home > front end >  Implementation of RealTimeDatabase of Firebase into a Kotlin App
Implementation of RealTimeDatabase of Firebase into a Kotlin App

Time:10-08

I was developing an App where I try to connect to a Database, create with firebase, in order to upload the diferents services offer into the App.

My question comes when I see into the firebase documentation, the way to read data from it:

database.child("users").child(userId).child("username").setValue(name)

In my case the structure of my firebase database is the following:

enter image description here

So, my question is who is my 'child', into my firebase database, due to I don't have an id as 'users', and I don't know if I should.

The code where I try to implment this is the following:

package com.example.appadoskotlin2.ui.contract

import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SearchView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.appadoskotlin2.R
import com.example.appadoskotlin2.data.Service
import com.example.appadoskotlin2.databinding.FragmentContractBinding
import com.example.appadoskotlin2.ui.adapters.AdapterContract
import com.google.firebase.database.*
import com.google.firebase.ktx.Firebase

class ContractFragment : Fragment(), (Service) -> Unit {

    private lateinit var contractViewModel: ContractViewModel
    private var _binding: FragmentContractBinding? = null
    private lateinit var searchView: SearchView
    private lateinit var rvContract:RecyclerView
    private lateinit var adapter: AdapterContract
    //TODO("Inicialmente proporcionamos los servicios de manera local.
    // En el futuro hacerlo a traves de una API.")
    private lateinit var services: ArrayList<Service>
    private val binding get() = _binding!!
    private lateinit var database: DatabaseReference

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        contractViewModel =
            ViewModelProvider(this).get(ContractViewModel::class.java)

        _binding = FragmentContractBinding.inflate(inflater, container, false)
        val root: View = binding.root

        //TODO("Cargar array services con servicios de BBDD.")
        val postListener = object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                // Get Post object and use the values to update the UI
               if(dataSnapshot != null){
                   services = ArrayList()
                   services = dataSnapshot.getValue() as ArrayList<Service>
               }else{
                   Toast.makeText(context, "No hay ningun servicio disponible", Toast.LENGTH_LONG).show()
               }
            }

            override fun onCancelled(databaseError: DatabaseError) {
                // Getting Post failed, log a message
                Toast.makeText(context, "Operación cancelada", Toast.LENGTH_LONG).show()
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
            }
        }
        database = FirebaseDatabase.getInstance().reference
        database.addValueEventListener(postListener)


        //services.add(Service("Ofertado", "Fontaneria"))
        //services.add(Service("Ofertado", "Mecanica"))
        //services.add(Service("Ofertado", "Cuidado del hogar"))
        //services.add(Service("Ofertado", "Electricidad"))
        //services.add(Service("Ofertado", "Instalaciónes"))


        searchView = root.findViewById(R.id.svContract)
        rvContract = root.findViewById(R.id.rvContract)
        adapter = AdapterContract(this, services)
        rvContract.adapter = adapter
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                //TODO() Search on the available services


                return false
            }
            override fun onQueryTextChange(newText: String): Boolean {
                //TODO() Change the text on SerchView to newText

                return false
            }
        })
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun invoke(service: Service) {
        //TODO() Implemenetar busqueda en la BBDD de firebase

        Toast.makeText(context, "Buscando servicio: "   service.type, Toast.LENGTH_LONG).show()
    }
}

The question is due to unkoledge of the working flowof firebase database.

So if you can help take thanks in advance !

[EDIT]

Ad the Service model class:

@kotlinx.serialization.Serializable
data class Service(
    val status: String?,
    val type: String,
) : Serializable

CodePudding user response:

There are more ways to read the data than what is described in the question. But first you need to define your data model in terms of 'documents' and 'collections' as described by the Firebase documentation

Some pointers so that you can clarify the data model:

What is the relationship between services and user? i.e each user can have distinct services that you store? Or are there same three services for all users that are stored in Firebase just so that realtime status of each service is available all the time?

CodePudding user response:

if(dataSnapshot != null){
   services = ArrayList()
   services = dataSnapshot.getValue() as ArrayList<Service>
}else{
   Toast.makeText(context, "No hay ningun servicio disponible", Toast.LENGTH_LONG).show()
}

Make change Here To This

if(dataSnapshot != null){
   services = ArrayList();
   for(snap in dataSnapshot.childern){
     services.add(Service(
        snap.getValue(String::class.java),
        snap.key
     ))
   }
}else{
   Toast.makeText(context, "No hay ningun servicio disponible", Toast.LENGTH_LONG).show()
}
  • Related