how to display each array item to recyclerview in kotin (FireStore) - android

Database
enter image description here
output
enter image description here
it only showing the last entry in array i wann show each entry
Adapter code
package com.example.caterers_app
class CommentAdapter(private val commentlist : ArrayList<CommentDataClass>) : RecyclerView.Adapter<CommentAdapter.MyViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): CommentAdapter.MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.commentstemplate,
parent,false)
return MyViewHolder(itemView) }
override fun getItemCount(): Int {
Log.d("size", commentlist.size.toString())
return commentlist.size
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val comment : TextView = itemView.findViewById(R.id.comment)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val comments = commentlist[position]
comments.list?.forEach {
holder.comment.text = it.toString()
}
//holder.comment.text = comments.list.toString()
}
}
if i use holder.comment.text = comments.list.toString()
it will display all array items in single recyclerview block
data class
package com.example.caterers_app
data class CommentDataClass(val list : List<String>? = null)
{
}
fragment
package com.example.caterers_app
class Comments(val doc : String) : Fragment() {
private lateinit var docid : String
private lateinit var recyclerView: RecyclerView
private lateinit var commentarraylist : ArrayList<CommentDataClass>
private lateinit var adapter: CommentAdapter
private lateinit var db : FirebaseFirestore
init {
docid = doc
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_comments, container, false)
recyclerView = view.findViewById(R.id.comentoo)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.setHasFixedSize(true)
commentarraylist = arrayListOf()
adapter = CommentAdapter(commentarraylist)
recyclerView.adapter = adapter
EventChangeListner()
return view
}
companion object {
fun newInstance(): Comments {
return Comments("null")
}
}
private fun EventChangeListner() {
var obj = CommentDataClass()
db = FirebaseFirestore.getInstance()
db.collection("User_Events")
.addSnapshotListener(object : EventListener<QuerySnapshot> {
override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {
if(error!= null) {
return
}
for (dc : DocumentChange in value?.documentChanges!!){
if(dc.type == DocumentChange.Type.ADDED){
//eventarraylist.add(dc.document.toObject(EventsData::class.java))
if(dc.document.id.toString() == docid.toString()){
obj = dc.document.toObject(CommentDataClass::class.java)
commentarraylist.add(obj)
}
}
}
adapter.notifyDataSetChanged()
}
})
}
}
i want to display each array item in seperate recyclerview item how can i do that in kotlin using firebase firestore

You're passing an ArrayList<CommentDataClass> into the adapter when you likely want to pass List<String> instead, since CommentDataClass contains that List<String>?
You'll probably want to make CommentAdapter.commentlist modifiable:
class CommentAdapter() : RecyclerView.Adapter<CommentAdapter.MyViewHolder>() {
var commentlist = emptyList<String>()
...
}
and overwrite it once you have your CommentDataClass:
if(dc.document.id.toString() == docid.toString()){
obj = dc.document.toObject(CommentDataClass::class.java)
adapter.commentlist = obj.list
}

Related

Unable to get realtime database in recyclerview of the fragment

I am trying to get data in recyclerview of fragment from realtime database.
Here is the code of Home Fragment I used to get data from realtime database:-
class HomeFragments : Fragment() {
private var recyclerView: RecyclerView? = null
private var typesAdapter: SU_Types_adapter? = null
private var type: MutableList<SU_Type_Model>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
recyclerView = rv_home_fragment
recyclerView?.setHasFixedSize(true)
recyclerView?.layoutManager = GridLayoutManager(activity, 2)
type = ArrayList()
typesAdapter = activity?.let { SU_Types_adapter(it, type as ArrayList<SU_Type_Model>, true) }
recyclerView?.adapter = typesAdapter
val typesRef = FirebaseDatabase.getInstance().getReference().child("SU_Types").orderByChild("type")
typesRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (snapshot in dataSnapshot.children) {
typesAdapter?.notifyDataSetChanged()
val su_type = snapshot.getValue(SU_Type_Model::class.java)
if (su_type != null) {
(type as ArrayList<SU_Type_Model>)?.add(su_type)
}
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home_fragments, container, false)
}
}
Here is the adapter code that I use to get the database data:-
class SU_Types_adapter(
private var mContext: Context,
private var mTypes: List<SU_Type_Model>,
private var isActivity: Boolean = false
) : RecyclerView.Adapter<SU_Types_adapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =
LayoutInflater.from(mContext).inflate(R.layout.rv_home_fragment_adapter, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val su_type = mTypes[position]
Picasso.get().load(su_type.getImageUrl()).into(holder.ImageIv)
holder.ImgId.text = su_type.gettype()
}
override fun getItemCount(): Int {
return mTypes.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var ImageIv: ImageView? = itemView.su_type_iv
var ImgId: TextView = itemView.su_type_tv
}
}
Here is the model code:-
class SU_Type_Model {
private var ImageUrl: String = ""
private var type: String = ""
constructor()
constructor(
ImageUrl: String,
type: String
) {
this.ImageUrl = ImageUrl
this.type = type
}
fun getImageUrl(): String {
return ImageUrl
}
fun setImageUrl(ImageUrl: String) {
this.ImageUrl = ImageUrl
}
fun gettype(): String {
return type
}
fun settype(type: String) {
this.type = type
}
}
here is snapshot of [database image.]
json file code is:-
{
"SU_Types": {
"asdfadsfa": {
"ImageUrl": "\"https://firebasestorage.googleapis.com/v0/b/ehi-10.appspot.com/o/Types%2FAdvertising%2F1113-lalbaugcha-raja-wallpaper-07.jpg?alt=media&token=c2d78337-e66b-43cf-bed5-8e65cf94c342\"",
"type": "\"sing\""
}
}
}
I was able to get the data in activity using similar code but I am unable to get the data in Fragment. Can someone please help me?
Instead of activity use context:-
recyclerView?.layoutManager = GridLayoutManager(context, 2)
typesAdapter = context?.let { SU_Types_adapter(it, type as ArrayList<SU_Type_Model>, true) }
and make changes for getting recyclerview:-
recyclerView = view.findViewById(R.id.rv_home_fragment)

FireBase and LiveData the text on in the cardviews don't appear and the content doesn't update (I can see the cards but there is no content)

I use Firebase Realtime Database. I have RecycleViewAdapter class, a Fragment which shows the recycleview, a ViewHolder class which gives data to the fragment (I use LiveData) and there is a Repository class which communicates with the firebase database.
class Post(
var title: String = "",
var dateStr: String = "",
var desc: String = "",
var id: String = "")
class PostsFireBaseRepository(val bucketListViewModel: BucketListViewModel) {
private val path: String = "posts"
init {
initPostsListener()
}
fun getAllPosts() {
var data = mutableListOf<Post>()
FirebaseDatabase.getInstance().reference
.child(FirebaseAuth.getInstance().currentUser?.uid.toString())
.child(path)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val newPost = dataSnapshot.getValue<Post>(Post::class.java)
if (newPost != null) {
data.add(newPost)
}
}
bucketListViewModel.allPosts.value = data
bucketListViewModel.dataChanged()
}
override fun onCancelled(error: DatabaseError) {
}
})
}
class BucketListViewModel() : ViewModel() {
private val repository: PostsFireBaseRepository
var recyclerViewAdapter: BucketListRecyclerViewAdapter? = null
var allPosts: MutableLiveData<MutableList<Post>> = MutableLiveData<MutableList<Post>>()
init {
repository = PostsFireBaseRepository(this)
repository.getAllPosts()
}
fun dataChanged() {
recyclerViewAdapter?.notifyDataSetChanged()
}
}
class BucketListFragment : Fragment(), DatePickerDialogFragment.OnDateSelectedListener,
BucketListRecyclerViewAdapter.PostItemClickListener {
private lateinit var bucketListViewModel: BucketListViewModel
private lateinit var recyclerViewAdapter: BucketListRecyclerViewAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_bucketlist, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
bucketListViewModel = ViewModelProvider(requireActivity()).get(BucketListViewModel::class.java)
bucketListViewModel.allPosts.observe(viewLifecycleOwner) { posts ->
recyclerViewAdapter.addAll(posts)
}
}
BucketListRecyclerViewAdapter
class BucketListRecyclerViewAdapter() : RecyclerView.Adapter<BucketListRecyclerViewAdapter.ViewHolder>() {
interface PostItemClickListener {
fun onItemLongClick(position: Int, view: View, post: Post?): Boolean
fun onItemClick(position: Int, view: View, post: Post?): Boolean
}
private var postList = mutableListOf<Post>()
private var lastDeleted: Post? = null
private var lastDeletedPos: Int? = null
var postClickListener: PostItemClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.bucketlist_post_row, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val post = postList[holder.adapterPosition]
holder.post = post
holder.tvTitle.text = post.title
holder.tvDesc.text = post.desc
holder.tvRowDate.text = post.dateStr
}
override fun getItemCount() = postList.size
fun addItem(post: Post) {
postList.add(post)
notifyItemInserted(postList.size-1)
}
fun addAll(posts: List<Post>) {
postList.clear()
postList.addAll(posts)
notifyDataSetChanged()
}
In your onDataChange method you will need to inform that adapter that its data is changed, otherwise it won't repaint the UI element. To do this, you call notifyDataSetChanged() on the adapter after you've updated the data source for that adapter.
So something like:
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val newPost = dataSnapshot.getValue<Post>(Post::class.java)
if (newPost != null) {
data.add(newPost)
}
}
bucketListViewModel.allPosts.value = data
adapter.notifyDataSetChanged();
}
Exactly how to reach the adapter depends on your code. For example, in your case you may have to add a method to the BucketListViewModel that you call from onDataChange and that then calls the adapter.

RecyclerView doesn`t get elements from firestore KOTLIN firebase

i want to get recyclerview in my homefragment end set into elements from firestore firebase
my problem with get elements from firestore! maybe whos know how to search a problem because elements doesnt come frome firestore!
HomeFragment
class HomeFragment : Fragment() {
private val TAG = "HomeFragment"
private val firebaseRepository: FirebaseNoteRepo = FirebaseNoteRepo()
private var noteList: List<NotesModel> = ArrayList()
private val notesListAdapter: NotesListAdapterClass = NotesListAdapterClass(noteList)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init(view)
}
private fun init(view: View) {
if(firebaseRepository.getUser() == null){
Log.d(TAG,"Error log user")
}else{ loadNotesData()}
note_list_recycler_view.layoutManager = LinearLayoutManager(context)
note_list_recycler_view.adapter = notesListAdapter
add_note_fab.setOnClickListener {
noteCreateDialog(view)
}
}
private fun loadNotesData() {
firebaseRepository.getNoteList().addOnCompleteListener {
if (it.isSuccessful){
noteList = it.result!!.toObjects(NotesModel::class.java)
notesListAdapter.notesListItem = noteList
notesListAdapter.notifyDataSetChanged()
}else{
Log.d(TAG,"Error: ${it.exception!!.message}")
}
}
}
my NotesModel
data class NotesModel(
val title: String = "",
val date: com.google.firebase.Timestamp? = null,
val post_type: Long = 0
)
my repository
FirebaseNoreRepo
class FirebaseNoteRepo {
private val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance()
private val firebaseFirestore: FirebaseFirestore = FirebaseFirestore.getInstance()
fun getUser(): FirebaseUser? {
return firebaseAuth.currentUser
}
fun getNoteList(): Task<QuerySnapshot> {
Log.d("HomeFragment"," ad "+ firebaseFirestore.collection("Notes").get().toString())
return firebaseFirestore
.collection("Notes")
.orderBy("title", Query.Direction.ASCENDING)
.get()
}
and my adapter
class NotesListAdapterClass (var notesListItem: List<NotesModel>):
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.note_layout,parent,false)
return ViewHolderNotes(view)
}
override fun getItemViewType(position: Int): Int {
return if (notesListItem[position].post_type == 1L){
POST_TYPE1
}else{
POST_TYPE1
}
}
override fun getItemCount(): Int {
Log.d("HomeFragment","notesListAdapter size : "+notesListItem.size)
return notesListItem.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (getItemViewType(position) == POST_TYPE1){
(holder as ViewHolderNotes).bind(notesListItem[position])
}
}
class ViewHolderNotes(itemView: View):RecyclerView.ViewHolder(itemView){
fun bind(notesModel: NotesModel){
itemView.note_title.text = notesModel.title
}
}
}
in my adapter i have Log.d he say me size of list of item ( is always equal 0), in firestore i have 2 elements. i dont understand why in log i have 0!
Database sceenshot

My RecyclerView is not showing the Anything

I am using MVVM with Room persistence and livedata. I am fetching the data from local database and want to show in the form of list in the recyclerView and my recyclerView is not showing anything.
My adapter is like any other regular adapter
RecyclerView Code
class MyInformationAdapter : RecyclerView.Adapter<MyInformationAdapter.ViewHolder>() {
private var myList: List<PersonInformation> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val view = layoutInflater.inflate(R.layout.my_adapter_data, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int = myList.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var myDataClass: PersonInformation = myList[position]
holder.name.text = myDataClass.name
holder.fName.text = myDataClass.fatherName
holder.email.text = myDataClass.email
holder.contact.text = myDataClass.contactNo.toString()
}
fun updateTheState(myList: List<PersonInformation>){
this.myList = myList
notifyDataSetChanged()
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var name: TextView = itemView.findViewById(R.id.yourName)
var fName: TextView = itemView.findViewById(R.id.yourFatherName)
var email: TextView = itemView.findViewById(R.id.yourEmail)
var contact: TextView = itemView.findViewById(R.id.yourContact)
}
}
RecyclerView Activity Code
class FinalActivity : AppCompatActivity() {
private var myDataList : List<PersonInformation> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_final)
setAdapter()
}
private fun setAdapter() {
val adapter = MyInformationAdapter()
val layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
adapter.updateTheState(myDataList)
}
}
*Fragment as a View of MVVM *
class PersonalInformationFragment : Fragment() {
private var viewModel: PersonInformationViewModel? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_personal_information, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
btn.setOnClickListener {
viewModel = ViewModelProviders.of(this)[PersonInformationViewModel::class.java]
viewModel?.getAllData()?.observe(this, Observer {
this.setAllData(it)
})
val intent = Intent(activity, FinalActivity::class.java)
startActivity(intent)
}
}
private fun setAllData(personInformation: List<PersonInformation>) {
val setData = PersonInformation(
name.text.toString(),
fName.text.toString(),
email.text.toString(),
contact.text.toString().toInt()
)
viewModel?.setTheData(setData)
}
}

RecyclerView not showing data from firebase (Kotlin)

can anyone help me?
i try lesson online for android-firebase, but it an old one.
So the code change already. I got stuck at onBindViewHolder and onCreateViewHolder because the lesson don't have that.
class UsersAdapter(databaseQuery: DatabaseReference, var context: Context):
FirebaseRecyclerAdapter<Users, ViewHolder>(
FirebaseRecyclerOptions.Builder<Users>().setQuery(databaseQuery, Users::class.java).build()
) {
override fun onBindViewHolder(holder: ViewHolder, position: Int, model: Users) {
var userID = getRef(position).key
holder.bindView(model, context)
holder.itemView.setOnClickListener {
//todo create a popup dialog where user can do
Toast.makeText(context, "user row click $userID", Toast.LENGTH_LONG).show()
}
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
var view = LayoutInflater.from(p0.getContext())
.inflate(R.layout.friendlist_row, p0, false)
return ViewHolder(view,context)
}
}
above is my adapter for RecycleView
class ViewHolder(itemView: View, context: Context): RecyclerView.ViewHolder(itemView) {
var userNameTxt: String ? = null
var userStatusTxt: String ? = null
var userProfilePicLink: String ? = null
fun bindView(user: Users, context: Context) {
var userName = itemView.findViewById < TextView > (R.id.friendlistNameTXID)
var userStatus = itemView.findViewById < TextView > (R.id.friendlistStatusTXID)
// var userProfilePic = itemView.findViewById<CircleImageView>(R.id.friendlistImageIVID)
//set the string so we can pass in the intent
userNameTxt = user.usernickname
userStatusTxt = user.userstatus
// userProfilePicLink = user.thumb_image
userName.text = userNameTxt
userStatus.text = userStatusTxt
// Picasso.get()
// .load(userProfilePicLink)
// .placeholder(R.drawable.ic_launcher_foreground)
// .into(userProfilePic)
}
}
above is my ViewHolder for myAdapter
class UsersFragment: Fragment() {
var mUserDatabase: DatabaseReference ? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup ? ,
savedInstanceState : Bundle ?
): View ? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_user, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle ? ) {
super.onViewCreated(view, savedInstanceState)
var linearLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mUserDatabase = FirebaseDatabase.getInstance().reference.child("Users")
friendlistRVID.setHasFixedSize(true)
friendlistRVID.layoutManager = linearLayoutManager
friendlistRVID.adapter = UsersAdapter(mUserDatabase!!, context!!)
}
}
and above is the fragment that I use that has RecycleView inside it
It would't show anything and no error too. Thank you in advance
did you use itemCount in adapter?
override fun getItemCount(): Int {
return count
}

Categories

Resources