I’ve written a code which should discover bluetooth devices and write it to the text file. But when writing to the text file, only the last found device is written and the rest of it are ignored.
For example my device discovers “abcd”, “efgh”, & “ijkl” bluetooth devices, and only “ijkl” is written to the text file.
How do I write all the discovered devices to text file?
Below is the code of my Broadcast Receiver
private final BroadcastReceiver bcReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
deviceName = device.getName();
try{
File root = new File(Environment.getExternalStorageDirectory(), "Folder");
if(!root.exists()){
root.mkdirs();
}
File deviceFiles = new File(root, "File");
FileWriter writer = new FileWriter(deviceFiles);
writer.append(deviceName);
writer.flush();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
btArrayAdapter.add(deviceName);
}
}
};
This is happening because, you are creating a new file, every time a new device is found. So after saving abcd device in the file (say DeviceFile), it then searches for the next device, on finding efgh, it then creates a file DeviceFile which replaces the old one. thus only the last device is saved in the file.
So create the file before starting the scan.
Edit-
Though I havent tested it. Just implemented the logic. Make the relavent adjustments if required.