简体   繁体   中英

Android app force closing with arduino

I'm developing an app with eclipse and arduino which connects to a bluetooth module. I can then control the LEDS on the board. However my code shows no errors but the app force closes everytime I hit a button. Here is my code:

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class BluetoothTest extends Activity
{
TextView labelConnect;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;


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

    Button openButton = (Button)findViewById(R.id.open);
    Button closeButton = (Button)findViewById(R.id.close);

    Button onButton  = (Button)findViewById(R.id.onButton);
    Button offButton = (Button)findViewById(R.id.offButton);

    Button redButton  = (Button)findViewById(R.id.redButton);
    Button greenButton = (Button)findViewById(R.id.greenButton);
    Button blueButton = (Button)findViewById(R.id.blueButton);

    labelConnect = (TextView)findViewById(R.id.mylabel);

    //Open Bluetooth
    openButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                findBT();
                openBT();
            }
            catch (IOException ex) { }
        }
    });

    //Close Bluetooth
    closeButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                closeBT();
            }
            catch (IOException ex) { }
        }
    });

  //Red Button
    redButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                redButton();
            }
            catch (IOException ex) { }
        }
    });

    //Green Button
    greenButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                greenButton();
            }
            catch (IOException ex) { }
        }
    });

    //Blue Button
    blueButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                blueButton();
            }
            catch (IOException ex) { }
        }
    });

    //On Button    - set strip to white
    onButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                onButton();
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    });

  //Off Button    - set strip to all OFF
    offButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                offButton();
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    });


}  // end onCreate 


void findBT()
{
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(mBluetoothAdapter == null)
    {
        labelConnect.setText("No bluetooth adapter available");
    }

    if(!mBluetoothAdapter.isEnabled())
    {
        Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetooth, 0);
    }

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0)
    {
        for(BluetoothDevice device : pairedDevices)
        {
            if(device.getName().equals("BTNode0"))    // Change to match RN42 - node name
            {
                mmDevice = device;
                Log.i("ArduinoBT", "findBT found device named " + mmDevice.getName());
                Log.i("ArduinoBT", "device address is " + mmDevice.getAddress());
                break;
            }
        }
    }
    labelConnect.setText("Bluetooth Device Found");
}

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

    labelConnect.setText("BT  << " + mmDevice.getName()  + " >> is now open ");
}

void closeBT() throws IOException
{
    mmOutputStream.close();
    mmSocket.close();
    labelConnect.setText("Bluetooth Closed");
}


  void offButton() throws IOException
{
    mmOutputStream.write("0".getBytes());
}


void redButton() throws IOException
{
    mmOutputStream.write("1".getBytes());
}

void greenButton() throws IOException
{
    mmOutputStream.write("2".getBytes());
}

void blueButton() throws IOException
{
    mmOutputStream.write("3".getBytes());
}

void onButton() throws IOException
{
    mmOutputStream.write("4".getBytes());
}



}

And here is my log for what happens when I hit the connect button

04-25 12:15:10.771: W/asset(22604): Copying FileAsset 0x74c0a9d8 (zip:/data/app/Android.Arduino.Bluetooth-2.apk:/resources.arsc) to buffer size 1912 to make it aligned.
04-25 12:15:10.821: D/RenderPolicy(22604): ViewRootImpl.enableHardwareAcceleration -> enableRenderPolicy
04-25 12:15:10.881: I/Adreno-EGL(22604): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build:  (CL4169980)
04-25 12:15:10.881: I/Adreno-EGL(22604): OpenGL ES Shader Compiler Version: 17.01.10.SPL
04-25 12:15:10.881: I/Adreno-EGL(22604): Build Date: 02/04/14 Tue
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Branch: 
04-25 12:15:10.881: I/Adreno-EGL(22604): Remote Branch: 
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Patches: 
04-25 12:15:10.881: I/Adreno-EGL(22604): Reconstruct Branch: 
04-25 12:15:12.363: W/dalvikvm(22604): threadid=1: thread exiting with uncaught exception (group=0x41625e18)
04-25 12:15:12.373: E/AndroidRuntime(22604): FATAL EXCEPTION: main
04-25 12:15:12.373: E/AndroidRuntime(22604): Process: Android.Arduino.Bluetooth, PID: 22604
04-25 12:15:12.373: E/AndroidRuntime(22604): java.lang.NullPointerException
04-25 12:15:12.373: E/AndroidRuntime(22604):    at Android.Arduino.Bluetooth.BluetoothTest.openBT(BluetoothTest.java:185)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at Android.Arduino.Bluetooth.BluetoothTest$1.onClick(BluetoothTest.java:53)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at android.view.View.performClick(View.java:4480)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at android.view.View$PerformClick.run(View.java:18673)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at android.os.Looper.loop(Looper.java:157)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at android.app.ActivityThread.main(ActivityThread.java:5872)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
04-25 12:15:12.373: E/AndroidRuntime(22604):    at dalvik.system.NativeStart.main(Native Method)

As they have already said in the comments, the mmDevice you are trying to use in the openBT method is null, because no device was found in the findBT method and the variable was not initialized. You need to fix your code so that you don't try to open the connection if the device was not found.

The other main issue in your code, once you solve this, is the SocketConnection you are trying to open in the Main Thread. Button handlers and GUI events are executed in the main thread, so your openBT should be moved to a separate thread (or better, a Service).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM