0

I have list (mListCache). Which I am filling with Firebase. How do I iterate through all the sheets in mListCache and leave only those with name: B.

My adapter:

package ua.lujek.expiration_date.ui.fragment.Adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.expation_item.view.*
import ua.lujek.expiration_date.R
import ua.lujek.expiration_date.models.ExpationModel
import ua.lujek.expiration_date.utilits.daysString

class ExpationAdatper : RecyclerView.Adapter<ExpationAdatper.ExpationHolder>() {

    private var mListCache = emptyList<ExpationModel>()
    private var mListSort = emptyList<ExpationModel>()

    class ExpationHolder(view: View) : RecyclerView.ViewHolder(view) {
        val name: TextView = view.expation_name
        val volume: TextView = view.expation_volume
        val count: TextView = view.count
        val data_end: TextView = view.dataend
        val lastday: TextView = view.lastday
        val market: TextView = view.expation_market
        val market_adress: TextView = view.expation_adress
        val lastday_text: TextView = view.lastday_text
        val count_text: TextView = view.count_text
        val data_text: TextView = view.Date_text
        val tt_text: TextView = view.expation_tt
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExpationHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.expation_item, parent, false)
        return ExpationHolder(view)
    }

    override fun getItemCount(): Int = mListCache.size

    override fun onBindViewHolder(holder: ExpationHolder, position: Int)
    {
        holder.name.text = mListCache[position].name
        holder.volume.text = mListCache[position].bottlevolume
        holder.count.text = mListCache[position].count
        holder.data_end.text = mListCache[position].dataend
        holder.lastday.text = daysString(mListCache[position].dataend)
        holder.market.text = mListCache[position].market
        holder.market_adress.text = mListCache[position].marketadress
        holder.data_text.text = mListCache[position].data_text
        holder.lastday_text.text = "Осталось дней:"
        holder.count_text.text = "Количество:"
        holder.tt_text.text = "Торговая точка:"
        Glide.with(holder.itemView.context)
            .load(mListCache[position].photo_Url)
            .error(R.drawable.ic_item_photo)
            .placeholder(R.drawable.ic_item_photo)
            .into(holder.itemView.photo_item)
    }

    fun setList(list: List<ExpationModel>) {
            mListCache = list
            notifyDataSetChanged()
    }
}

My Fragment:

package ua.lujek.expiration_date.ui.fragment

import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.DatabaseReference
import kotlinx.android.synthetic.main.fragment_main.*
import ua.lujek.expiration_date.DB.*
import ua.lujek.expiration_date.R
import ua.lujek.expiration_date.models.ExpationModel
import ua.lujek.expiration_date.ui.fragment.Adapter.ExpationAdatper
import ua.lujek.expiration_date.utilits.*


class MainFragment : BaseFragment(R.layout.fragment_main) {

    private lateinit var mRecycleView:RecyclerView
    private lateinit var mRefExpation: DatabaseReference
    private lateinit var mAdapter:ExpationAdatper
    private lateinit var mExpationListener: AppValueEventListener
    private var mListExpation = emptyList<ExpationModel>()
    private val merchName: MutableList<String> = ArrayList()
    private val nameAdapter = ArrayAdapter<String>(APP_ACTIVITY, android.R.layout.simple_spinner_item, merchName)


    override fun onResume() {
        super.onResume()
        APP_ACTIVITY.title = "Товары"
        AddButtonNewProduct.setOnClickListener {
            APP_ACTIVITY.supportFragmentManager.beginTransaction()
                .replace(R.id.Fragment_container, NewProductFragment()).commit()
        }
        DownloadName()
        initRecycleView()
    }

    fun DownloadName() {
        REF_DATABASE_ROOT.child(NODE_EXPATION).child(USER.company).child(USER.region)
            .addValueEventListener(AppValueEventListener {
                for (nameSnapshot in it.children) {
                    val areaName = nameSnapshot.child("merchName").getValue(String::class.java)!!
                    merchName.add(areaName)
                    val set: Set<String> = HashSet(merchName)
                    merchName.clear()
                    merchName.addAll(set)
                }
                merchName.add(0, "Все мерчендайзеры")
                nameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item)
                etmerchName.adapter = nameAdapter
            })

        etmerchName.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) { }
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View, position: Int, l: Long) {
                REQUEST_SPINNER = etmerchName.getItemAtPosition(position).toString()
            }
        }
    }
    private fun initRecycleView() {
        mRecycleView = expation_recycle_view
        mAdapter = ExpationAdatper()
        mRefExpation = REF_DATABASE_ROOT.child(NODE_EXPATION).child(USER.company).child(USER.region)
        mRecycleView.adapter = mAdapter
        mExpationListener = AppValueEventListener { dataSnapshot ->
            mListExpation = dataSnapshot.children.map { it.getExpationModel() }
            mAdapter.setList(mListExpation)
        }
        mRefExpation.addValueEventListener(mExpationListener)
    }
    override fun onPause() {
        super.onPause()
        mRefExpation.removeEventListener(mExpationListener)
    }
}

Please help me. If instead of sorting the sheets, you suggest a different approach for displaying specific items in the RecyclerView. I will be very happy about that.

1
  • You can't modify mListCache, because it's a List, and not necessarily a MutableList. If it were, you could just call removeAll(). Commented Aug 6, 2020 at 21:57

2 Answers 2

2

How do I iterate through all the sheets in mListCache and leave only those with name: B.

The direct answer would be to filter the values inside the setList method

fun setList(list: List<ExpationModel>) {
    mListCache = list.filter { it.name == "B" } 
    notifyDataSetChanged()
}

Other solution would be to retrieve specific data from the database instead of getting all and then filtering.

Sign up to request clarification or add additional context in comments.

2 Comments

I need to get everything. Since I have a spinner in which the user chooses to display everything or only with the name B
When I use: mListCache = list.filter{ it.merchName.startsWith(REQUEST_SPINNER)} println(mListSort) notifyDataSetChanged() I get a blank sheet
1

What you ask for is "filter" not "sort".

Filtering is quite easy in Kotlin.

val newlist = list.filter{ it.name.startsWith("B") }

Sorting is also quite easy:

val newList = list.sortedBy{ it.name }

Both methods return a new list, the old list is not modified. The more tricky part is where to call the filter method. I'm not sure about that, I would try it here:

fun setList(list: List<ExpationModel>) {
        mListCache = list.filter{ it.name.startsWith("B") }
        notifyDataSetChanged()
}

.

3 Comments

Thank you so much. I'll try to do it in a couple of hours. But how can I force the adapter to load a new list later when the desired item is selected in the spinner?
When I use: mListCache = list.filter{ it.merchName.startsWith(REQUEST_SPINNER)} println(mListSort) notifyDataSetChanged() I get a blank sheet. I need to remove unwanted positions in RecycleView when I switch Spinner
Sorry it works. I'm a fool)). Forgot to update RecycleView after selection in spinner

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.