Bluetooth Messages received in Android from the Arduino are incomplete in My app

Hi!
I work on an Android application that is receive message from the Arduino.
My problem is that the message received incomplete.
I have tested the code for the Arduino on several applications for Bluetooth and it works correctly.
I am sending from Arduino the word “help” but I receive it in the application as “elp”.

the main activity code:

i have but some comment in the code to Explain some points.

package com.example.al_br.tictactoy;
    import java.io.IOException;
    import java.util.Set;
    import java.util.UUID;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.provider.Settings;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;

    public class MainActivity extends Activity  {

    static final int STATE_LISTENING = 1;
    static final int STATE_CONNECTING=2;
    static final int STATE_CONNECTED=3;
    static final int STATE_CONNECTION_FAILED=4;
    static final int STATE_MESSAGE_RECEIVED=5;

    TextView t1;
    //CheckBox cb1;
    SendReceive sendReceive ;

    String address = null , name=null;

    BluetoothAdapter myBluetooth = null;
    BluetoothSocket btSocket = null;
    Set<BluetoothDevice> pairedDevices;
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {setw();} catch (Exception e) {}
       //cb1 =  findViewById(R.id.checkBox);
            //stream();
    }
    @SuppressLint("ClickableViewAccessibility")
    private void setw() throws IOException
    {
        t1=(TextView)findViewById(R.id.textView1);
        text = (TextView) findViewById(R.id.textView_Text);
        //cb1 = (CheckBox) findViewById(R.id.checkBox);
        bluetooth_connect_device();
        }

    private void bluetooth_connect_device() throws IOException
    {
        try
        {
            myBluetooth = BluetoothAdapter.getDefaultAdapter();
            address = myBluetooth.getAddress();
            pairedDevices = myBluetooth.getBondedDevices();
            if (pairedDevices.size()>0)
            {
                for(BluetoothDevice bt : pairedDevices)
                {
                    address=bt.getAddress().toString();name = bt.getName().toString();
                    Toast.makeText(getApplicationContext(),"Connected", Toast.LENGTH_SHORT).show();
                }
            }
        }
        catch(Exception we){}
        myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
        BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
        btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
        btSocket.connect();
        try { t1.setText("BT Name: "+name+"\nBT Address: "+address); }
        catch(Exception e){}

        sendReceive=new SendReceive(btSocket);
        sendReceive.start();
    }

    public class SendReceive extends Thread{
        private final BluetoothSocket bluetoothSocket;
        private final InputStream inputStream;
        //private final OutputStream outputStream;
        public SendReceive(BluetoothSocket socket){

            bluetoothSocket = socket;
            InputStream tmpIn = null;
            //OutputStream tmpOut = null;

            try {
                tmpIn = bluetoothSocket.getInputStream();
               // tmpOut = bluetoothSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

            inputStream = tmpIn;
           // outputStream = tmpOut;
        }

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

            while (true){
                try {
                   bytes = inputStream.read(buffer);
                    handler.obtainMessage(STATE_MESSAGE_RECEIVED,bytes,-1,buffer).sendToTarget();//send the message to handler
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }//end of while
        }//end of method run()


    }//end of send resev

    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what)
            {
                case STATE_LISTENING:
                   // status.setText("Listening");
                    break;
                case STATE_CONNECTING:
                   // status.setText("Connecting");
                    break;
                case STATE_CONNECTED:
                  //  status.setText("Connected");
                    break;
                case STATE_CONNECTION_FAILED:
                   // status.setText("Connection Failed");
                    break;
                case STATE_MESSAGE_RECEIVED:
                    byte[] readBuff= (byte[]) msg.obj;
                    String tempMsg=new String(readBuff,0,msg.arg1);
                   // text.setText(tempMsg); <-- if I but this line the tixt will be elp
                    if(tempMsg == "help"){//the handler check is the message is == to help
                    SendSms();
                    }
                    break;
            }
            return true;
        }
    });

    public void SendSms(){
    text.setText("HELP,OK!");
    }
    }

My main point is to send “help” from the Arduino to the Android and the Android

the App will check If the incoming message == help (in the Handler) the handler

will call another method that is set text to HELP,OK!.

(I am calling SendSms() To make sure that is I can call it , because I want it to send real SMS , But now it is under development.)

Can you give me some advice and guidance?

All thanks and appreciation.

If your problem is with your Android code then this is not the Forum for getting help.

If you think the problem is in your Arduino code then please post the Arduino program and give as much detail as possible about what you think is wrong with it.

...R

this is my arduino code :

#include <SoftwareSerial.h>
#define ACTIVATED LOW
const int RX_PIN = 2;
const int TX_PIN = 3;
SoftwareSerial Ser(RX_PIN, TX_PIN);
const int buttonPin = 4;
int BUZER_PIN = 13; // Initializing pin number 
int buttonState = 0;
void setup() //The setup function will only run once, after each powerup.It initializes and sets the initial values
{
  Ser.begin(9600);
  Serial.begin(9600);   //Sets the baud for serial data transmission (Bits Per Second)
  pinMode(BUZER_PIN,OUTPUT); //Specify behaviour of pin to work either as an input or an output
  pinMode(buttonPin,INPUT);
  digitalWrite(buttonPin,HIGH);
}
void loop() 
{
  buttonState = digitalRead(buttonPin);
  if(buttonState == ACTIVATED){
    digitalWrite(BUZER_PIN,HIGH);
    Ser.println("help");
    delay(1000);
    }
    else{
    digitalWrite(BUZER_PIN,LOW);
    }
}

I have test it with other app and it works correctly but with my app it is not work.

so When I change Ser.println(“help”); To Ser.print("help "); it is not work

I mean with print only I do not receive any messages , but with println I receive it elp.

so Maybe the problem is in the arduino code.

Mohamed_Ali_Klay:
I have test it with other app and it works correctly but with my app it is not work.

What two apps are you referring to?

The Arduino code is short and I don’t see anything wrong with it, However it is not a very robust way of sending data because the receiving program has no means to know when a message starts or ends.

Have a look at the 3rd example in Serial Input Basics .

You can send data in a compatible format with code like this

Serial.print('<'); // start marker
Serial.print(value1);
Serial.print(','); // comma separator
Serial.print(value2);
Serial.println('>'); // end marker

The example was written for receiving messages on the Arduino but the concept is just as relevant for receiving messages from an Arduino. The technique can certainly be implemented in an Android program but you will need to get advice elsewhere if you need help with Android programming.

…R

Hello Mohamed , i have some problem !! can you help me ??

Hi.

I would try a Bluetooth serial terminal app on the phone instead of your app. See if that receives "elp".

John.