0

When I click the open button in my android app then the bluetooth gets connected but when it displays the value in textview my app stops. By open button, bluetooth connection is done of android phone and bluetooth module I checked it in logcat then the error I get is:

11-21 23:06:32.338 11949-12442/com.example.sugandhabansal.bluetooth_torch E/AndroidRuntime: FATAL EXCEPTION: Thread-520
                                                                                        Process: com.example.sugandhabansal.bluetooth_torch, PID: 11949
                                                                                        java.lang.StringIndexOutOfBoundsException: length=0; index=0
                                                                                            at java.lang.String.charAt(Native Method)
                                                                                            at com.example.sugandhabansal.bluetooth_torch.bluetooth_torch_Activity$5.run(bluetooth_torch_Activity.java:222)
                                                                                            at java.lang.Thread.run(Thread.java:818)

java code is:

package com.example.sugandhabansal.bluetooth_torch;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class bluetooth_torch_Activity extends Activity
{
    TextView myLabel,mydata,myvalue;

    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    int counter;
    volatile boolean stopWorker;
    private CameraManager mCameraManager;
    private String mCameraId;
    private ImageButton mTorchOnOffButton;
    private Boolean isTorchOn;
    int min_data_onflash=-10;
    int max_data_onflash=10;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Log.d("bluetooth_torch", "onCreate()");
        setContentView(R.layout.activity_bluetooth_torch_);

        Button openButton = (Button)findViewById(R.id.open);
        Button closeButton = (Button)findViewById(R.id.close);
        myLabel = (TextView)findViewById(R.id.label);
        myvalue = (TextView)findViewById(R.id.value);
        mydata = (TextView)findViewById(R.id.data);

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

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

        mTorchOnOffButton = (ImageButton) findViewById(R.id.button_on_off);
        isTorchOn = false;

        Boolean isFlashAvailable = getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        if (!isFlashAvailable) {

            AlertDialog alert = new AlertDialog.Builder(bluetooth_torch_Activity.this)
                    .create();
            alert.setTitle("Error !!");
            alert.setMessage("Your device doesn't support flash light!");
            alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // closing the application
                    finish();
                    System.exit(0);
                }
            });
            alert.show();
            return;
        }


        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            mCameraId = mCameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

        mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isTorchOn) {
                        turnOffFlashLight();
                        isTorchOn = false;
                    } else {
                        turnOnFlashLight();
                        isTorchOn = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    void findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null)
        {
            myLabel.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("HC-05"))
                {
                    mmDevice = device;
                    break;
                }
            }
        }
        myLabel.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();
        mmInputStream = mmSocket.getInputStream();

        beginListenForData();

        myLabel.setText("Bluetooth Connected");
    }

    void beginListenForData()
    {
        final Handler handler = new Handler();
        final byte delimiter = 35; //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");
                                    Log.d("SKY",DATA);
                                    readBufferPosition = 0;


                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            mydata.setText(DATA);
                                        }
                                    });
                                    if (DATA.charAt(i) == '#') {
                                        String number_string = DATA.substring(1  /* data after # */, DATA.length());

                                        int angle = Integer.getInteger(number_string);


                                        if (angle > min_data_onflash && angle < max_data_onflash) {
                                            turnOnFlashLight();
                                        } else {
                                            turnOffFlashLight();
                                        }
                                    }
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        stopWorker = true;
                    }
                }
            }
        });

        workerThread.start();
    }


    void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    }

    public void turnOnFlashLight() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mCameraManager.setTorchMode(mCameraId, true);
                mTorchOnOffButton.setImageResource(R.drawable.on);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void turnOffFlashLight() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mCameraManager.setTorchMode(mCameraId, false);
                mTorchOnOffButton.setImageResource(R.drawable.off);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(isTorchOn){
            turnOffFlashLight();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(isTorchOn){
            turnOffFlashLight();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isTorchOn){
            turnOnFlashLight();
        }
    }
}

What is the error and how can I remove it?.....please help me out

Sugandha
  • 59
  • 7
  • mmDevice is only set if device.getName().equals("HC-05"). If device.getName() equals something else then wouldn't mmDevice be null? – MikeJRamsey56 Nov 20 '16 at 18:50
  • the name of the device is set to "HC-05". So, I think this maynot be the error – Sugandha Nov 21 '16 at 00:39
  • Put a try catch(IOException e) around mmOutputStream = mmSocket.getOutputStream(); mmInputStream = mmSocket.getInputStream(); – MikeJRamsey56 Nov 21 '16 at 02:32
  • Take a look at [Java Code Examples for android.bluetooth.BluetoothSocket](http://www.programcreek.com/java-api-examples/index.php?api=android.bluetooth.BluetoothSocket) – MikeJRamsey56 Nov 21 '16 at 02:34
  • I had edited my code and have found an error. The code and error has been edited. Please help me out – Sugandha Nov 21 '16 at 17:52
  • You logged DATA. How many characters does DATA have? Looks like the number of characters in DATA is less than bytesAvailable. It is easier to ask for help but now is the time to calm down and think it through. You can do it. :-) – MikeJRamsey56 Nov 21 '16 at 18:06

0 Answers0