Search code examples
kotlinsortingfirebase-realtime-databaseandroid-recyclerviewandroid-mvvm

How to sort recyclerview data fetched from firebase by value in mvvm architecture


I am trying to sort datas which are fetched from firebase realtime database according to the value of a child using MVVM architecture the daabase reference is created in a repository

GroupNoticeRepository

class GroupNoticeRepository(private var groupSelected: String) {
    val auth = Firebase.auth
    val user = auth.currentUser!!.uid

    private val scheduleReference: DatabaseReference =
        FirebaseDatabase.getInstance().getReference("group-notice").child(groupSelected)

    @Volatile
    private var INSTANCE: GroupNoticeRepository? = null
    fun getInstance(): GroupNoticeRepository {
        return INSTANCE ?: synchronized(this) {

            val instance = GroupNoticeRepository(groupSelected)
            INSTANCE = instance
            instance
        }
    }

    fun loadSchedules(allSchedules: MutableLiveData<List<GroupNoticeData>>) {

        scheduleReference.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {

                try {

                    val scheduleList: List<GroupNoticeData> =
                        snapshot.children.map { dataSnapshot ->

                            dataSnapshot.getValue(GroupNoticeData::class.java)!!

                        }
                    allSchedules.postValue(scheduleList)

                } catch (_: Exception) {

                }

            }

            override fun onCancelled(error: DatabaseError) {

            }


        })
    }
}

GroupNoticeFragment

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    recycler = binding.taskList
    recycler.layoutManager = LinearLayoutManager(context)
    recycler.setHasFixedSize(true)
    adapter = GroupNoticeAdapter(_inflater)
    recycler.adapter = adapter
    viewModel = ViewModelProvider(this)[GroupNoticeViewModel::class.java]

    viewModel.initialize(groupId)

    viewModel.allSchedules.observe(viewLifecycleOwner) {
        adapter!!.updateUserList(it)
    }

}

GroupNoticeViewModel


class GroupNoticeViewModel : ViewModel() {

    private lateinit var repository: GroupNoticeRepository
    private val _allSchedules = MutableLiveData<List<GroupNoticeData>>()
    val allSchedules: LiveData<List<GroupNoticeData>> = _allSchedules

    fun initialize(groupSelected: String) {
        repository = GroupNoticeRepository(groupSelected).getInstance()
        repository.loadSchedules(_allSchedules)
    }
}

`enter image description here

As you can see the current structure group-notice -groupId(groups) -noticeId (notices) - taskDate

Here under group notice there are some groups and in each group there are some notices(noticeId) . Each notice has a task date . Now I am trying to sort the notices according to the taskdate meaning the taskDate which will is closer to todays date will view first in the recycler view. Or the notice with latest taskdate given will appear first in the recycler view .


Solution

  • Just as hassan bazai said I followed the same concept of comparing two dates

    class FirebaseDataComparator : Comparator<GroupNoticeData?> {
        override fun compare(p0: GroupNoticeData?, p1: GroupNoticeData?): Int {
    
            val dateFormat = SimpleDateFormat("dd/MM/yyyy")
    
            val firstDate: Date = dateFormat.parse(p0?.taskdate!!) as Date
            val secondDate: Date = dateFormat.parse(p1?.taskdate!!) as Date
    
            return firstDate.compareTo(secondDate)
        }
    }
    

    Here groupNoticeData is the data class I am using to populate the data in my recycler View and took two objects of them . Parsed their date format accordingly and later on compared them. And in the recyclerViewAdapter before adding my data, I sorted them using the comparator class and added them later on. Here is the part where I had to use the comparator class.

    fun updateNoticeList(notices: List<GroupNoticeData>) {
            Collections.sort(notices, FirebaseDataComparator())
            this.tasks.clear()
            this.tasks.addAll(notices)
    
            notifyDataSetChanged()
    
        }