1

os pongo en contexto, mediante un recyclerView estoy obteniendo los datos de los proveedores de una bd (firebase/firestore), estos los muestra correctamente, la cuestión es que me gustaría que mediante una acción de clic obtener el modelo seleccionado y enviarlo al fragment NewNonPerishableFragment, para ello uso un Fragment principal, Fragment con recyclerView, el adaptador y el modelo del objeto.

Aqui el codigo:

Modelo:

class ProviderModel {

    var Name: String? = null

    constructor()
}

Adaptador:

open class ProviderAdapter(options: FirestoreRecyclerOptions<ProviderModel>) :
    FirestoreRecyclerAdapter<ProviderModel, ProviderAdapter.ProviderVH>(options) {

    class ProviderVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var providerName = itemView.findViewById<TextView>(R.id.textViewProviderName)
    }

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

    override fun onBindViewHolder(holder: ProviderVH, position: Int, model: ProviderModel) {
        holder.providerName.text = model.Name
        holder.itemView.setOnClickListener { view ->

        }
    }
}

Fragment proveedor:

class ProviderFragment() : Fragment(){

    private lateinit var nav: NavController
    private lateinit var root: View
    private var adapter: ProviderAdapter? = null
    private var db: FirebaseFirestore = FirebaseFirestore.getInstance()
    private var providerRef: CollectionReference = db.collection("provider")


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        root = inflater.inflate(R.layout.fragment_recyclerprovider, container, false)
        setUpRecyclerView()
        return root
    }

    private fun setUpRecyclerView() {
        var query: Query = providerRef.orderBy("Name")
        var options: FirestoreRecyclerOptions<ProviderModel> = FirestoreRecyclerOptions.Builder<ProviderModel>()
            .setQuery(query, ProviderModel::class.java).build()

        adapter = ProviderAdapter(options)
        var providers: RecyclerView = root.findViewById(R.id.recyclerView)
        providers.layoutManager = LinearLayoutManager(context)
        providers.adapter = adapter
    }

    override fun onStart() {
        super.onStart()
        adapter!!.startListening()
    }

    override fun onStop() {
        super.onStop()
        adapter!!.stopListening()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        nav = Navigation.findNavController(view)
        view.findViewById<FloatingActionButton>(R.id.buttonAddPerishable).setOnClickListener() {
            nav.navigate(R.id.nav_newProviderFragment)
        }
    }
}

fragment principal:

class NewNonPerishableFragment : Fragment() {

    private lateinit var nav: NavController
    private lateinit var auth: FirebaseAuth
    private lateinit var db: FirebaseFirestore

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_newnonperishable, container, false)
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        db = Firebase.firestore
        auth = Firebase.auth
        var date: String
        var product: String
        var provider: String
        var delivery: String
        var lot: String
        var amount: String
        var condition: String
        var preferentialDate: String
        var startDate: String
        var endDate: String
        var responsable: String = ""

        db.collection("users")
            .whereEqualTo("Email", auth.currentUser.email.toString())
            .get()
            .addOnSuccessListener { documents ->
                for (document in documents) {
                    responsable = document.data.get("Name").toString()
                    view.findViewById<TextInputEditText>(R.id.TextInputEditTextResponsable)
                        .setText(responsable)
                }
            }
            .addOnFailureListener { _ ->
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextResponsable)
                    .setText("")
            }

        view.findViewById<TextInputEditText>(R.id.TextInputEditTextDate)
            .setText(SimpleDateFormat("dd/MM/yyy").format(Date()))

        nav = Navigation.findNavController(view)
        view.findViewById<Button>(R.id.buttonChooseDate).setOnClickListener() {
            nav.navigate(R.id.nav_dateFragment)
        }
        view.findViewById<Button>(R.id.buttonChoosePreferentialDate).setOnClickListener() {
            nav.navigate(R.id.nav_preferentialDateFragment)
        }
        view.findViewById<Button>(R.id.buttonChooseStartDate).setOnClickListener() {
            nav.navigate(R.id.nav_startDateFragment)
        }
        view.findViewById<Button>(R.id.buttonChooseEndDate).setOnClickListener() {
            nav.navigate(R.id.nav_endDateFragment)
        }
        view.findViewById<Button>(R.id.buttonReset).setOnClickListener() {
            reset(view, responsable)
        }
        view.findViewById<Button>(R.id.buttonChooseProvider).setOnClickListener() {
            nav.navigate(R.id.nav_providerFragment)
        }
        view.findViewById<Button>(R.id.buttonChooseResponsable).setOnClickListener() {
            nav.navigate(R.id.nav_responsableFragment)
        }

        view.findViewById<Button>(R.id.buttonUpload).setOnClickListener() {
            date =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextDate).text.toString()
            product =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextProduct).text.toString()
            provider =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextProvider).text.toString()
            delivery =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextDelivery).text.toString()
            lot =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextLotNumber).text.toString()
            amount =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextAmount).text.toString()
            condition =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextCondition).text.toString()
            preferentialDate =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextPreferentialDate).text.toString()
            startDate =
                view.findViewById<TextInputEditText>(R.id.TextInputEdiStartDate).text.toString()
            endDate =
                view.findViewById<TextInputEditText>(R.id.TextInputEditEndDate).text.toString()
            responsable =
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextResponsable).text.toString()

            val newNonPerishable = hashMapOf(
                "Date" to date,
                "Product" to product,
                "Provider" to provider,
                "Delivery" to delivery,
                "Lot" to lot,
                "Amount" to amount,
                "Condition" to condition,
                "PreferentialDate" to preferentialDate,
                "StartDate" to startDate,
                "EndDate" to endDate,
                "Responsable" to responsable
            )
            try {
                db.collection("nonPerishable")
                    .add(newNonPerishable)
                Toast.makeText(context, R.string.successfully, Toast.LENGTH_LONG).show()
                reset(view, responsable)
            } catch (e: Exception) {
                Toast.makeText(context, R.string.Error, Toast.LENGTH_LONG).show()
            }
        }

        parentFragmentManager.setFragmentResultListener(
            "date",
            this,
            FragmentResultListener { _, result ->
                var datetoday: String? = result.getString("date")
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextDate).setText(datetoday)
            })
        parentFragmentManager.setFragmentResultListener(
            "preferentialDate",
            this,
            FragmentResultListener { _, result ->
                var preferentialdate: String? = result.getString("preferentialDate")
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextPreferentialDate)
                    .setText(preferentialdate)
            })
        parentFragmentManager.setFragmentResultListener(
            "startDate",
            this,
            FragmentResultListener { _, result ->
                var startdate: String? = result.getString("startDate")
                view.findViewById<TextInputEditText>(R.id.TextInputEdiStartDate)
                    .setText(startdate)
            })
        parentFragmentManager.setFragmentResultListener(
            "endDate",
            this,
            FragmentResultListener { _, result ->
                var enddate: String? = result.getString("endDate")
                view.findViewById<TextInputEditText>(R.id.TextInputEditEndDate)
                    .setText(enddate)
            })

        parentFragmentManager.setFragmentResultListener(
            "provider",
            this,
            FragmentResultListener { _, result ->
                var provider: String? = result.getString("provider")
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextProvider)
                    .setText(provider)
            })

        parentFragmentManager.setFragmentResultListener(
            "responsable",
            this,
            FragmentResultListener { _, result ->
                var responsable: String? = result.getString("responsable")
                view.findViewById<TextInputEditText>(R.id.TextInputEditTextResponsable)
                    .setText(responsable)
            })



    }

    fun reset(view: View, responsable: String) {
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextDate)
            .setText(SimpleDateFormat("dd/MM/yyy").format(Date()))
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextProduct).setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextProvider).setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextDelivery).setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextLotNumber).setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextAmount).setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextCondition).setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextPreferentialDate)
            .setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEdiStartDate).setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEditEndDate).setText("")
        view.findViewById<TextInputEditText>(R.id.TextInputEditTextResponsable).setText(responsable)
    }
}

Comentar que llevo poco tiempo en Android y kotlin.

4
  • Bienvenido! Por "valor/nombre del objeto seleccionado" te refieres al ProviderModel seleccionado? A cuál de los dos fragment quieres enviarlo y que relación existe entre ellos? Commented el 28 may. 2021 a las 22:12
  • Así es @SinneroftheSystem , me refiero al modelo seleccionado, el valor me gustaría recibirlo en el fragment principal NewNonPerishableFragment para luego introducirlo en un textEdit. De momento me muestra el valor al cual le hago clic por consola, pero no consigo enviarlo a donde deseo. ¡Si necesitas algo mas respecto al código solo tienes que pedirlo! ^^
    – Miguel
    Commented el 28 may. 2021 a las 23:06
  • Refactoricé uno de tus fragments pero el otro también deberías refactorizarlo porque estás repitiendo mucho código innecesario Commented el 28 may. 2021 a las 23:18
  • disculpa, olvidaste aceptar la respuesta o no te sirvió? Commented el 28 jun. 2021 a las 2:23

1 respuesta 1

0

Una forma de hacerlo es agregar un parámetro al adapter para poder setear el click listener desde el fragment

open class ProviderAdapter(
    options: FirestoreRecyclerOptions<ProviderModel>,
    val onClick: (ProviderModel) -> Unit // callback a ejecutar dentro del click listener
) :
    FirestoreRecyclerAdapter<ProviderModel, ProviderAdapter.ProviderVH>(options) {

    class ProviderVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var providerName = itemView.findViewById<TextView>(R.id.textViewProviderName)
    }

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

    override fun onBindViewHolder(holder: ProviderVH, position: Int, model: ProviderModel) {
        holder.providerName.text = model.Name
        holder.itemView.setOnClickListener { onClick(model) } // ejecuta callback
    }
}

Luego en el fragment creas creas un callback que navegue al fragment deseado y lo pasas como argumento al constructor del adapter. Los argumentos se pasan en un bundle a la función navController.navigate

class ProviderFragment() : Fragment(R.layout.fragment_recyclerprovider) {
    private lateinit var navController: NavController

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        navController = Navigation.findNavController(view)
        setUpRecyclerView(view.findViewById(R.id.recyclerView))
        view.findViewById<FloatingActionButton>(R.id.buttonAddPerishable).setOnClickListener {
            navController.navigate(R.id.nav_newProviderFragment)
        }
    }

    private fun setUpRecyclerView(recycler: RecyclerView) {
        val query = Firebase.firestore.collection("provider").orderBy("Name")
        val options = FirestoreRecyclerOptions.Builder<ProviderModel>()
            .setQuery(query, ProviderModel::class.java)
            .setLifecycleOwner(viewLifecycleOwner)
            .build()
        recycler.layoutManager = LinearLayoutManager(context)
        recycler.adapter = ProviderAdapter(options) { providerModel ->
            // navega y pasa los datos como argumento
            val args = bundleOf("provider" to providerModel.Name)
            navController.navigate(R.id.fragment_newnonperishable, args)
        }
    }
}

También tendrías que modificar el fragment principal porque no creo que esos result listeners sean compatibles con los argumentos que usa el navigation component.

La forma más simple de recibirlo es así val provider = arguments?.getString("provider") pero hay otras mejores que puedes ver en la documentación

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.