I am trying to activate bluetooth programatically in android and the application installs fine, but when I click the button to activate BT , it gives exception. I am not able to handle the exception. Any help is greatly appreciated. I am new to this. Here is the code :
package com.example.helloandroid2;
import java.io.IOException;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HelloAndroid extends Activity {
// Declare our Views, so we can access them later
private Button activate_buletooth;
static final int REQUEST_ENABLE_BT = 0;
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set Activity Layout
setContentView(R.layout.main);
activate_buletooth = (Button)findViewById(R.id.activate_buletooth);
// Set Click Listener
activate_buletooth.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Context context = getApplicationContext();
CharSequence text = "BT not suported";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == REQUEST_ENABLE_BT)
{
if(resultCode == RESULT_CANCELED)
{
Context context = getApplicationContext();
CharSequence text = "bt not available";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
}
}
}
}