Home > database >  Recycler View not displaying inside a Fragment
Recycler View not displaying inside a Fragment

Time:05-16

I'm using Recycler view to show items in my Fragment named Recent History. I want to display user data from firebase to my recent history Fragment. But the recycler view is not showing on the fragment. Please Help me out in this. What did I do wrong here? or what's the solution so that my fragment shows the recycler view.

Recent History Fragment Code:

`
class recent_history : Fragment(R.layout.fragment_recent_history) {

    private var binding: FragmentRecentHistoryBinding? = null
    private lateinit var auth: FirebaseAuth

    var database: FirebaseDatabase? = null
    var databaseReference: DatabaseReference? = null
     private lateinit var userArrayList: ArrayList<User>
     private lateinit var myAdapter: AdapterClass


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentRecentHistoryBinding.inflate(inflater, container, false)
        return binding!!.root


    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        auth = FirebaseAuth.getInstance()
        database = FirebaseDatabase.getInstance()
        databaseReference = database?.reference!!.child("Users").child("result")
        userArrayList= arrayListOf()
        myAdapter=AdapterClass(userArrayList)
        binding?.recyclerview.apply {
            binding?.recyclerview?.adapter = myAdapter
            var linearLayoutManager = LinearLayoutManager(activity)
            binding?.recyclerview?.layoutManager = linearLayoutManager
            binding?.recyclerview?.setHasFixedSize(true)
        }
        getData()

    }

    override fun onDestroy() {
        super.onDestroy()
        binding = null
    }
    private fun getData() {
        val user = auth.currentUser


        databaseReference?.child(user?.uid!!)
        databaseReference!!.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    for (data in snapshot.children) {
                        var model = data.getValue(User::class.java)
                        userArrayList.add(model!!)

                    }

                }

                }

            override fun onCancelled(error: DatabaseError) {
                Log.e("cancel", error.toString())
            }

        })
    }
}

`

Fragment Recent History Layout

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".recent_history">

    <TextView
        android:id="@ id/profiletitle"
        android:layout_width="389dp"
        android:layout_height="46dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="28dp"
        android:fontFamily="monospace"
        android:text="Recent Search History"
        android:textAlignment="center"
        android:textColor="@color/Twit"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </TextView>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@ id/recyclerview"
        android:layout_width="220dp"
        android:layout_height="664dp"
        android:layout_marginBottom="100dp"
        android:orientation="vertical"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/profiletitle"
        tools:listitem="@layout/adapterview">


    </androidx.recyclerview.widget.RecyclerView>


</androidx.constraintlayout.widget.ConstraintLayout>

I'm sending data to firebase from another Fragment named keyword Fragment.  My Firebase snippet Code of keyword fragment:

class keywordfrag : Fragment() {
    private var binding: FragmentKeywordfragBinding? = null
    private lateinit var auth: FirebaseAuth

    var database: FirebaseDatabase? = null
    var databaseReference: DatabaseReference? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentKeywordfragBinding.inflate(inflater, container, false)
        return binding!!.root

    }

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

        auth = FirebaseAuth.getInstance()
        database = FirebaseDatabase.getInstance()
        val user = auth.currentUser
        databaseReference?.child(user?.uid!!)

        databaseReference = database?.getReference("Users")?.child("result")
        binding?.analyzebtn?.setOnClickListener {
            sendData()

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding = null
    }
    private fun sendData() {

        val keywordtext = binding?.userenteredkeyword?.text.toString().trim()
        val timestamp = Timestamp(System.currentTimeMillis())
        val timendate = timestamp.toString().trim()
//        val username=auth.currentUser?.uid.toString().trim()
//        val email=auth.currentUser?.email.toString().trim()

        if (TextUtils.isEmpty(keywordtext)) {
            binding?.userenteredkeyword?.error = "keyword can not be Empty"
        } else {

            val model = User(keywordtext, timendate)
            val user = auth.currentUser
             databaseReference?.child(user?.uid!!)?.setValue(model)
            binding?.userenteredkeyword?.setText("")
            val currentUser = auth.currentUser
            val currentUserdb = databaseReference?.child((currentUser?.uid!!))

            currentUserdb?.child("keywordtext")?.setValue(keywordtext)
            currentUserdb?.child("timendate")?.setValue(timendate)



        }

    }
}

Adapter Class:

    package com.example.emotela_finalyearproject

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.emotela_finalyearproject.databinding.AdapterviewBinding
import kotlin.collections.ArrayList

class AdapterClass(var list:ArrayList<User>) :RecyclerView.Adapter<AdapterClass.ViewHolder>() {
    class ViewHolder(val binding: AdapterviewBinding) : RecyclerView.ViewHolder(binding.root) {
        var keyword = binding.keywordtv
        var timenddate=binding.timendatetv


    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = AdapterviewBinding.inflate(LayoutInflater.from(parent.context), parent, false)

        return ViewHolder(binding)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        with(holder) {
            with(list[position]) {
                keyword.text = this.keywordtext
                timenddate.text= this.timendate

            }


        }


    }

}

Adapter view Layout

    <?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardElevation="8dp"
    app:cardCornerRadius="8dp"
    android:layout_margin="16dp">

    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginVertical="6dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="336dp"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@ id/keywordtitle"
                android:layout_width="141dp"
                android:layout_height="35dp"
                android:fontFamily="monospace"
                android:text="searched word: "
                android:textSize="10sp"
                android:textStyle="bold">

            </TextView>

            <TextView
                android:id="@ id/keywordtv"
                android:layout_width="143dp"
                android:layout_height="36dp"
                android:fontFamily="monospace"
                android:textSize="10sp">

            </TextView>


            <TextView
                android:id="@ id/timeanddatetitle"
                android:layout_width="160dp"
                android:layout_height="36dp"
                android:fontFamily="monospace"
                android:text="Time and Date: "
                android:textSize="10sp"
                android:textStyle="bold">

            </TextView>

            <TextView
                android:id="@ id/timendatetv"
                android:layout_width="171dp"
                android:layout_height="48dp"
                android:fontFamily="monospace"
                android:textSize="10sp">

            </TextView>

            <LinearLayout
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginVertical="6dp"
                android:orientation="horizontal">


                <LinearLayout
                    android:layout_width="336dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical"
                    android:orientation="vertical">

                </LinearLayout>
            </LinearLayout>



        </LinearLayout>

    </LinearLayout>





</androidx.cardview.widget.CardView>

Result in Emulator:

Result showing in Emulator

CodePudding user response:

You need to calll

imageAdapter.notifyDataSetChanged()

after you fetch the data from firebase.

  • Related