I have created an app to display paired devices successfully but not able to connect to it.
I tried a lot but i'm getting "app has been stopped working".
Please advise on issues in my code to connect to paired devices:
public class MainActivity extends AppCompatActivity {
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothAdapter bt;
ArrayAdapter<String> listAdapter;
Set<BluetoothDevice> devicesArray;
ListView listview;
Button connectbutton;
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
if(bt==null){
Toast.makeText(getApplicationContext(), "no bluetooth on device",Toast.LENGTH_SHORT).show();
finish();
}
else
{
if(!bt.isEnabled()){
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);
}
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), (CharSequence) parent.getItemAtPosition(arg2), Toast.LENGTH_SHORT).show();
if(bt.isDiscovering())
{
bt.cancelDiscovery();
}
BluetoothDevice selectedDevice = (BluetoothDevice) parent.getItemAtPosition(arg2);
}
});
}
public void onButtonClick(View v)
{
getpaireddevices();
}
public void onButtonClick2(View v)
{
startdiscovery();
}
private void getpaireddevices() {
devicesArray = bt.getBondedDevices();
if (devicesArray.size() > 0) {
for (BluetoothDevice device : devicesArray)
listAdapter.add(device.getName());
}
}
private void startdiscovery()
{
bt.cancelDiscovery();
bt.startDiscovery();
}
private void init() {
listview = (ListView)findViewById(R.id.listView);
connectbutton = (Button)findViewById(R.id.button);
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
listview.setAdapter(listAdapter);
bt= BluetoothAdapter.getDefaultAdapter();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "bluetooth must be turned on to continue",Toast.LENGTH_SHORT).show();
finish();
}
}