'RecyclerView sorting process and getting position issue

I have an activity that shows model comes from Firebase in a recyclerView. Each row has a delete button and user can delete which row he/she wants.

The problem is that My recyclerView is getting wrong position. For example: if I have two rows named A and B. First, I added A and then added B.Firebase sorting them by time .Therefore recyclerView shows them like that:

  • B
  • A

But, if I click row B's delete button and log the position it logs row A's position. So, I can't delete the row which I want.

ViewModel:

class PairVM(application: Application) : AndroidViewModel(application) {

val list = MutableLiveData<ArrayList<AnalyzeDTO>>()
private val database = FirebaseFirestore.getInstance()
private val ozelSharedPreferences = OzelSharedPreferences(getApplication())
private val chosenPair = ozelSharedPreferences.clickiAl().toString()
private val currentU = Firebase.auth.currentUser
private val dbCollection = currentU?.let { it.email.toString() }
private val collectionRef = database.collection(dbCollection!!)
    .document("Specified")
    .collection("Pairs")
    .document(chosenPair)
    .collection("Analysis")

fun retrieveData() {

    val docRef = collectionRef.orderBy("tarih", Query.Direction.DESCENDING)

    docRef.addSnapshotListener { value, error ->
        try {
            if (value != null && !value.isEmpty) {

                val documents = value.documents
                for (document in documents) {

                    val url = document.get("tradingViewUrl") as String?
                    val rr = document.get("rrRatio") as Double?
                    val reason = document.get("reason") as String?
                    val result = document.get("result") as String?
                    val concept = document.get("concept") as String?
                    val tarih = document.get("tarih") as Timestamp

                    val downloadedAnalyze = AnalyzeDTO(url, rr, reason, result, concept, tarih)
                    val analyzeList = arrayListOf(downloadedAnalyze)
                    list.value = analyzeList
                }
            } else if (error != null) {
                Toast.makeText(getApplication(), error.localizedMessage, Toast.LENGTH_LONG)
                    .show()
            } /*else {
                Toast.makeText(getApplication(), "Burada hiç analiz yok.", Toast.LENGTH_SHORT).show()
            }*/
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

fun deleteData(position: Int) {
    collectionRef.get().addOnSuccessListener { result ->
        val newList = ArrayList<String>()
        if (result != null) {
            for (document in result) {
                newList.add(document.id)
                collectionRef.document(newList[position]).delete()
            }
        }
    }
}}

Adapter:

class PairDetailRecyclerAdapter(
private val list: ArrayList<AnalyzeDTO>,
private val listener: Listener) : RecyclerView.Adapter<PairDetailRecyclerAdapter.AnalyzeViewHolder>() {

interface Listener {
    fun deleteOnClick(newlist: ArrayList<AnalyzeDTO>, position: Int)
}

class AnalyzeViewHolder(itemview: View) : RecyclerView.ViewHolder(itemview) {
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AnalyzeViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val view = inflater.inflate(R.layout.pair_detail_row, parent, false)

    return AnalyzeViewHolder(view)
}

override fun onBindViewHolder(holder: AnalyzeViewHolder, position: Int) {

    holder.itemView.rrRatioText.text = "RR Oranı: ${list[position].rrRatio}"
    holder.itemView.resultText.text = "Sonuç: ${list[position].result}"
    holder.itemView.causeForEntryText.text = "Sebep: ${list[position].reason}"
    holder.itemView.conceptText2.text = "Concept: ${list[position].concept}"
    if (list[position].tradingViewUrl != null && list[position].tradingViewUrl!!.isNotEmpty()) {
        Picasso.get().load(list[position].tradingViewUrl)
            .into(holder.itemView.tradingviewImage);
    }
    holder.itemView.imageView.setOnClickListener {
        listener.deleteOnClick(list, holder.layoutPosition)
        //println(list[position].rrRatio)
    }
}

override fun getItemCount(): Int {
    return list.size

}

fun updateAnalyzeList(newAnalyzeList: List<AnalyzeDTO>) {
    list.addAll(newAnalyzeList)
    notifyDataSetChanged()
}}

Activity:

class PairDetailActivity : AppCompatActivity(), PairDetailRecyclerAdapter.Listener {

private lateinit var auth: FirebaseAuth
private lateinit var database: FirebaseFirestore
private var recyclerA = PairDetailRecyclerAdapter(arrayListOf(), this)
private lateinit var viewModel: PairVM
private var sharedPreferences = OzelSharedPreferences()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_pair_detail)

    auth = FirebaseAuth.getInstance()
    database = FirebaseFirestore.getInstance()

    viewModel = ViewModelProvider(this).get(PairVM::class.java)
    viewModel.retrieveData()


    pair_detail_recyclerView.layoutManager = LinearLayoutManager(this)
    pair_detail_recyclerView.adapter = recyclerA

    pairDetailPairHeader.text = sharedPreferences.clickiAl()

    observeLiveData()

}

fun observeLiveData() {
    viewModel.list.observe(this, Observer { myList ->
        myList?.let {
            recyclerA.updateAnalyzeList(it)
        }
    })
}

fun addButton1(v: View) {
    val intent = Intent(this, AddAnalyzeActivity::class.java)
    startActivity(intent)
    finish()
}

override fun deleteOnClick(newlist: ArrayList<AnalyzeDTO>, position: Int) {
    viewModel.deleteData(position)
    newlist.removeAt(position)
    recyclerA.notifyDataSetChanged()

}}

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source