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)
Related
Fragment1 exists in MainActivity and Fragment2 exists in Fragment1.
Fragment2 contains a recycler view, and inside the recycler view there are items with a move button. When I click the go button, I want to switch to a screen other than the RcyclerView with the items currently displayed in Fragment2.
adpater
class Quality_Material_Certification(
val material_name : String,
val use_type : String,
val standard : String,
val material_num : String
)
class QualityMaterialCertificationAdapter(private val dataset:
List<Quality_Material_Certification>) :RecyclerView.Adapter<QualityMaterialCertificationAdapter.QualityMaterialCertificationViewHolder>() {
class QualityMaterialCertificationViewHolder(val binding:
ItemQualityMaterialCertificationBinding) :
RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int):
QualityMaterialCertificationViewHolder {
val view =LayoutInflater.from(viewGroup.context).inflate(R.layout.item_quality_material_certification, viewGroup, false)
return QualityMaterialCertificationViewHolder(ItemQualityMaterialCertificationBinding.bind(view))
}
override fun onBindViewHolder(viewHolder: QualityMaterialCertificationViewHolder, position: Int) {
val listposition = dataset[position]
viewHolder.binding.materialName.text= listposition.material_name
viewHolder.binding.useType.text = listposition.use_type
viewHolder.binding.standard.text = listposition.standard
viewHolder.binding.goToMoreBtn.setOnClickListener {
setDataAtFragment(Fragment2(), listposition.material_num)
}
}
override fun getItemCount() = dataset.size
private fun setDataAtFragment(fragment: Fragment, material : String)
{
val bundle = Bundle()
val transaction = binding.root.supportFragmentManager?.beginTransaction()
bundle.putString("material", material)
fragment.arguments = bundle
transaction?.replace(R.id.appro_fl, fragment)?.commit()
}
}
fragment1
private var token : String? = null
private var const_code : String? = null
private var list = arrayListOf<Quality_Material_Certification>()
class Fragment1 : Fragment() {
private lateinit var binding:
FragmentQualityManagementFirefightingMaterialsCertificationBinding
var material: GetApproMaterListDTO? = null
lateinit var data: Quality_Material_Certification
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = FragmentQualityManagementFirefightingMaterialsCertificationBinding.inflate(layoutInflater)
binding.materialRecycler.layoutManager = LinearLayoutManager(context)
binding.materialRecycler.adapter = QualityMaterialCertificationAdapter(list)
arguments?.let {
token = it.getString("token").toString()
const_code = it.getString("cons_code").toString()
}
val dto = RequestDTO( "0", "9")
retrofit.requestservice(sysCd, token.toString(), dto).enqueue(object :
Callback<GetApproMaterListDTO> {
override fun onFailure(call: Call<GetApproMaterListDTO>, t: Throwable) { Log.d("retrofit", t.toString()) }
#SuppressLint("NotifyDataSetChanged")
override fun onResponse(call: Call<GetApproMaterListDTO>, response: Response<GetApproMaterListDTO>) {
material = response.body()
list.clear()
for (i in 0 until material?.value?.list!!.size) {
val material_name = material?.value?.list?.get(i)?.material_name.toString()
val use_type = material?.value?.list?.get(i)?.use_type.toString()
val standard = material?.value?.list?.get(i)?.standard.toString()
val material_num = material?.value?.list?.get(i)?.material_num.toString()
data = Quality_Material_Certification(material_name, use_type, standard ,material_num )
list.add(data)
}
binding.materialRecycler.adapter?.notifyDataSetChanged()
}
})
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return binding.root
}
companion object {
#JvmStatic
fun newInstance(param1: String, param2: String) =
Fragment1().apply {
arguments = Bundle().apply {
}
}
}
}
modified comment opinion
apdapter
interface clicktoDetail{
fun onClickDetail(model : CertificationDTO)
}
class CertificationAdapter(
private val context: Context,
private val dataset: List<CertificationDTO>,
private val clickListener: clicktoDetail)
: RecyclerView.Adapter<QualityMaterialCertificationAdapter.ChangeHolder>() {
inner class ChangeHolder(val binding: ItemCertificationBinding) : RecyclerView.ViewHolder(binding.root){
//val btn :Button = button.findViewById(R.id.go_to_more_btn)
init{
binding.goToMoreBtn.setOnClickListener { clickListener.onClickDetail(dataset[position]) }
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ChangeHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_certification, viewGroup, false)
return ChangeHolder(ItemCertificationBinding.bind(view))
}
override fun onBindViewHolder(viewHolder: ChangeHolder, position: Int) {
val listposition = dataset[position]
viewHolder.binding.materialName.text= listposition.material_name
viewHolder.binding.useType.text = listposition.use_type
viewHolder.binding.standard.text = listposition.standard
viewHolder.binding.madeCompanyName.text = listposition.produce_co
/* viewHolder.binding.goToMoreBtn.setOnClickListener {
val intent = Intent(context, Fragment1::class.java)
intent.putExtra("cons_code", listposition.project_const)
intent.run{
context.startActivity(this)
(context as Activity).finish()
}
}*/
}
override fun getItemCount() = dataset.size
}
Fragment
private var token : String? = null
private var const_code : String? = null
private var material_list = arrayListOf<Quality_Material_CertificationDTO>()
class Certification_Fragment : Fragment() {
private lateinit var binding: FragmentQualityManagementFirefightingMaterialsCertificationBinding
var material: GetListDTO? = null
lateinit var material_data : Quality_Material_CertificationDTO
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = FragmentCertificationBinding.inflate(layoutInflater)
val retrofitApproMaterList = RetrofitC("http://")
val GetApproMaterListService: GetApproMaterListService = retrofitApproMaterList.create(GetListService::class.java)
binding.materialRecycler.layoutManager = LinearLayoutManager(context)
binding.materialRecycler.adapter = CertificationAdapter(requireContext(), material_list, GotoDetail())
arguments?.let {
token = it.getString("token").toString()
const_code = it.getString("cons_code").toString()
}
val mdto = RequestDTO("", "")
GetApproMaterListService.requestappromaterial(sysCd, token, mdto).enqueue(object :
Callback<GetListDTO> {
override fun onFailure(call: Call<GetListDTO>, t: Throwable) { Log.d("retrofit", t.toString()) }
#SuppressLint("NotifyDataSetChanged")
override fun onResponse(call: Call<GetAListDTO>, response: Response<GetListDTO>) {
material = response.body()
material_list.clear()
for (i in 0 until material?.value?.list!!.size) {
val material_name = material?.value?.list?.get(i)?.material_name.toString()
val use_type = material?.value?.list?.get(i)?.use_type.toString()
val standard = material?.value?.list?.get(i)?.standard.toString()
val produce_co = material?.value?.list?.get(i)?.produce_co.toString()
val material_num = material?.value?.list?.get(i)?.material_num.toString()
material_data = Quality_Material_CertificationDTO(material_name, use_type, standard, produce_co ,material_num)
material_list.add(material_data)
CertificationAdapter(requireContext(), material_list, GotoDetail())
}
binding.materialRecycler.adapter?.notifyDataSetChanged()
}
})
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return binding.root
}
companion object {
#JvmStatic
fun newInstance(param1: String, param2: String) =
Quality_Management_Firefighting_Materials_Certification_Fragment().apply {
arguments = Bundle().apply {
}
}
}
class GotoDetail : Fragment(), clicktoDetail{
override fun onClickDetail(model: Quality_Material_CertificationDTO) {
val bundle = Bundle()
val transaction = activity?.supportFragmentManager?.beginTransaction()
bundle.putString("cons_code", const_code)
bundle.putString("token", token)
Fragment().arguments = bundle
transaction?.replace(R.id.appro_fl, Certification_More_Fragment())!!.commit()
}
}
}
You are trying to access activities and fragments inside your adapter class which is incorrect. Never do that! Instead, create an item click listener and create a reference to it in your activity. This way you can handle item click in your activity and perform fragment transactions.
Here, You can take help on how to do so by making an onClickInterface
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
}
The error in "adapter = UserAdapter(users)" says type mismatch required: context "Change parameter Context type of primary constructor of class UserAdapter to ArrayList" I tried running it while the "adapter = UserAdapter(users)" is enclosed as a comment (like so //adapter = UserAdapter(users)) in shows an error in logcat saying "java.lang.NullPointerException: v.findViewById(R.id.RVusermain) must not be null
at com.example.chattrialskot.fragments.Year1.onCreateView(Year1.kt:49) ".
USERS.kt
class Users {
var userstuID: String? = null;
var username: String? = null;
var useremail: String? = null;
var useraccstat: String? = null;
var useruid: String? = null;
var useryear: String? = null;
constructor(){}
constructor(userstuID: String?, username: String?, useremail: String?, useraccstat: String?,
useruid: String?, useryear: String?){
this.userstuID = userstuID
this.username = username
this.useremail = useremail
this.useraccstat = useraccstat
this.useruid = useruid
this.useryear = useryear
} }
USER ADAPTER
class UserAdapter(var UAContext: Context, var userlist: ArrayList<Users>):
RecyclerView.Adapter<UserAdapter.UsersViewHolder> (){
fun UserAdapter(userlist: ArrayList<Users>, mContext: Context){
this.userlist = userlist
this.UAContext = mContext
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UsersViewHolder {
val view:View = LayoutInflater.from(UAContext).inflate(
R.layout.userlayout, parent,
false)
return UserAdapter.UsersViewHolder(view)
}
FRAGMENT
class Year1 : Fragment() {
companion object {
fun newInstance(): Year1 {
return Year1()
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_year1, container, false)
userrecyclerviewer = v.findViewById<RecyclerView>(R.id.RVyear1)
userrecyclerviewer.setHasFixedSize(true)
userrecyclerviewer.layoutManager = LinearLayoutManager(context)
userrecyclerviewer.adapter = adapter
users = ArrayList()
adapter = UserAdapter(users)
getUsers()
return v
}
private fun getUsers(){
FireAuth = FirebaseAuth.getInstance()
FireDB = FirebaseDatabase.getInstance().getReference()
FireDB.child("users").addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
users.clear()
for(postSnapshot in snapshot.children){
val userfrmDB = postSnapshot.getValue(Users::class.java)
if(FireAuth.currentUser?.uid != userfrmDB?.useruid
&& userfrmDB?.useraccstat != "Banned")
{
users.add(userfrmDB!!)
}
}
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
}
})
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}}
class Year1 : Fragment() {
companion object {
fun newInstance(): Year1 {
return Year1()
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_year1, container, false)
userrecyclerviewer = v.findViewById<RecyclerView>(R.id.RVusermain)
userrecyclerviewer.setHasFixedSize(true)
getUsers()
users = ArrayList()
userrecyclerviewer.layoutManager = LinearLayoutManager(context)
adapter = UserAdapter(context?, users)
userrecyclerviewer.adapter = adapter
return v
}
private fun getUsers(){
FireAuth = FirebaseAuth.getInstance()
FireDB = FirebaseDatabase.getInstance().getReference()
FireDB.child("users").addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
users.clear()
for(postSnapshot in snapshot.children){
val userfrmDB = postSnapshot.getValue(Users::class.java)
if(FireAuth.currentUser?.uid != userfrmDB?.useruid
&& userfrmDB?.useraccstat != "Banned")
{
users.add(userfrmDB!!)
}
}
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
}
})
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}}
You were getting Nullpointer exception because you were setting adapter even it has been initialized. Please, follow the code above.
call getUsers() this method in main thread before you pass the list to adapter because you list should not be null. Then pass the context and list to adapter like this
users = ArrayList()
getUsers()
adapter = UserAdapter(requireContext(),users)
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.
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