Túlio Rossi
Túlio Rossi

Reputation: 60

How to get a list after each discovered device?

I'm using this function to scan BLE devices and save then into a list.

    public BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
        act.runOnUiThread(new Runnable() {

            public void run() {
                if(aDevices.size() > 0) {

                    boolean isNewItem = true;

                    for (int i = 0; i < aDevices.size(); i++) {
                        if (aDevices.get(i).getMacAddress().equals(device.getAddress())) {
                            isNewItem = false;
                        }
                    }
                    if(isNewItem) {
                        aDevices.add(new BluetoothLE(device.getName(), device.getAddress(), rssi, device));
                    }
                }else{
                    aDevices.add(new BluetoothLE(device.getName(), device.getAddress(), rssi, device));
                }
                
            }
        });

    }
    
};

And using this function to get a a list:

        public ArrayList<BluetoothLE> getListDevices(){
    return aDevices;
}

But, I want to get the list after each aDevices.add() inside the thread. What should I do?

Upvotes: 1

Views: 62

Answers (1)

Francesco Bocci
Francesco Bocci

Reputation: 867

You could use an instance of ObservableArrayList and provide it with an implementation of OnListChangedCallback that is notified on each change instead of the ArrayList you are currently using.

public class MyCallback extends ObservableList.OnListChangedCallback<ObservableList> {

public void onChanged(ObservableList sender) {
    Log.i(tag, "list changed");
}

public void onItemRangeChanged(ObservableList sender, int positionStart, int itemCount) {
    Log.i(tag, "item range changed");
}

public void onItemRangeInserted(ObservableList sender, int positionStart, int itemCount) {
    Log.i(tag, "item range inserted");
}

public void onItemRangeMoved(ObservableList sender, int fromPosition, int toPosition, int itemCount)  {
    Log.i(tag, "item range moved");
}

public void onItemRangeRemoved(ObservableList sender, int positionStart, int itemCount)  {
    Log.i(tag, "item range removed");
}
}


ObservableArrayList list = new ObservableArrayList();
list.addOnListChangedCallback(new MyCallback());
...
list.add(element);

Upvotes: 1

Related Questions