Filling ListView Android - android

First of all.... HappyNew Year!!!! I'm starting to learn about Android programming and actually I'm trying to develop some code. Main idea is to search for Paired Bluetooth devices and also list all BT devices near... later I'll try to connect both devices but time to time :P
My problem is supposed to be easy because I fill my ListView with the paired ones but using this code I can't fill the one's I discover... But I don't know what I'm doing wrong cause Toast.MakeText shows this BT devices but not in the ListView.... Anyone can help me??? Many Thanks
//SHOW ANDROID VERSION
Context context = getApplicationContext();
//Setting up for JELLY_BEAN_MR1 and above
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
BluetoothManager bluetoothManager = (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager != null)
{
mBluetoothAdapter = bluetoothManager .getAdapter();
}
} else {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
//Enable
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
}
//Discover my BT
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
//Paired Devices
pairedDevices = mBluetoothAdapter.getBondedDevices();
final ArrayList<String> listBT = new ArrayList<String>();
ListView lv =(ListView)findViewById(R.id.listDevicesFound);
for(BluetoothDevice bt : pairedDevices)
listBT.add(bt.getName());
//Starting Search
final BroadcastReceiver mReceiver = 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);
listBT.add(device.getName()); //Something happens but not adding to ListView
Toast.makeText(getApplicationContext(), device.getName(),
Toast.LENGTH_SHORT).show();
}
}
};
registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
mBluetoothAdapter.startDiscovery();
//Show ListView
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , listBT));

Create a class variable for your adapter (above in your class):
private ArrayAdapter<String> mDeviceListAdapter;
Crete the adapter and set it to the list:
//Show ListView
mDeviceListAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , listBT);
lv.setAdapter(mDeviceListAdapter);
Update the adapter data when you have a new item:
#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);
listBT.add(device.getName());
if(mDeviceListAdapter!=null){
mDeviceListAdapter.add(device.getName());
mDeviceListAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(), device.getName(),
Toast.LENGTH_SHORT).show();
}
}

Related

what method i must use instead of DeviceListAdapter in android studio

I want to scan unpaired devices through Bluetooth. Devices are not shown in the list. is there a problem of not using DeviceListAdapter ?? if it is then which option i have to use to show devices because in android studio there is no option of DeviceListAdapter.
This is button code :
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.startDiscovery();
IntentFilter discoverDeviceIntent = new IntentFilter(BluetoothDevice
.ACTION_FOUND);
registerReceiver(broadcastReceiver, discoverDeviceIntent);
}
if (!bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.startDiscovery();
IntentFilter discoverDeviceIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, discoverDeviceIntent);
}
}
});
//and here is broadcast_receiver code to receive device
broadcastReceiver =new BroadcastReceiver() {
#Override
public void onReceive (Context context, Intent intent) {
final String action = intent.getAction();
unpaired_list = new ArrayList<>();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
unpaired_list.add(device);
Toast.makeText(MainActivity.this, "Showing Unpaired Device", Toast.LENGTH_LONG).show();
final ArrayAdapter upadapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1);
unpairlv.setAdapter(upadapter);
}
}
};
Try adding as below
upadapter.addAll(unpaired_list);
add it just after creating upadapter in the below line.
final ArrayAdapter upadapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1);
Edited Answer
Declare global variables
ArrayAdapter upadapter;
ArrayList unpaired_list = new ArrayList<>();
Add this in oncreate()
upadapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1);
change the broadcastReceiver onReceive method.
broadcastReceiver =new BroadcastReceiver() {
#Override
public void onReceive (Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
unpaired_list.add(device);
Toast.makeText(MainActivity.this, "Showing Unpaired Device", Toast.LENGTH_LONG).show();
upadapter.add(device);
unpairlv.setAdapter(upadapter);
}
}
};

Android Bluetooth BroadcastReceiver not discovering devices

I have combed the forums in order to try and figure out why my bluetooth BroadcastReceiver isn't working and all I can find is people saying to ensure that coarse/fine location permissions are requested. I'm already doing that here (method is called before the discovery method):
Request Permissions
private void requestPermissions()
{
final int CODE = 5; // app defined constant used for onRequestPermissionsResult
boolean allPermissionsGranted = true;
String[] permissionsToRequest =
{
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
for(String permission : permissionsToRequest)
{
allPermissionsGranted = allPermissionsGranted &&
(ContextCompat.checkSelfPermission(this, permission)
== PackageManager.PERMISSION_GRANTED);
}
if(!allPermissionsGranted)
{
ActivityCompat.requestPermissions(this, permissionsToRequest, CODE);
}
}
The problem is that my BroadcastReceiver never finds other discoverable devices, if a device is already paired, it puts it in a ListView as expected, but once the device is unpaired, it cannot identify it again. See screenshots below.
Output with no paired devices
Output with paired devices
I'm at a loss at this point, it feels like I've tried everything, if anyone has any ideas you'd save my life and I'd be eternally grateful.
Thanks,
Broadcast Receiver
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(btDevice.getBondState() != BluetoothDevice.BOND_BONDED)
{
newDevicesArrayAdapter.add(btDevice.getName() + "\n" + btDevice.getAddress());
}
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
setTitle(R.string.select_device);
if(newDevicesArrayAdapter.getCount() == 0)
{
newDevicesArrayAdapter.clear();
String noDevices = getResources().getText(R.string.none_found).toString();
newDevicesArrayAdapter.add(noDevices);
}
}
}
};
onCreate - Setup ListView elements and IntentFilters
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_machine);
setResult(Activity.RESULT_CANCELED);
pairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
newDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
pairedListView.setAdapter(pairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(deviceClickListener);
newDevicesListView.setAdapter(pairedDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(deviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(broadcastReceiver, filter);
}
doDiscovery() - Called by onStart method, I've verified that it gets called
private void doDiscovery()
{
Log.d(TAG, "doDiscovery()");
requestPermissions();
setTitle(R.string.scanning);
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
if(btAdapter.isDiscovering()) { btAdapter.cancelDiscovery(); }
newDevicesArrayAdapter.clear();
btAdapter.startDiscovery();
}
Turns out I was just being stupid and had values updating to both ListViews, so I never saw the list of other devices.
newDevicesListView.setAdapter(pairedDevicesArrayAdapter);
Should have been:
newDevicesListView.setAdapter(newDevicesArrayAdapter);

Android Studio 2.2.3 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); is deprcated

the below is my full code, when i switch to this activity, it crashed.
I have tried many solutions, yet it didn't work. Thanks!!
there is some mistake (deprecated) on
line 41 : requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
line 118 : setProgressBarIndeterminateVisibility(true);
line 175 : setProgressBarIndeterminateVisibility(false);
public class DeviceList extends Activity {
private static final String TAG = DeviceList.class.getSimpleName();
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_device_list);
// Set result CANCELED in case the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
ArrayAdapter<String> pairedDevicesArrayAdapter =
new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(pairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_device);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = "none paired";
pairedDevicesArrayAdapter.add(noDevices);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle("Scanning");
// Turn on sub-title for new devices
findViewById(R.id.new_device_title).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
/**
* The on-click listener for all devices in the ListViews
*/
private AdapterView.OnItemClickListener mDeviceClickListener
= new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
/**
* The BroadcastReceiver that listens for discovered devices and changes the title when
* discovery is finished
*/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle("Select Device");
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = "Not Found";
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}

Is there a system action to discover and pair Bluetooth devices in Android?

The discovery and pairing process described in the Android Bluetooth Documentation is quite complex. Even a separate permission is needed for that: BLUETOOTH_ADMIN.
I wonder if there is a system action, that I just would call, that will handle the UI, return, and the I will just choose an already paired device. Or do I have to implement all that UI myself?
if you want to get the list of paired bluetooth devices you can use this code
public class DeviceList extends ActionBarActivity
{
//widgets
Button btnPaired;
ListView devicelist;
//Bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
//Calling widgets
btnPaired = (Button)findViewById(R.id.button);
devicelist = (ListView)findViewById(R.id.listView);
//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
pairedDevicesList();
}
});
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, NextActivity.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at NextActivity
startActivity(i);
}
};
}

Android Bluetooth Discovery in a sequential method?

I am new to Android programming. I want to make a library (a JAR file) that contains the Bluetooth discovery functionality.
Since it is a library, the method inside should be a sequential method (start the Bluetooth discovery, wait for an amount of time, and return the result).
I made a code below, but it does not work. In the LogCat, I could see the intents, but the BroadcastReceiver could not catch the intents.
Is there something wrong with the code?.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mSendButton = (Button) findViewById(R.id.button1);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
}
});
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("device_name", device.getName());
Log.e("device_add", device.getAddress());
numberOfDevice++;
Found_Device = true;
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if(numberOfDevice == 0){
Log.e("DISCOVERY", "No Device found");
}
Log.e("DISCOVERY", "Number of device :" + numberOfDevice);
Discovery_Finish = true;
}
}
};
public void doDiscovery(){
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
Discovery_Finish = false;
Found_Device = false;
long counter = 0;
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
while((Found_Device == false) || (Discovery_Finish == false)){
counter++;
if (counter >= 1000000){
break;
}
}
// Add a code to check the number of device
unregisterReceiver(mReceiver);
mBluetoothAdapter.cancelDiscovery();
}
Is there any way to check the intent without using BroadcastReceiver?
Thank you for your help.
I think you are missing to start the discovering the other devices.
You are overwriting your IntentFilter when you do this:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
You should do it like this:
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);

Categories

Resources