1

I'm making a program that will look for paired with phone Bluetooth devices, show them and their address bfor user to see, and it's working fine when user has already turned on Bt in his phone. Problem appears when he doesn't, cause data added into arrayList duplicates. I used a while loop so it only checks for paired devices after Bt module is turned on, is it a good way to make such thing at onResume()?

Flyentology
  • 121
  • 10

2 Answers2

1

A quick fix would be to check if the String is already present in your data source list. Something like this

 for (BluetoothDevice device: pairedDevice) {
     String name = device.getName();
     String address = device.getAddress();
     String toBeAdded = address + " " + name;
     if (!QueryDevices_final.contains(toBeAdded) {
             QueryDevices_final.add(toBeAdded);
             arrayAdapter.notifyDataSetChanged();
         }
     }
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

Can´t you put your checkBluetoothState() inside the onCreate method? And depending on the result call the array creation stuff?

Depending on how your app is developed, onResume can be called more than once. To avoid it, you can:

  • create a shared preference/flag and call it only once (firstRun=true and update it to false when it runs once) and then make the array creation and update depend on that flag,

  • create a public variable inside that class and run the code only if it´s the first time. Change the variable in the end.

  • change the way your activity is implemented in order for onResume to run only once.

You can also check this answer and try to understand where is your app calling onResume twice: Why is my onResume being called twice?

Curious Mind
  • 659
  • 10
  • 26