title: Update nearby unpaired bluetooth devices list in listview [Android Studio]
body: <p>Note: I am completely new to android studio (java) and this is my very first project. </p>
  
  <p>I am trying to scan all (paired and unpaired) bluetooth devices and display a list of these devices on application screen. </p>
  
  <p>I have been successful in getting a list so far but following issues persist:</p>
  
  <p>1) As new unpaired devices are scanned, earlier scanned devices are repeated in the display list as duplicates. </p>
  
  <p>2) If I turn off discover-ability in a device, the list is not updated and keeps showing the turned off (no longer available) device in the list.</p>
  
  <p><strong>Problem: Bluetooth device list is not updated correctly every time a device becomes available or unavailable.</strong> </p>
  
  <p>I have tried clearing my array list before it is updated. Doesn't seem to work. Also, I understand there are a lot of resources on stackoverflow and other websites that cover similar topics of getting nearby bluetooth device list. I have followed multiple of them and written my code but could not come across anything that could solve this "list update" issue. </p>
  
  <p>I am sharing current code and results. Please suggest edits/additions.</p>
  
  <p>Appreciate your time and help. </p>
  
  <p><strong><em>Main Activity Class Code</em></strong></p>
  
  <pre><code>
  public class MainActivity extends AppCompatActivity {
  
      private static final int REQUEST_ENABLE_BT = 1;                         //Enable bluetooth request variable
      private static final int REQUEST_DISCOVERABILITY = 1 ;                  //Make bluetooth discoverable request variable
  
      private BluetoothAdapter btAdapter;                                     //Define bluetooth adapter variable
  
      ArrayList&lt;String&gt; deviceList = new ArrayList&lt;&gt;();                       //Store paired devices list
      ArrayList&lt;String&gt; newDevices = new ArrayList&lt;&gt;();                       //Store available devices list
      ArrayList&lt;String&gt; allDevices = new ArrayList&lt;&gt;();                       //Store all devices for display on screen
  
      ListView btList;                                                        //Define list UI item
  
  
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {                    //On activity creation do the following
  
  
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);                             //Pre-written -- to set layout as screen UI
  
  
          btList = (ListView)findViewById(R.id.list1);                        //Set list variable to UI item in layout
  
  
          btAdapter = BluetoothAdapter.getDefaultAdapter();                   //Initialize adapter
  
  
          if(allDevices != null){
  
              allDevices.clear();                                             //Clear array to display fresh list
          }
  
  
  
          int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
          ActivityCompat.requestPermissions(this,
                  new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},   //Ask for permission to turn on location
                  MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
  
  
  
      }
  
  
  
      public void btOn(View view){                                           //Bluetooth On event
  
          if (btAdapter != null) {
  
              if (!btAdapter.isEnabled()) {                                  //Enable bluetooth if not enables already
                  Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                  startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
              }
              else{                                                          //If already enabled display list of paired devices
  
                  pairedList();
  
              }
          }
  
      }
  
  
  
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  
          if (requestCode == REQUEST_ENABLE_BT) {
  
              if (resultCode == RESULT_OK) {
  
                  pairedList();                                              //If user has enabled bluetooth, show list of paired devices
  
              }
  
          }
      }
  
  
      public void discoverOn(){                                              //Method for setting bluetooth on discoverable mode
                                                                             //for 5 minutes
          Intent discoverableIntent =
                  new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
          discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
          startActivityForResult(discoverableIntent, REQUEST_DISCOVERABILITY);
  
  
      }
  
  
  
  
      public void scanNewDevices(View view){                                  //Scan for unpaired available bluetooth devices when "scan button" is clicked
  
          discoverOn();                                                       //Set bluetooth to discoverable
  
          if (btAdapter.isDiscovering()) {
                                                                              //Bluetooth is already in mode discovery mode, we cancel to restart it again
              btAdapter.cancelDiscovery();
          }
          btAdapter.startDiscovery();                                         //Start scanning
  
          IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  
          registerReceiver(receiver, filter);
  
  
      }
  
  
  
  
  
  
      public void pairedList(){                                                //Method gets list of paired devices
  
          Set&lt;BluetoothDevice&gt; pairedDevices = btAdapter.getBondedDevices();
  
          if (deviceList != null) {                                            //Clear older list items
              deviceList.clear();
          }
  
          if(pairedDevices != null) {
              for (BluetoothDevice bt : pairedDevices) {
  
                  deviceList.add(bt.getName() + '\n' + bt.getAddress());      //Add current items
              }
          }
  
  
          Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
  
          allDevices.addAll(deviceList);                                      //Update final display list
  
          showList();                                                         //Display list on screen
  
      }
  
  
                                                                              //Create a BroadcastReceiver for ACTION_FOUND.
      private final BroadcastReceiver receiver = new BroadcastReceiver() {
          public void onReceive(Context context, Intent intent) {
              String action = intent.getAction();
              if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                                                                              //Discovery has found a device. Get the BluetoothDevice
                                                                              //object and its info from the Intent.
                  BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  
  
  
                  if(newDevices != null){
  
                      newDevices.clear();                                     //Clear earlier list
  
                  }
  
  
                  if (device != null ) {
  
                      newDevices.add(device.getName() + '\n' + device.getAddress());
  
                      allDevices.addAll(newDevices);                          //Update new devices in final display list
  
                      showList();                                             //Display list
                  }
  
              }
          }
      };
  
      @Override
      protected void onDestroy() {                                           //When application is closed,
          super.onDestroy();
                                                                             //Unregister the ACTION_FOUND receiver.
          unregisterReceiver(receiver);
      }
  
  
  
      public void showList(){                                                 //Method to set device list to ListView UI
  
          final ArrayAdapter&lt;String&gt; adapter = new  ArrayAdapter&lt;&gt;(this,android.R.layout.simple_list_item_1, allDevices);
  
          btList.setAdapter(adapter);
  
      }
  
  }
  
  
  </code></pre>
  
  <p><strong><em>activity_main.xml code: to get understanding of layout</em></strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MainActivity"&gt;
  
      &lt;Button
          android:id="@+id/btbutton"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginStart="96dp"
          android:layout_marginLeft="96dp"
          android:layout_marginTop="56dp"
          android:onClick="btOn"
          android:text="@string/btbutton"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintTop_toTopOf="parent" /&gt;
  
      &lt;ListView
          android:id="@+id/list1"
          android:layout_width="305dp"
          android:layout_height="500dp"
          android:layout_marginStart="32dp"
          android:layout_marginLeft="32dp"
          android:layout_marginTop="204dp"
          android:layout_marginEnd="32dp"
          android:layout_marginRight="32dp"
          app:layout_constraintEnd_toEndOf="parent"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintTop_toTopOf="parent" /&gt;
  
      &lt;Button
          android:id="@+id/button2"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginStart="104dp"
          android:layout_marginLeft="104dp"
          android:layout_marginTop="124dp"
          android:onClick="scanNewDevices"
          android:text="@string/button2"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintTop_toTopOf="parent" /&gt;
  &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
  </code></pre>
  
  <p><strong><em>Current Results</em></strong></p>
  
  <p>Duplicate device names and if I turn off any of these devices, they are still displayed in the list.</p>
  
  <p><a href="https://i.stack.imgur.com/gIfeKm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gIfeKm.png" alt="Duplicate device names and if I turn off any of these devices, they are still displayed in the list"></a></p>