Дубликаты в RecyclerView - SortedList - PullRequest
0 голосов
/ 28 ноября 2018

Я борюсь с дубликатами в моем адаптере вида переработчика.Это сценарий: у меня есть приложение, которое сканирует устройства BLE и обновляет список с именем устройства, адресом и RSSI устройства.Список должен быть упорядочен по значению RSSI (DESC).Я реализовал SortedListAdapterCallback в своем адаптере и упорядочил его, однако адаптер дублирует устройство в списке каждый раз, когда получено обновление для существующего устройства (например, изменилось устройство rssi).Это мой адаптер:

class SortedDeviceAdapter(private val mContext: Context,
                          private val mClickListener: DeviceItemClickListener) : RecyclerView.Adapter<SortedDeviceAdapter.ViewHolder>() {

    private val mDevices: SortedList<BLEDeviceWithRssi>

    init {
        mDevices = SortedList(BLEDeviceWithRssi::class.java, object : SortedListAdapterCallback<BLEDeviceWithRssi>(this) {
            override fun compare(o1: BLEDeviceWithRssi, o2: BLEDeviceWithRssi): Int = o2.rssi - o1.rssi

            override fun areContentsTheSame(oldItem: BLEDeviceWithRssi, newItem: BLEDeviceWithRssi): Boolean = oldItem.device.name == newItem.device.name

            override fun areItemsTheSame(item1: BLEDeviceWithRssi, item2: BLEDeviceWithRssi): Boolean = item1.device.address == item2.device.address
        })
    }

    // Create new views (invoked by the layout manager)
    override fun onCreateViewHolder(parent: ViewGroup,
                                    viewType: Int): ViewHolder {
        // create a new view
        val v = LayoutInflater.from(mContext)
                .inflate(R.layout.item_device, parent, false)
        // set the view's size, margins, paddings and layout parameters
        return ViewHolder(v)
    }

    // Replace the contents of a view (invoked by the layout manager)
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        val currentDevice = mDevices.get(position)
        holder.tvDeviceName.text = currentDevice.device.name
        holder.tvDeviceAddress.text = currentDevice.device.address
        holder.tvRssi.text = mContext.getString(R.string.rssi, currentDevice.rssi)
        val bondState = currentDevice.device.bondState
        when (bondState) {
            BluetoothDevice.BOND_BONDED -> holder.ivBondStatus.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_bonded))
            BluetoothDevice.BOND_NONE -> holder.ivBondStatus.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_ble))
        }
        holder.btConnect.setOnClickListener { mClickListener.onConnectButtonClicked(currentDevice) }
    }

    fun addDevice(device: BLEDeviceWithRssi) {

        mDevices.add(device)
    }

    // Return the size of your dataset (invoked by the layout manager)
    override fun getItemCount(): Int {
        return mDevices.size()
    }

    fun clearList() {
        mDevices.clear()
    }


    interface DeviceItemClickListener {
        fun onConnectButtonClicked(device: BLEDeviceWithRssi)
    }

    class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
        // each data item is just a string in this case
        internal var tvDeviceName: TextView
        internal var tvDeviceAddress: TextView
        internal var tvRssi: TextView
        internal var btConnect: Button
        internal var ivBondStatus: ImageView


        init {
            ivBondStatus = v.findViewById(R.id.ivBondStatus)
            tvDeviceName = v.findViewById(R.id.tvDeviceName)
            tvDeviceAddress = v.findViewById(R.id.tvDeviceAddress)
            tvRssi = v.findViewById(R.id.tvRssi)
            btConnect = v.findViewById(R.id.btConnect)
        }
    }

    companion object {
        private val TAG = SortedDeviceAdapter::class.java.simpleName
    }
}

Каждый раз, когда моя служба Bluetooth обнаруживает устройство, я вызываю функцию addDevice в моем адаптере с целью добавления / обновления устройства в списке.К сожалению, если устройство существует в списке, добавляется дубликат.Что я делаю неправильно?Спасибо

...