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

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"));

Related

file transfer through Wifi Direct

I am trying to write an android application that streams images taken from a first device, through the camera, to a second device with WiFi Direct.
I am trying to use this GitHub project, WiFiDIrectDemo, I managed to connect the devices and to send just one file.
When I try to send a second file I don't get any error and, from the logs, everything seems to work, but the second device doesn't get any file.
Is this a known issue? I have tried to look on the internet but I could not find anything that could help me.
I am attaching my File Transfer Service class:
public class FileTransferService extends IntentService {
Handler mHandler;
public static final int SOCKET_TIMEOUT = 50000; //ms
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public static int PORT = 8888;
public static final String inetaddress = "inetaddress";
public static final int ByteSize = 512;
public static final String Extension = "extension";
public static final String Filelength = "filelength";
public FileTransferService(String name) {
super(name);
}
public FileTransferService() {
super("FileTransferService");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
InputStream is = null;
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
String extension = intent.getExtras().getString(Extension);
String filelength = intent.getExtras().getString(Filelength);
try {
if(!socket.isConnected())
{
Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.setReuseAddress(true);
socket.connect((new InetSocketAddress(host, port)),5000); // ..,socket_timeout)
Log.e("File Transfer Service"," socket connect");
}
Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
Log.e("file transfer" +
" service", "get output stream");
ContentResolver cr = context.getContentResolver();
Long FileLength = Long.parseLong(filelength);
WiFiTransferModal transObj = null;
ObjectOutputStream oos = new ObjectOutputStream(stream);
if(transObj == null) transObj = new WiFiTransferModal();
transObj = new WiFiTransferModal(extension,FileLength);
oos.writeObject(transObj);
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
}
DeviceDetailFragment.copyFile(is, stream);
Log.d(WiFiDirectActivity.TAG, "Client: Data written");
oos.flush();
oos.close(); //close the ObjectOutputStream after sending data.
} catch (IOException e) {
Log.e("file transfer service","unable to connect: " + e.toString() );
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (Exception e) {
// Give up
e.printStackTrace();
Log.e("File transfer service","exception socket.close: " + e.toString());
}
}
}
else Log.e("file transfer service","socket is already null");
}
}
}
}
EDIT
Receiving code:
public class FileServerAsyncTask extends AsyncTask<String, String, String> {
// private TextView statusText;
private Context mFilecontext;
private String Extension, Key;
private File EncryptedFile;
private long ReceivedFileLength;
private int PORT;
public FileServerAsyncTask(Context context, int port) {
this.mFilecontext = context;
handler = new Handler();
this.PORT = port;
}
#Override
protected String doInBackground(String... params) {
try {
Log.e("device detail fragment", "File Async task port-> " + PORT);
ServerSocket serverSocket = new ServerSocket();
Log.e("device detail fragment"," new server");
serverSocket.setReuseAddress(true);
Log.e("device detail fragment","set reuse address");
serverSocket.bind(new InetSocketAddress(PORT));
Log.e("device detail fragment","socket bind");
Socket client = serverSocket.accept();
Log.e("device detail fragment "," socket client accept");
Log.e("Device detail fragment ", "client inet address" + client.getInetAddress());
WiFiClientIp = client.getInetAddress().getHostAddress();
Log.e("device detail fragment"," get client ip: " + WiFiClientIp);
ObjectInputStream ois = new ObjectInputStream(
client.getInputStream());
Log.e("device detail fragment","object input stream + " + ois.toString());
WiFiTransferModal obj = null;
String InetAddress;
try {
obj = (WiFiTransferModal) ois.readObject();
Log.e("device detail fragment"," read object");
if (obj != null) {
Log.e("device detail fragment"," obj != null ");
InetAddress = obj.getInetAddress();
Log.e("device detail fragment"," get inet address: " +
InetAddress);
if (InetAddress != null
&& InetAddress
.equalsIgnoreCase(FileTransferService.inetaddress)) {
SharedPreferencesHandler.setStringValues(mFilecontext,
mFilecontext.getString(R.string.pref_WiFiClientIp), WiFiClientIp);
//set boolean true which identify that this device will act as server.
SharedPreferencesHandler.setStringValues(mFilecontext,
mFilecontext.getString(R.string.pref_ServerBoolean), "true");
ois.close(); // close the ObjectOutputStream object
Log.e("device detail fragment"," output stream close");
// after saving
serverSocket.close();
Log.e("device detail fragment","close");
return "Demo";
}
Log.e("device detail fragment","FileName got from socket on other side->>> "+
obj.getFileName());
}
final File f = new File(
Environment.getExternalStorageDirectory() + "/"
+ FolderName + "/"
+ obj.getFileName());
Log.e("background"," new file f from inputstream");
File dirs = new File(f.getParent());
Log.e("device detail fragment"," f get parent()");
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.e("device detail fragment","create new file");
/**
* Receive file length and copy after it
*/
this.ReceivedFileLength = obj.getFileLength();
InputStream inputstream = client.getInputStream();
Log.e("device detail fragment","input stream client get input");
Message msg = Message.obtain();
msg.what = 1;
try
{
// send the images to the image view through handler
Bitmap bitmap = BitmapFactory.decodeStream(inputstream);
Log.e("device detail fragment", "decode stream");
Bundle b = new Bundle();
b.putParcelable("bitmap", bitmap);
msg.setData(b);
Log.e("device detail fragment","message: " + msg.toString());
messageHandler.sendMessage(msg);
}
catch (Exception e)
{
Log.e("device detail fragment","stream not decoded into bitmap with" +
"exception: " + e.toString());
}
copyRecievedFile(inputstream, new FileOutputStream(f),
ReceivedFileLength);
Log.e("device detail fragment","copy input stream into file");
ois.close(); // close the ObjectOutputStream object after saving
// file to storage.
Log.e("device detail fragment","ois close");
/**
* Set file related data and decrypt file in postExecute.
* */
this.Extension = obj.getFileName();
this.EncryptedFile = f;
final Uri uri = Uri.fromFile(f);
return f.getAbsolutePath();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
Log.e("device detail fragment", e.getMessage());
}
return "";
} catch (IOException e) {
Log.e("device detail fragment", e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
if (!result.equalsIgnoreCase("Demo")) {
Log.e("On Post Execute","result +" + result);
} else if (!TextUtils.isEmpty(result)) {
/**
* To initiate socket again we are initiating async task
* in this condition.
*/
FileServerAsyncTask FileServerobj = new
FileServerAsyncTask(mFilecontext, FileTransferService.PORT);
if (FileServerobj != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
FileServerobj.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
Log.e("Post Execute", "FileServerobj.execute on executor");
} else
{
FileServerobj.execute();
Log.e("Post Execute", "FileServerobj.execute");
}
}
}
}
}
#Override
protected void onPreExecute() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(mFilecontext);
}
if(imageView == null){
imageView = new ImageView(mFilecontext);
}
}
}
The server will receive a file and then opens it by letting the user choose an app to display the file. The server asynctask then has finished. So no new file can be received. So i do not believe you if you say that the logs tell that all is normal. Your client socket can not connect to begin with. All is intented behaviour.
* To initiate socket again we are initiating async task * in this condition..
Your code is not coming there.
You have to start an asynctask again to receive the next file.

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)

Textview values does not update when data received from Arduino

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 ...

Passing special characters over socket connection

I have built a chat application in Android powered by sockets. The messages send and receive fine, so long as the user does not send messages with special characters, ie. Hey, it's me, will not work, but Hey its me, will, the comma and apostrophe prevent the message from being delivered.
I attempted using URLEncoder, but that did not allow the unique characters to be sent.
Sending message method:
public String sendMessage(String username, String tousername, String message, String campaign_id, String location_id)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&to=" + URLEncoder.encode(tousername, "UTF-8")
+ "&message=" + URLEncoder.encode(message, "UTF-8")
+ "&campaign_id=" + URLEncoder.encode(campaign_id, "UTF-8")
+ "&location_id=" + URLEncoder.encode(location_id, "UTF-8")
+ "&action=" + URLEncoder.encode("sendMessage", "UTF-8")
+ "&gcmregid=" + gcmRegistrationID
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
with
SocketerInterface socketOperator = new Socketer(this);
and Socketer class as:
public class Socketer implements SocketerInterface {
// Have to set the proper ports that apache is runnign on as well as your
// computers IP address: ie. ip:4430 or 800
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://"
// + ipAddress.getIpAddress() + ":80/AndroidChatterDatabase/"; // Google Compute Engine Access
//+ ipAddress.getIpAddress() + ":4430/AndroidChatterDatabase/"; // Localhost access
+ ipAddress.getFeastChatServer(); // For Heroku access
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new
// PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.v("XML MESSAGE", inputLine);
if (inputLine.equals("exit") == false) {// as long as have
// noted exited yet,
// will continuing
// reading in
Log.v("XML MESSAGE", inputLine);
// appManager.messageReceived(inputLine);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket
.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ", "");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params) {
URL url;
String result = new String();
try {
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
// Testing to remove <head/> tag from Google App Engine
//return result.replace("<head/>","");
return result;
}
public int startListening(int portNo) {
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
// e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
// e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket",
"Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening() {
this.listening = false;
}
public void exit() {
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator
.hasNext();) {
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e) {
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}
How can I format/encode to allow sending these messages?
Java uses UTF-16 for internal String representation, but it looks like you are using UTF-8, but you aren't doing anything special to convert it from UTF-8 when reading it from BufferedReader. In the params, try specifying UTF-16 instead.
From the Java String documentation:
A String represents a string in the UTF-16 format

how to avoid an application hanging while calculating two functions together?

float totalKm = Contsants.jobEndKm-Contsants.jobStartKm ;
jcTotalKms.setText(String.format("%.2f",totalKm));
//jcTotalKms.setText(Float.toString((float) (totalKm/16.0)));
//finding total fare here
//int value=100;
if (totalKm<Contsants.minDist)
{
jcWaitingFare.setText("0");
float totalfare=Contsants.minFare;
jcTotalFare.setText(String.format("%.2f",(totalfare)));
Contsants.jobTotalKm= totalKm;
Contsants.jobTotalFare=totalfare;
}
else
{
jcWaitingFare.setText(Integer.toString((Contsants.cont_WaitingTimeInSec/60)*1));
float totalfare= Contsants.minFare+ ((totalKm-Contsants.minDist) *Contsants.rupeeKm) +(Contsants.cont_WaitingTimeInSec/60)*1;
jcTotalFare.setText(String.format("%.2f",(totalfare)));
Contsants.jobTotalKm= totalKm;
Contsants.jobTotalFare=totalfare;
}
tcpsocket class
public class tcpSocket extends Thread{
static boolean startSocket=false;
public static final String SERVERIP = "ip address here"; //your computer IP address
public static final int SERVERPORT = 8900;
private static boolean mRun = false;
public static Socket socket;
public static OnMessageReceived mMessageListener;
public static OnMessageReceived getmMessageListener() {
return mMessageListener;
}
public static void setmMessageListener(OnMessageReceived mMessageListener) {
tcpSocket.mMessageListener = mMessageListener;
}
public tcpSocket()
{
}
#Override
public void run(){
//some long operation
startSocket=true;
while(startSocket)
{
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.d("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
Log.d("TCP Client", "C: Sent.");
Log.d("TCP Client", "C: Done.");
final OutputStream out =socket.getOutputStream();
writeResponse(out, "$0001~01~"+Contsants.Cont_IMEINo+"~Version#");
//in this while the client listens for the messages sent by the server
final InputStream in = socket.getInputStream();
while(!mRun)
{
if (!(in.available() > 0)) {
goSleep(2000);
continue;
}
processClient(in);
}
}catch (Exception e) {
// TODO: handle exception
}finally{
socket.close();
}
} catch (Exception e) {
Log.d("tcp error",e.toString());
// TODO: handle exception
}
}
}
private void goSleep(final long milliSec) {
try {
Thread.sleep(milliSec);
} catch (final InterruptedException e) {
Log.e("server conn Thread ","Sleeping client interrupted" + e);
}
}
private void processClient(final InputStream in) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
final char[] cbuf = new char[1024];
final int length = reader.read(cbuf);
if (length <= 0) {
Log.d("d","No data read from client.");
return;
}
cbuf[length] = '#';
String packet = new String(cbuf, 0, length + 1);
if (!packet.startsWith("$") && !packet.contains("#")) {
Log.d("d","Invalid packet recieved: " + packet);
return;
}
try
{
if(!packet.contains("$0002") && !packet.contains("$0423"))
{
final String [] packetDo=packet.split("\\~");
writeResponse(socket.getOutputStream(), "$102~"+packetDo[1]+"~"+Contsants.Cont_IMEINo+"#");
}
Log.d("d","Recived packet is :"+packet);
Message msg = new Message();
Bundle b = new Bundle();
b.putString("ServerMsg", packet);
msg.setData(b);
// send message to the handler with the current message handler
mHandler.sendMessage(msg);
}catch (Exception e) {
// TODO: handle exception
Log.e("TCP", "p: Error", e);
}
}
Handler mHandler =new Handler(){
#Override
public void handleMessage(Message message){
//update UI
Bundle b = message.getData();
final String data =b.getString("ServerMsg");
mMessageListener.messageReceived(data);
}
};
/*public class MyAsync extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
String response = null;
return SendMessage(response);
}
}
public static boolean SendMessage(final String response) {
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out, response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun = true;
return false;
}
return true;
}
*/
public static boolean SendMessage(final String response)
{
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out,response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun=true;
return false;
}
return true;
}
private static void writeResponse(final OutputStream out, final String response) throws IOException {
// logger.info("Sending response to client: " + response);
out.write(response.getBytes());
out.flush();
}
}
here is my code for calculating distance and fare together when the condition exceeds minimum(minDist) kilometer. But while checking this application in real device it hangs up after two kilometer. Because after two kilometer it goes to else condition part. i don't know how to solve this issue.

Categories

Resources