1

I have this android application when I'm trying to connect to another bluetooth device (HC-05). The problem is when I first open the program a "Unfortunately, AppName has stopped" message pops up 3 times (after pressing the ok button every time). Then a bluetooth request message ("An app wants to turn on Bluetooth,Allow?") pops up and that message also pops up three times and after pressing yes every time the application programs but still continues to run in the background. The application works after opening the app a second time. What could be causing this problem? I got this code from https://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/

public class MainActivity extends AppCompatActivity
{
TextView notification,btstate;
BluetoothAdapter myBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;


private BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        switch (intent.getIntExtra(myBluetoothAdapter.EXTRA_STATE,-1))
        {
            case STATE_ON:
                MainActivity.this.setTitle("Opened");
                break;
            case STATE_OFF:
                MainActivity.this.setTitle("Closed");
                break;
        }
    }
};


@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button doorState = (Button)findViewById(R.id.btn_door);
    final Button led1State = (Button)findViewById(R.id.btn_led1);
    final Button led2State = (Button)findViewById(R.id.btn_led2);
    final Button led3State = (Button)findViewById(R.id.btn_led3);
    Button tempState = (Button)findViewById(R.id.btn_temp);
    Button motionState = (Button)findViewById(R.id.btn_motion);
    Button fanState = (Button)findViewById(R.id.btn_fan);

   btstate = (TextView)findViewById(R.id.txt_btstate);
   notification = (TextView)findViewById(R.id.txt_notification);


    try
    {
        findBT();
        openBT();
    }
    catch (IOException ex) { }


   //Buttons codes here

void findBT()
{
    myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    this.registerReceiver(br,new IntentFilter(myBluetoothAdapter.ACTION_STATE_CHANGED));

    if(myBluetoothAdapter == null)
    {
       btstate.setText("No bluetooth adapter available");
    }

    if(myBluetoothAdapter.getState()== STATE_OFF)
    {
        Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetooth, 0);
    }

    Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0)
    {
        for(BluetoothDevice device : pairedDevices)
        {
            if(device.getName().equals("SmartHome"))
            {
                mmDevice = device;
                btstate.setText("Connection Succesful");
                break;
            }
            else{
                btstate.setText("Connection Lost");
            }
        }
    }
}

void openBT() throws IOException
{
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID //bluetooth id
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
    mmSocket.connect();
    mmOutputStream = mmSocket.getOutputStream();
    mmInputStream = mmSocket.getInputStream();

    beginListenForData();

    btstate.setText("Bluetooth Opened");
}

void beginListenForData()
{
    final Handler handler = new Handler();
    final byte delimiter = 10; //This is the ASCII code for a newline character

    stopWorker = false;
    readBufferPosition = 0;
    readBuffer = new byte[1024];
    workerThread = new Thread(new Runnable()
    {
        public void run()
        {
            while(!Thread.currentThread().isInterrupted() &&    !stopWorker)
            {
                try
                {
                    int bytesAvailable = mmInputStream.available();
                    if(bytesAvailable > 0)
                    {
                        byte[] packetBytes = new byte[bytesAvailable];
                        mmInputStream.read(packetBytes);
                        for(int i=0;i<bytesAvailable;i++)
                        {
                            byte b = packetBytes[i];
                            if(b == delimiter)
                            {
                                byte[] encodedBytes = new byte[readBufferPosition];
                                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                final String data = new String(encodedBytes, "US-ASCII");
                                readBufferPosition = 0;

                                handler.post(new Runnable()
                                {
                                    public void run()
                                    {

                                   notification.setText(data);

                                    }
                                });
                            }
                            else
                            {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                }
                catch (IOException ex)
                {
                    stopWorker = true;
                }
            }
        }
    });

    workerThread.start();
}

void sendData(String msg) throws IOException
{
    msg += '\n';
    mmOutputStream.write(msg.getBytes());
}
/*
void closeBT() throws IOException
 {
    stopWorker = true;
    mmOutputStream.close();
    mmInputStream.close();
    mmSocket.close();
    btState.setText("Bluetooth Closed");
}

*/
}

Log cat errors:

E/AndroidRuntime: FATAL EXCEPTION: main
 Process: appname.company.com.android_enon, PID: 27502
 java.lang.RuntimeException: Unable to start activity ComponentInfo{appname.company.com.android_enon/appname.company.com.android_enon.MainActivity}: java.lang.NullPointerException
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2200)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
     at android.app.ActivityThread.access$800(ActivityThread.java:139)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:136)
     at android.app.ActivityThread.main(ActivityThread.java:5105)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: java.lang.NullPointerException
     at appname.company.com.android_enon.MainActivity.openBT(MainActivity.java:240)
     at appname.company.com.android_enon.MainActivity.onCreate(MainActivity.java:80)
     at android.app.Activity.performCreate(Activity.java:5275)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250) 
     at android.app.ActivityThread.access$800(ActivityThread.java:139) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:136) 
     at android.app.ActivityThread.main(ActivityThread.java:5105) 
     at java.lang.reflect.Method.invokeNative(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:515) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608) 
     at dalvik.system.NativeStart.main(Native Method) 
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Melek
  • 11
  • 2
  • 1
    Use LogCat to examine the Java stack trace associated with each of your crashes: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare Dec 20 '15 at 23:02

1 Answers1

0

I think the problem is that the myBluetoothAdapter can be addressed before inicializing in BroadcastReceiver and is null. Therefore, apply this (assuming your device can bluetooth)

private static BluetoothAdapter myBluetoothAdapter {get {return BluetoothAdapter.DefaultAdapter; }}

or check if pairedDevices not null...

Majkl
  • 765
  • 1
  • 9
  • 25
  • Did you check MainActivity.this... in BroadCastReceiver If it is not null? BroadcastReceiver can be independent MainActivity and jump before MainActivity. – Majkl Dec 21 '15 at 07:51
  • According to the added stack trace it looks like the problem occurs at the start activity (but log the text does not say what problem and where exactly is). Try to comment most of the code and then gradually try uncomment code and test where the problem occurs. – Majkl Dec 21 '15 at 08:23