Share this post on:

Lets see how we can set Data in Recycler View from Firebase in Fragment using Kotlin Language in Android studio.

A Fragment represents a reusable portion of your app’s UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own–they must be hosted by an activity or another fragment.

Step 1 : Create a Blank Fragment named as Public Group. Now create a Layout Design of Items in Fragment Layout.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Fragments.PublicGroupFragments">

<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/groupRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:layout_marginBottom="3dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="@layout/layout_publicgroup" />


<LinearLayout
android:id="@+id/createGroup"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="14dp"
android:background="@drawable/profile_edit"
app:fabCustomSize="50dp">

<ImageView
android:id="@+id/edit"
android:layout_width="50dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:src="@drawable/add_status_vector"
app:tint="@color/white" />
</LinearLayout>

</RelativeLayout>


</FrameLayout>

Step 2 : Create a Model class

package com.raiyanshahid.letstalk.publicGroup.Model

class PublicGroup_Model {

var groupid: String? = null
var title: String? = null
var description: String ?= null
var url : String ?= null
var topic : String ?= null
var groupImage : String ?= null
var profileImage : String ?= null
var createdBy : String ?= null
var uid : String ?= null



constructor(
groupid: String?,
title: String?,
description: String?,
url: String?,
topic: String?,
groupImage: String?,
profileImage: String?,
createdBy : String?,
uid : String?
) {
this.groupid = groupid
this.title = title
this.description = description
this.url = url
this.topic = topic
this.groupImage = groupImage
this.profileImage = profileImage
this.createdBy = createdBy
this.uid = uid
}

constructor()
}

Step 3 : Create a Adapter class

class PublicGroup_Adapter  (arrayList: ArrayList<PublicGroup_Model>, mContext: Context) : RecyclerView.Adapter<PublicGroup_Adapter.MyViewHolder>() {

var arrayList: ArrayList<PublicGroup_Model>
var mContext: Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.layout_publicgroup, parent, false)
return MyViewHolder(view)
}

override fun onBindViewHolder(holder: MyViewHolder, @SuppressLint("RecyclerView") position: Int) {
val model: PublicGroup_Model = arrayList[position]
var totalUsers : String ?= null
holder.groupname.setText(arrayList[position].title)
val timeAgo = TimeAgo.getTimeAgo(arrayList[position].groupid!!.toLong())
holder.createdAt.setText("Created "+timeAgo)
holder.createdBy.setText("Created by "+arrayList[position].createdBy)
Glide.with(mContext)
.load(arrayList[position].groupImage)
.placeholder(R.drawable.letstalk_logo)
.into(holder.groupimage)

var userImage : String ?= null
var userName : String ?= null

FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().uid!!)
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
userName = snapshot.child("name").getValue(String::class.java)
userImage = snapshot.child("profileImage").getValue(String::class.java)
}

override fun onCancelled(error: DatabaseError) {}
})


holder.itemView.setOnClickListener {
val firebaseAuth : FirebaseAuth = FirebaseAuth.getInstance()
val rootRef = FirebaseDatabase.getInstance().reference
val userNameRef = rootRef.child("PublicGroupParticipants").child(arrayList[position].groupid!!)
.child("Participants").child(firebaseAuth!!.uid!!)
val eventListener: ValueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (!dataSnapshot.exists()) {
val bottomSheetDialog = BottomSheetDialog(mContext, R.style.BottomSheetDialogTheme)
val bottomsheetView = LayoutInflater.from(mContext).inflate(R.layout.layout_joingroup,
bottomSheetDialog.findViewById<CardView>(R.id.bottomJoinGroup) as CardView?)

bottomsheetView.findViewById<TextView>(R.id.groupTitle).setText(arrayList[position].title)
bottomsheetView.findViewById<TextView>(R.id.member).setText(totalUsers+" members")
bottomsheetView.findViewById<TextView>(R.id.description).setText(arrayList[position].description)
bottomsheetView.findViewById<TextView>(R.id.url).setText(arrayList[position].url)
bottomsheetView.findViewById<TextView>(R.id.createdby).setText("Created by "+arrayList[position].createdBy)
val timeAgo = TimeAgo.getTimeAgo(arrayList[position].groupid!!.toLong())
bottomsheetView.findViewById<TextView>(R.id.createdOn).setText("Created on "+timeAgo)
bottomsheetView.findViewById<ImageView>(R.id.close)
.setOnClickListener { bottomSheetDialog.dismiss() }

bottomsheetView.findViewById<Button>(R.id.joingroup).setOnClickListener {
val timestamp = "" + System.currentTimeMillis()
val hashMap = HashMap<String, String>()
hashMap["uid"] = firebaseAuth!!.uid!!
hashMap["role"] = "participant"
hashMap["userImage"] = userImage!!
hashMap["user"] = userName!!
hashMap["timestamp"] = "" + timestamp
val reference = FirebaseDatabase.getInstance().getReference("PublicGroupParticipants")
reference.child(arrayList[position].groupid!!).child("Participants").child(firebaseAuth!!.uid!!).setValue(hashMap)
.addOnSuccessListener {
Toast.makeText(mContext, "You Added successfully in "+ arrayList[position].title, Toast.LENGTH_SHORT).show()
val intent = Intent(mContext, TcmGroupChat::class.java)
intent.putExtra("sdgid",arrayList[position].groupid)
intent.putExtra("totalUsers",totalUsers)
intent.putExtra("sdgimage",arrayList[position].groupImage)
intent.putExtra("sdgname",arrayList[position].title)
intent.putExtra("sdgdescription",arrayList[position].description)
intent.putExtra("sdg",arrayList[position].topic)
intent.putExtra("createdby",arrayList[position].createdBy)
intent.putExtra("url",arrayList[position].url)
intent.putExtra("uid",arrayList[position].uid)
mContext.startActivity(intent)
}.addOnFailureListener {
Toast.makeText(mContext, " Failed!! Try Again Later", Toast.LENGTH_SHORT).show()
}
bottomSheetDialog.dismiss()
}
bottomSheetDialog.setContentView(bottomsheetView)
bottomSheetDialog.show()
}
else
{
val intent = Intent(mContext, TcmGroupChat::class.java)
intent.putExtra("sdgid",arrayList[position].groupid)
intent.putExtra("totalUsers",totalUsers)
intent.putExtra("sdgimage",arrayList[position].groupImage)
intent.putExtra("sdgname",arrayList[position].title)
intent.putExtra("createdby",arrayList[position].createdBy)
intent.putExtra("sdgdescription",arrayList[position].description)
intent.putExtra("sdg",arrayList[position].topic)
mContext.startActivity(intent)
}
}

override fun onCancelled(databaseError: DatabaseError) {
Log.d(ContentValues.TAG, databaseError.message) //Don't ignore errors!
}
}
userNameRef.addListenerForSingleValueEvent(eventListener)
}


//This is used fo taking the total numbers of Members ina Tcm Group
var userReference = FirebaseDatabase.getInstance().getReference("PublicGroupParticipants")
.child(arrayList[position].groupid!!).child("Participants")
userReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
totalUsers = dataSnapshot.childrenCount.toString()
holder.groupMember.setText(totalUsers)
}

override fun onCancelled(databaseError: DatabaseError) {}
})

}

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

inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var groupimage: ImageView
var groupname: TextView
var groupMember: TextView
var groupVisibility : TextView
var createdAt : TextView
var createdBy : TextView


init {
groupimage = itemView.findViewById(R.id.groupImage)
groupname = itemView.findViewById(R.id.groupName)
groupMember = itemView.findViewById(R.id.totalmember)
groupVisibility = itemView.findViewById(R.id.groupVisisbility)
createdAt = itemView.findViewById(R.id.createdDate)
createdBy = itemView.findViewById(R.id.createdBy)
}
}

init {
this.arrayList = arrayList
this.mContext = mContext
}
}

Step 4: Create Layout for Adapter

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="3dp"
android:layout_alignParentTop="true">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="150dp"
app:cardCornerRadius="18dp"
android:id="@+id/top">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/groupImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/travel" />

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/bottom_design"
android:orientation="horizontal">

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:orientation="vertical">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/groupName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:textColor="@color/white"
android:textSize="16sp"
android:padding="1dp"
android:textStyle="bold" />
</LinearLayout>

<TextView
android:id="@+id/groupVisisbility"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type : Public Group"
android:textColor="@color/white"
android:padding="5dp"
android:textSize="11sp" />
</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:orientation="vertical">

<TextView
android:id="@+id/createdDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="end"
android:padding="1dp"
android:textColor="@color/white"
android:textSize="12sp" />

<TextView
android:id="@+id/createdBy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="end"
android:padding="5dp"
android:textColor="@color/white"
android:textSize="12sp" />
</LinearLayout>


</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginRight="12dp"
android:gravity="end"
android:orientation="vertical">

<TextView
android:id="@+id/totalmember"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:textColor="#DD660D"
android:textSize="30sp"
android:layout_marginRight="5dp"
android:textStyle="bold" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Members"
android:textColor="@color/white"
android:textSize="20sp" />

</LinearLayout>

</RelativeLayout>
</androidx.cardview.widget.CardView>

</RelativeLayout>

Step 5 : Finally set Your adapter and model class in PublicGroupFragment





class PublicGroupFragments : Fragment() {

var createGroup : LinearLayout?= null
var groupRecyclerView : RecyclerView?= null
var groupModel : ArrayList<PublicGroup_Model>? = null
var groupAdapter : PublicGroup_Adapter?= null
var database : FirebaseDatabase?= null


override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
var view: View= inflater.inflate(R.layout.fragment_public_group_fragments, container, false)

createGroup = view.findViewById(R.id.createGroup)
groupRecyclerView = view.findViewById(R.id.groupRecyclerView)
database = FirebaseDatabase.getInstance()
groupModel = ArrayList()


val reference = database!!.reference.child("PublicGroup")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
groupModel?.clear()
for (dataSnapshot in snapshot.children) {
val registrationModel: PublicGroup_Model? = dataSnapshot.getValue(PublicGroup_Model::class.java)
val newsModel = PublicGroup_Model()
newsModel.title = registrationModel?.title
newsModel.groupImage = registrationModel?.groupImage
newsModel.description = registrationModel?.description
newsModel.url = registrationModel?.url
newsModel.createdBy = registrationModel?.createdBy
newsModel.topic = registrationModel?.topic
newsModel.description = registrationModel?.description
newsModel.groupid = registrationModel?.groupid
newsModel.uid = registrationModel?.uid
groupModel!!.add(newsModel)

}
groupAdapter!!.notifyDataSetChanged()
}

override fun onCancelled(error: DatabaseError) {}
})

groupAdapter = PublicGroup_Adapter(groupModel!!, requireContext())
groupRecyclerView?.setAdapter(groupAdapter)

createGroup!!.setOnClickListener {
startActivity(Intent(context, CreatePublicGroup::class.java))
}

return view
}
}

Result :

Share this post on:
Avatar Raiyan

Author: Raiyan

Hi, I guess you're here because you want to know a bit about me. huh? I am not so good on talking about myself but I'll give a short about me.

My Name is Raiyan. I am a Professional Application Developer and a Blogger.
I started this website to Share my Knowledge. Here I provide all my knowledge whatever I earned till now.

Leave a Comment

Your email address will not be published. Required fields are marked *