-3

I am want to separate the strings incoming from arduino and store it in variables for database purposes but when I try to divide that string using split() after a few moments the exception occurs java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 and the app keeps stopping the error is at Line 203 separated[1]

public class MainActivity extends AppCompatActivity {

private static final String TAG = "Android-Arduino";

Button btnOn, btnOff;
TextView temperatureText, heartbeatText;
Handler h;

final int RECIEVE_MESSAGE = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();

private ConnectedThread connectedThread;

// Common service that bluetooth device support
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

// MAC address of the bluetooth module.
private static String address = "00:18:E4:35:75:A6";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    temperatureText = (TextView) findViewById(R.id.temp);
    heartbeatText = (TextView)findViewById(R.id.heartbeat);

    getDataArduino();

    // Bluetooth adapter
    btAdapter = BluetoothAdapter.getDefaultAdapter();

    // Check whether the bluetooth is enabled / disabled
    checkBTState();


}

// Creates the communication chanel
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
    if(Build.VERSION.SDK_INT >= 10){
        try {
            final Method m = device.getClass().
                    getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class });
            return (BluetoothSocket) m.invoke(device, MY_UUID);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
    }
    return  device.createRfcommSocketToServiceRecord(MY_UUID);
}

@Override
public void onResume() {
    super.onResume();
    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: "
                + e.getMessage() + ".");
    }

    btAdapter.cancelDiscovery();
    try {
        btSocket.connect();
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException ex) {
            errorExit("Fatal Error", "In onResume() and unable to close socket during " +
                    "connection failure" + ex.getMessage() + ".");
        }
    }

    // Creates the data stream with the server
    connectedThread = new ConnectedThread(btSocket);
    connectedThread.start();
}

@Override
public void onPause() {
    super.onPause();

    try     {
        btSocket.close();
    } catch (IOException ex) {
        errorExit("Fatal Error", "In onPause() and failed to close socket." +
                ex.getMessage() + ".");
    }
}

private void checkBTState() {
    // Checks if the devices has bluetooth functionalities
    if(btAdapter==null) {
        errorExit("Fatal Error", "Bluetooth not support");
    } else {
        // Checks if the bluetooth is on
        if (btAdapter.isEnabled()) {
        } else {
            // Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}

private void errorExit(String title, String message){
    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
    finish();
}

private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[256];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                // Get number of bytes and message in "buffer"
                bytes = mmInStream.read(buffer);
                // Send to message queue Handler
                h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    //Call this from the main activity to send data to the remote device
    public void write(String message) {
        byte[] msgBuffer = message.getBytes();
        try {
            mmOutStream.write(msgBuffer);
        } catch (IOException e) {
            Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
        }
    }
}

public void getDataArduino() {
    temperatureText.clearComposingText();
    h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case RECIEVE_MESSAGE:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);
                    sb.append(strIncom);
                    int endOfLineIndex = sb.indexOf("\n");
                    if (endOfLineIndex > 0) {
                        String sbprint = sb.substring(0, endOfLineIndex);
                        sb.delete(0, sb.length());
                        String[] separated = sbprint.split(":");
                        heartbeatText.setText(separated[0]+ "");
                        temperatureText.setText(separated[1]+ "");


                    }
                    Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                    break;
            }
        }
    };
}
}

I need the temperature to display differently and heartrate to be displayed individually.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

You can first try to print the input data (StringBuffer sb) and split String array(String[] separated). You are getting error because the Strings have not split as your expected and only 1 element is present in the array sbprint, this is why when you try to access the second element you get ArrayIndexOutofBound index.

Once you print the Split String Array it would give you an idea where your data is wrong.

Ravi
  • 192
  • 1
  • 7
  • the sbprint turns out okay but how should I increase the length of the String[] separaed array? :( – Keyur Joshi Apr 09 '19 at 06:50
  • Since you are using the split function and storing the output in String[] separated array, you dont need to manually increase the size. size will be allocated based on the number of separator characters in your source string sbprint. – Ravi Apr 10 '19 at 06:15