VladMorzhanov
9/23/2017 - 2:43 PM

Android ble device list adapter example.

Android ble device list adapter example.

    // Adapter for holding devices found through scanning.
    private class LeDeviceListAdapter extends BaseAdapter {
        private ArrayList<BluetoothDevice> mLeDevices;
        private LayoutInflater mInflator;

        LeDeviceListAdapter() {
            super();
            mLeDevices = new ArrayList<>();
            mInflator = ScanActivity.this.getLayoutInflater();
        }

        void addDevice(BluetoothDevice device) {
            if (!mLeDevices.contains(device)) {

                if (device.getName() != null)
                    if (!device.getName().equals("")) {
                        String name = device.getName();

//                        if (name.toLowerCase().contains("mevics"))
                        mLeDevices.add(device);
                    }
            }
        }

        BluetoothDevice getDevice(int position) {
            return mLeDevices.get(position);
        }

        void clear() {
            mLeDevices.clear();
        }

        @Override
        public int getCount() {
            return mLeDevices.size();
        }

        @Override
        public Object getItem(int i) {
            return mLeDevices.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            // General ListView optimization code.
            if (view == null) {
                view = mInflator.inflate(R.layout.device_scan_list_item, null);
                viewHolder = new ViewHolder();
                viewHolder.tvScanItemAddress = view.findViewById(R.id.tvScanItemMac);
                viewHolder.tvScanItemName = view.findViewById(R.id.tvScanItemName);
                viewHolder.rbScanItemButton = view.findViewById(R.id.rbScanItem);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            BluetoothDevice device = mLeDevices.get(i);
            final String deviceName = device.getName();
            if (deviceName != null && deviceName.length() > 0) {
                viewHolder.tvScanItemName.setText(deviceName.trim());
            } else
                viewHolder.tvScanItemName.setText(R.string.un_device);
            viewHolder.tvScanItemAddress.setText(device.getAddress());

            return view;
        }
    }