Textview values does not update when data received from Arduino - android

I receiving 3 data from Arduino and the data just keep coming in. My problem is the data doesn't update to the new received values.
Here is the screenshot from the logcat:
So D/BPM is the value in the textview 68
D/SPo2 is the value in the textview 99
D/temp is the value in textview 28.0
D/read: 71 is for BPM 99 is for SPo2 and 28.11 is for temp.
But the textview values just stuck at 68 99 and 28.0. :(
Here are my code for the Android part:
public class Bluetooth_dataDisplay extends Activity {
//declaration
BluetoothAdapter mAdapter;
private ArrayAdapter adapter;
TextView myLabel;
TextView myLabel1;
TextView myLabel2;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;
private ListView listview;
private BluetoothSocket bluetoothSocket;
private ConnectedThread mConnectedThread;
final int handlerState = 0;
private StringBuilder recDataString = new StringBuilder();
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
recDataString.append(readMessage);
Log.d("read",readMessage);
if (recDataString.charAt(0) == '#')
{
String BPM = recDataString.substring(1,3);
String SPO2= recDataString.substring(3,5);
String Temp= recDataString.substring(5,9);
Log.d("BPM", BPM);
Log.d("SPO2", SPO2);
Log.d("Temp", Temp);
myLabel.setText("BPM" + " " + BPM);
myLabel1.setText("SPO2" +" "+ SPO2);
myLabel2.setText("Temp"+" " + Temp);
}
//recDataString.delete(0, recDataString.length());
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_datadisplay);
myLabel = (TextView)findViewById(R.id.label);
myLabel1 = (TextView)findViewById(R.id.label1);
myLabel2= (TextView)findViewById(R.id.label2);
}//end oncreate
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//Get MAC address from BluetoothActivity using intent and Extra
String MAC = getIntent().getStringExtra("MAC");
//must declare every time on a new activity if not will result in null error
mAdapter = BluetoothAdapter.getDefaultAdapter();
//create device and set the MAC address
BluetoothDevice bluetoothDevice = mAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
#Override
public void onPause()
{
super.onPause();
try {
bluetoothSocket.close();
} catch (IOException e) {
Log.e("error", "terminate thread");
e.printStackTrace();
}
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
*
* #param socket The BluetoothSocket on which the connection was made
* #param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
}
private class ConnectingThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
mAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
connected(bluetoothSocket, bluetoothDevice);
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream mmInputStream;
//private final OutputStream mmOutputStream;
public ConnectedThread(BluetoothSocket socket) {
bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
//tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInputStream = tmpIn;
//mmOutputStream = tmpOut;
}//endofConnectedThread(BluetoothSocket socket)
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInputStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}//end of void run
}//end of connectecthread
}
Because Arduino will be sending in data eg #719928.11 so the index will be in this order (0123456789)
Which is why I did it this way to extract the data:
if (recDataString.charAt(0) == '#')
{
String BPM = recDataString.substring(1,3);
String SPO2= recDataString.substring(3,5);
String Temp= recDataString.substring(5,9);
Log.d("BPM", BPM);
Log.d("SPO2", SPO2);
Log.d("Temp", Temp);
myLabel.setText("BPM" + " " + BPM);
myLabel1.setText("SPO2" +" "+ SPO2);
myLabel2.setText("Temp"+" " + Temp);
}
Just to add more details regarding the data:
BPM and SPO2 are in int (pulse oximeter)
Temp is in float format
So if my pulse oximeter is not on. My data look like this #0028.28 where the first 0 is BPM and the second 0 is SPO2. 28.28 is temp
So if the pulse oximeter is on. My data look like this #669928.28 where 66 is BPM and 99 is SPO2. 28.28 is temp. Below is data displayed in Arduino serial monitor:

Try this
1 .
replace
private StringBuilder recDataString = new StringBuilder();
with this one
private String recDataString = "";
2 . replace
recDataString.append(readMessage);
with this one
recDataString = readMessage ;
Data Parsing for different-2 situations :
if(recDataString.lenth > 0){
//If Oxiometer is OFF
if(recDataString.startsWith(#00) && recDataString.length == 8){
//Do Parsing here #0028.14
String BPM = "0";
String SPO2= "0";
String temp = recDataString.split("00")[1];
myLabel.setText("BPM" + " " + BPM);
myLabel1.setText("SPO2" +" "+ SPO2);
myLabel2.setText("Temp"+" " + Temp);
}
//If Oxiometer is on
if(recDataString.startsWith(#) && recDataString.length() == 10){
//Do Parsing here #779928.08
String BPM = recDataString.substring(1,3);
String SPO2= recDataString.substring(3,5);
String temp = recDataString.substring(5,recDataString.lenth());
myLabel.setText("BPM" + " " + BPM);
myLabel1.setText("SPO2" +" "+ SPO2);
myLabel2.setText("Temp"+" " + Temp);
}
//If String contains # only .
if(recDataString.startsWith(#) && recDataString.length == 1){
//Do nothing or you can decide
}
}

Before recDataString.append(readMessage); try to reset the recDataString first, like this:
recDataString.setLength(0);
Because if it does not reset, it will continue append new strings:
#689928.0
#689928.06899719928.11 ...

Related

Bluetooth issue

I am building an app which connects through bluetooth but the problem is that it is crushing the device when I try to open the activity as the app should transfer the data from arduino to android app and display on it.I am having problem with the default bluetooth device issue when i see it on terminal
Here is the code
public class BlankActivity extends AppCompatActivity {
Button btnOn, btnOff;
TextView txtString, txtStringLength, sensorView0;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensors_layout);
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
//txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
//txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, endOfLineIndex); //get sensor value from string between indices 1-5
//String sensor1 = recDataString.substring(6, 10); //same again...
//String sensor2 = recDataString.substring(11, 15);
//String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Intensity = " + sensor0 + " Raw "); //update the textviews with sensor values
//sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
//sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
//sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Measurement Off!!!", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Please Wait ", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(myUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(MainLayout.EXTRA_ADDRESS);
//create device and set the MAC address //I am having problem here in android monitor
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
// I have problem with this line
****mConnectedThread.write("x");**
}**
#Override
public void onPause() {
super.onPause();
try {
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
This is the crash code when I am facing when I click the button
at de.zmt.photometerapp.BlankActivity$3.onClick(BlankActivity.java:114)

Not able to read any data from Bluetooth device in Android

I am having a bluetooth device . Basically i want my app to connect to the device and receive the data it sends.However so far i am able to connect to the bluetooth device,but i am not able to receive any inputs from it .
here is my problem:
i) DataInputStream.available() always return 0.
ii) If i use any breakpoint on line
bytes = input.read(buffer); // This will freeze doesn't show anything.
and line below it never executes
public class ConnectThread extends Thread{
final String TAG="ConnectThread";
private ReadThread mReadThread = null;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean isDeviceConnected;
public final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket mmSocket = null;
Handler mHandler;
BluetoothDevice bTdevice;
private DataInputStream mReadData = null;
public ConnectThread(BluetoothDevice bTdevice, Handler mHandler) {
super();
this.bTdevice = bTdevice;
this.mHandler = mHandler;
InputStream tmpIn = null;
OutputStream tmpOut = null;
BluetoothSocket socket;
try {
socket = bTdevice.createRfcommSocketToServiceRecord(MY_UUID);
System.out.println("**** Socket created using standard way******");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
mmSocket = socket;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
#Override
public synchronized void run() {
// TODO Auto-generated method stub
super.run();
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
adapter.cancelDiscovery();
Log.i("***Bluetooth Adapter**", "Bluetooth Discovery Canceled");
}
if (mmSocket != null) {
mmSocket.connect();
Log.i("***Socket Connection Successful**", "Socket Connection Successful");
isDeviceConnected = true;
mReadData = new DataInputStream(mmSocket.getInputStream());
Log.i("***Read data**", "" + mReadData);
if (mReadThread == null) {
mReadThread=new ReadThread(mReadData,mmSocket);
mReadThread.start();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("***Error**", "Socket Connection failed");
e.printStackTrace();
try {
mmSocket.close();
isDeviceConnected = false;
} catch (IOException closeException) {
e.printStackTrace();
}
}
// mHandler.obtainMessage(DisplayBtdataActivity.SUCCESS_CONNECT,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
// Read the data from device
private class ReadThread extends Thread {
/** The input. */
private DataInputStream input;
/**
* Constructor for ReadThread.
*
* #param input
* DataInputStream
*/
private BluetoothSocket mSocket;
public ReadThread(DataInputStream input, BluetoothSocket socket) {
this.input = input;
this.mSocket = socket;
}
/**
* Method run.
*
* #see java.lang.Runnable#run()
*/
public synchronized void run() {
try {
Log.d(TAG, "ReadThread run");
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
bytes = input.available(); // always return 0
// bytes = mReadData.readInt();
Log.i("***Bytes data**", "" + bytes);// print 0
Log.i("***Data input stream**", "" + input); // Here input is not null
if (input != null) {
Log.i("***hello world**", "...");
while (isDeviceConnected) {
try {
bytes = input.read(buffer); // this code never executes
Log.i("**bytes data**", " " + bytes);
if (input != null) {
int len = input.readInt();
Log.i(TAG, "Response Length: " + len);
if (len > 65452) {// Short.MAX_VALUE*2
Log.i(TAG, "Error: Accesory and app are not in sync.");
continue;
}
Log.d(TAG, "Response Length: " + len);
Log.d(TAG, "Reading start time:" + System.currentTimeMillis());
byte[] buf = new byte[len];
Log.d(
TAG, "input.available() " + input.available());
if (input.available() > 0) {
input.readFully(buf);
System.out.println("Output:=");
}
Log.d(TAG, "Reading end time:" + System.currentTimeMillis());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
isDeviceConnected = false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
isDeviceConnected = false;
Log.e(TAG, "catch block 3 " + e.toString());
}
}
}
}
In ReadThread.Run() - you have to move the code
bytes = input.available (); // Always return 0
into while loop
1, you use input before checking for null if (input! = null)
2, Data is sent continuously and is a high probability that when running thread do not come any data, so therefore you have to give input.available bytes = (); into a while loop.
3, You can try to modify data processing. In principle, quickly read the data in the temporary buffer, and then move to MainBuffer and then manipulated with it. An example is in c # .net Xamarin, but just for an example :
private const int BTLPacketSize = 1024;
private const int BTLdataSize = 65536;
private System.Object InternaldataReadLock = new System.Object();
private System.Object dataReadLock = new System.Object();
private byte[] InternaldataRead = new byte[BTLPacketSize];//posila 64Byte pakety (resp. 62, protoze 2 jsou status bytes)
private byte[] TempdataRead = new byte[BTLPacketSize];
private byte[] dataRead = new byte[BTLdataSize];//Tyto pameti pouzivaji cursorc -> musim ohlidat preteceni pameti//Max. prenos rychlost je 115200 b/s.
private bool continueRead = true;
public override void Run()
{
while (continueRead)
{
try
{
int readBytes = 0;
lock (InternaldataReadLock)
{//Quick reads data into bigger InternaldataRead buffer and next move only "received bytes" readBytes into TempdataRead buffer
readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length);
Array.Copy(InternaldataRead, TempdataRead, readBytes);
}
if (readBytes > 0)
{//If something reads move it from TempdataRead into main dataRead buffer a send it into MainThread for processing.
lock (dataReadLock)
{
dataRead = new byte[readBytes];
for (int i = 0; i < readBytes; i++)
{
dataRead[i] = TempdataRead[i];
}
}
Bundle dataBundle = new Bundle();
dataBundle.PutByteArray("Data", dataRead);
Message message = btlManager.sourceHandler.ObtainMessage();
message.What = 1;
message.Data = dataBundle;
btlManager.sourceHandler.SendMessage(message);
}
}
catch (System.Exception e)
{
if (e is Java.IO.IOException)
{
//.....
}
}
}
}

How to send data from Arduino to Android

I went to a struggle. There are so many tutorials regarding this topic, but I cannot adapt any of those to my project.
What I want to do is simple:
User press the button in Android (Dialog opens, user enters numbeers, presses ok)
Arduino compares data and if it matches send one message to Android, if no - another.
Concept is this.
What I have so far is simple Arduino code
void loop() {
if (Serial.available() > 0) { // if the data came
incomingByte = Serial.read(); // read byte
if(incomingByte == '0') {
digitalWrite(LED, LOW); // if 1, switch LED Off
Serial.println("LED OFF. Press 1 to LED ON!"); // print message
}
if(incomingByte == '1') {
digitalWrite(LED, HIGH); // if 0, switch LED on
Serial.println("LED ON. Press 0 to LED OFF!");
bluetoothSerial.write
}
}
I found great tutorial for sending data from Arduino to Android, but it's made in Thread mode and I cannot adopt it to my AsyncThread solution. This is the main problem :\
My Android AsyncThread code looks like that:
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ConnectedActivity.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
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
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
Toast.makeText(ConnectedActivity.this, "Connection Failed. Is it a SPP Bluetooth? Try again.", Toast.LENGTH_SHORT).show();
finish();
}
else
{
Toast.makeText(ConnectedActivity.this, "Succeed.", Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
progress.dismiss();
}
}
Solution from the tutorial:
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
btnOff.setEnabled(true);
btnOn.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
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
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
Full tutorial can be found here:
http://solderer.tv/data-transfer-between-android-and-arduino-via-bluetooth/
I can send data from Android to Arduino with no problem. But receiving it.. nope. Any suggestions?
EDITv2
Silly me. I've put handler and thread's code in my activity. And ran
mConnectedThread = new ConnectedThread();
mConnectedThread.start();
in AsyncTask background task. I can see valid toast message now.
Tnx!

java.lang.IllegalArgumentException: Illegal character in query at index 56

This is the error caused after runnung the code
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.lang.Thread.run(Thread.java:841)
03-13 16:43:00.901: E/AndroidRuntime(18994): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 56: http://suprabha.orgfree.com/ecg/temp.php?name=10&temper= 31,w=t
03-13 16:43:00.901: E/AndroidRuntime(18994): at java.net.URI.create(URI.java:727)
03-13 16:43:00.901: E/AndroidRuntime(18994): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
03-13 16:43:00.901: E/AndroidRuntime(18994): at com.example.mobilehealthcare.Temperature$DownloadWebPageTask.doInBackground(Temperature.java:271)
java file
package com.example.mobilehealthcare;
public class Temperature extends Activity {
private static final String TAG = "bluetooth2";
Button btnOn, btnOff;
TextView txtArduino;
Handler h;
private GraphView mGraph;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
// private static String address = "00:12:09:29:42:57";
// private static String address = "00:15:83:15:A3:10";
// private static String address = "20:13:07:12:04:17";
String sdop = "";
String pd = "";
String s1,sa,s1nom,sakom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temperature);
SharedPreferences pre = getSharedPreferences("pref", 0);
s1 = pre.getString("savedDatasd", "10");
s1nom = pre.getString("savedDatad", "10");
mGraph = (GraphView)findViewById(R.id.grap);
txtArduino = (TextView)findViewById(R.id.texView1);
mGraph.setMaxValue(1024);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
// int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
int endOfLineIndex = sb.indexOf("/");
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
Toast.makeText(getApplicationContext(), "received message"+"----"+sbprint, 30).show();
sb.delete(0, sb.length()); // and clear
txtArduino.setText(sbprint); // update TextView
// final int s = Integer.parseInt(sbprint);
// mGraph.addDataPoint(s);
sdop+= txtArduino.getText().toString()+",";
}
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
public void tyre(View v)
{
mConnectedThread.write("t");
Toast.makeText(this, "waid for values to be received", Toast.LENGTH_SHORT).show();
}
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();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(s1);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
SharedPreferences preferences = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = preferences.edit();
//"savedData" is the key that we will use in onCreate to get the saved data
//mDataString is the string we want to save
// editor.putString("savedDatasd", sa);
// editor.putString("savedDatad", sakom);
// commit the edits
editor.commit();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} 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
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
public void bus(View v)
{
Intent jkl = new Intent(this,Select.class);
startActivity(jkl);
finish();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
//msg.setText(result);
if (result.contains("success")) {
Toast.makeText(getApplicationContext(), "Values are isent to Doctor", 30).show();
}else{Toast.makeText(getApplicationContext(), "Values are not sent to Doctor", 30).show();}
}
}
public void sav(View v)
{
String e = "t";
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://suprabha.orgfree.com/ecg/temp.php?name="+s1nom+"&temper="+sdop+"w="+e });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.temperature, menu);
return true;
}
}
Is it due to the php code?
or is the error in this java file.?
Which charater should be changed?
The error is in download web page task.
Edit:
This is the other code with same concept:
this works without error
public class Register extends Activity {
EditText a,b,c,d,e,f,g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
a = (EditText) findViewById(R.id.editname1);
b = (EditText) findViewById(R.id.editpas1);
c = (EditText) findViewById(R.id.age);
d = (EditText) findViewById(R.id.editph1);
e = (EditText) findViewById(R.id.editadd1);
f = (EditText) findViewById(R.id.editem1);
g = (EditText) findViewById(R.id.dph);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
//msg.setText(result);
if (result.contains("success")) {
Intent i2 = new Intent(getApplicationContext(), Login.class);
//i.putExtra("id",na);
startActivity(i2);
}else{Toast.makeText(getApplicationContext(), result, 30).show();}
}
}
public void insert(View v)
{
String h,i,j,k,l,m,n;
h = a.getText().toString();
i = b.getText().toString();
j = c.getText().toString();
k = d.getText().toString();
l = e.getText().toString();
m = f.getText().toString();
n = g.getText().toString();
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://suprabha.orgfree.com/ecg/regis.php?name="+h+"&pass="+i+"&age="+j+"&ph="+k+"&addr="+l+"&em="+m+"&docph="+n });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register, menu);
return true;
}
}
seems to me that the query url "__http://suprabha.orgfree.com/ecg/temp.php?name=10&temper= 31,w=t" is where the program is encountering problem.
the 56th character is "=" which shouldnt be unexpected. However the spaces before the "31" in the string, can those be a point of concern?
If the spaces are not required as per your design, i would suggest you to remove and try it. If, they are however required, i would suggest escaping it before using the same.
Hope it helps.
note: ignore the undescores before the url. did that to prevent hyperlinking.
Problem are the blank spaces after the = symbol. You can avoid this simply with String:trimm(), but won't solve other problems, so, to avoid this, with URL's use java.net.URLEncoder to fit your needed enconding, for example:
URLEncoder.encode(url, "UTF-8");
In your case:
HttpGet httpGet = new HttpGet(URLEncoder.encode(url, "UTF-8"));

I cannot cancel my thread in Android

I am developing an app that communicated with Arduino via bluetooth, however, I dont know why I cannot cancel the thread which responsible for the bluetooth inputstream.
public class mainclass extends Activity{
BluetoothSocket scSocket = AnotherClass.btSocket;
SendReceiveBytes sendReceiveBT;
Thread th;
protected void onCreate(Bundle savedInstanceState) {
.
.
sendReceiveBT = new SendReceiveBytes(scSocket);
th = new Thread(sendReceiveBT);
th.start();
.
.
sendReceiveBT.stop=true;
Log.e(TAG, "Request sent");
.
.
}
}
public class SendReceiveBytes implements Runnable {
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
private OutputStream btOutputStream = null;
public boolean stop=false;
public boolean stopped=false;
String TAG = "SendReceiveBytes";
public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (!stop) {
try {
// Read from the InputStream
bytes = btInputStream.read(buffer);
// Send the obtained bytes to the UI activity
byte[] readBuf = (byte[]) buffer;
// construct a string from the valid bytes in the buffer
readMessage = new String(readBuf, 0, bytes);
}
catch (IOException e) {
Log.e(TAG, "Error reading from btInputStream");
break;
}
}
Log.e(TAG, "Quit");
stopped=true;
}
}
In the LogCat, the tag with "Request sent" is shown which means I already set the "stop" to true, however, the tag with "Quit" never show up.
You could try to override the stop()-method, which set stop-flag to true. Also make sure to close your streams.

Categories

Resources