Changing String from buffer to int - java

So another one from the same code with another problem.
here is the code
package com.test.aplikasirevisi;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import static com.test.aplikasirevisi.Information.Highest;
import static com.test.aplikasirevisi.Information.Lowest;
import static com.test.aplikasirevisi.Information.mypreference;
public class MonitoringScreen extends Activity {
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
TextView highest;
TextView lowest;
private boolean mIsUserInitiatedDisconnect = false;
private TextView mTxtReceive;
private Button mBtnClearInput;
private Button mBtnGetBPM;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_screen);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
mTxtReceive = (TextView) findViewById(R.id.txtReceive);
chkScroll = (CheckBox) findViewById(R.id.chkScroll);
chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
scrollView = (ScrollView) findViewById(R.id.viewScroll);
mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
mBtnGetBPM = (Button) findViewById(R.id.mBtnGetBPM);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
mBtnClearInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mTxtReceive.setText("");
}
});
}
private class ReadInput implements Runnable{
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
String getHi = null;
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
getHi=highest.getText().toString();
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
int hi = Integer.parseInt(getHi);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
if (chkReceiveText.isChecked()) {
mTxtReceive.post(new Runnable() {
#Override
public void run() {
mTxtReceive.append(strInput);
System.out.println(strInput);
if(data < hi){
Log.d(TAG, "succes");
}
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
Log.d(TAG, "text longer than allowed:" + mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars));
}
if (chkScroll.isChecked()) { // Scroll only if this is checked
scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
#Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
}
});
}
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
}
i want to change the String to int from this part:
final String strInput = new String(buffer, 0, i);
so i can use it on this part :
if(data < hi){
Log.d(TAG, "succes");
}
i tried to use
int data = Integer.parseInt(strInput);
but well of course it span error because its string buffer and only the first one is changed
so how do i solve this prob?if any one can help
I already tried using arraylist but still error
Here is the error code :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.aplikasirevisi, PID: 21905
java.lang.NumberFormatException: For input string: "40
"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.test.aplikasirevisi.MonitoringScreen$ReadInput$1.run(MonitoringScreen.java:152)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I/Process: Sending signal. PID: 21905 SIG: 9

The error message is telling you what is wrong. Your input appears to be "40 and " is not a numeric character. You need make sure your inputted strings are numeric OR you need to extract the numeric component from the string BEFORE attempting to convert it into an integer. You could try new String(buffer, 1, i) if the character at index 0 is always the double quote character.
UPDATE:
Based on your last comment posted here, you need to initialize your strInput as follows (This is an example):
byte[] bytes = new byte[5];
bytes[0] = 49; // this is the ASCII value of the number "1"
bytes[1] = '\u0000'; // These are null characters
bytes[2] = '\u0000';
bytes[3] = '\u0000';
bytes[4] = '\u0000';
String temp = new String(bytes); // convert the byte array to String
String str = temp.substring(0, temp.indexOf('\u0000')); // parse the numeric contents
System.out.println(str); // You should see "1" printed out
int number = Integer.parseInt(str); // Because I parsed the numeric contents, it is safe to convert the String to a number.

Related

Attempt to invoke virtual method 'java.io.InputStream android.bluetooth.BluetoothSocket.getInputStream()'

I am trying to connect my android app with hc-06 for sending and receiving data purpose, below is the error occur and I've been stuck here from 3 days.
There error occured to me is
Attempt to invoke virtual method 'java.io.InputStreamandroid.bluetooth.BluetoothSocket.getInputStream()'
Kindly somebody solve it or provide me another working code for sending and receiving data through bluetoth hc-06 android app
package infoaryan.in.hc05_bluetooth;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class LedControl extends AppCompatActivity {
TextView textView;
Button btn1, btn2, btn3, btn4, btn5, btnDis;
String address = null;
TextView lumn;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
InputStream mmInputStream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_led_control2);
Intent intent = getIntent();
address = intent.getStringExtra(MainActivity.EXTRA_ADDRESS);
btn1 = findViewById(R.id.button2);
btn2 = findViewById(R.id.button3);
//For additional actions to be performed
btn3 = findViewById(R.id.button5);
btn4 = findViewById(R.id.button6);
btn5 = findViewById(R.id.button7);
btnDis = findViewById(R.id.button4);
lumn = findViewById(R.id.textView2);
textView = findViewById(R.id.textView3);
new LedControl.ConnectBT().execute();
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("0");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
sendSignal("5");
}
});
btnDis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Disconnect();
}
});
beginListenForData();
}
private void sendSignal ( String givenumber ) {
if ( btSocket != null ) {
try {
btSocket.getOutputStream().write(givenumber.getBytes());
} catch (IOException e) {
msg("Error");
}
}
}
private void Disconnect () {
if ( btSocket!=null ) {
try {
btSocket.close();
} catch(IOException e) {
msg("Error");
}
}
finish();
}
private void msg (String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean ConnectSuccess = true;
#Override
protected void onPreExecute () {
progress = ProgressDialog.show(LedControl.this, "Connecting...", "Please Wait!!!");
}
#Override
protected Void doInBackground (Void... devices) {
try {
if ( btSocket==null || !isBtConnected ) {
myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
} catch (IOException e) {
ConnectSuccess = false;
}
return null;
}
#Override
protected void onPostExecute (Void result) {
super.onPostExecute(result);
if (!ConnectSuccess) {
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
} else {
msg("Connected");
isBtConnected = true;
}
progress.dismiss();
}
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
textView.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
#Override
protected void onResume() {
super.onResume();
}
}

Getting the value from textview

Hello guys I got a code that I do for my project, the code is to get the value of the heartbeat sensor from Arduino to my android phone using Bluetooth. So far it's going well it can send the value to my app without a problem. but the problem now is I want to get the value of it so I can use my algorithm with it, but seems like I got in a pickle now.
Here is the code :
package com.test.aplikasirevisi;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class MonitoringScreen extends Activity {
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private boolean mIsUserInitiatedDisconnect = false;
private TextView mTxtReceive;
private Button mBtnClearInput;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_screen);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
mTxtReceive = (TextView) findViewById(R.id.txtReceive);
chkScroll = (CheckBox) findViewById(R.id.chkScroll);
chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
scrollView = (ScrollView) findViewById(R.id.viewScroll);
mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnClearInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mTxtReceive.setText("");
}
});
}
private class ReadInput implements Runnable{
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
if (chkReceiveText.isChecked()) {
mTxtReceive.post(new Runnable() {
#Override
public void run() {
mTxtReceive.append(strInput);
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
System.out.println(mTxtReceive.getText().toString());
}
if (chkScroll.isChecked()) { // Scroll only if this is checked
scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
#Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
}
});
}
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
}
What i want is to get the value of mTxtReceive on this :
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
System.out.println(mTxtReceive.getText().toString());
}
I used System.out.println for seeing if i got the value but in the log it didn't show any thing.
So i need you guys wisdom for this any help?
Your view mTextReceive seems to be a TextView and therefore not editable:
private TextView mTxtReceive;
If it's not an EditText (editable) mTxtReceive.getEditableText will return null see docs
and getText should be called instead see docs.
Therefore your condition might always resolve from
if(txtLength > mMaxChars) into if(null > 50000) which is always false (or actually it might even crash before) and therefore your code inside the if-block is never executed
Try:
// recommended for debugging. Check if this is even called and if text length is really longer than max chars
Log.d(TAG, "text length:" + mTxtReceive.getText().length());
int txtLength = mTxtReceive.getText().length();
if(txtLength > mMaxChars){
// not sure what operation you want to do here but leave out for debugging
Log.d(TAG, "text longer than allowed:" + mTxtReceive.getText().toString());
}
Also use Log.d instead of System.out.println since your log might otherwise not be forwarded to Logcat. Also are you sure this block is executed at all? I'd put a Log.d(TAG, "text length:" + mTxtReceive.getText().length()); outside of the condition for debugging purposes. And finally the obvious question would be if the txtLength is even longer than max chars (and that would be quite a long text with 50000 chars). But you can verify that simply with the recommended log outside the block as well.

Bluetooth communication in Android Cant get the message

I am trying to make a link (bluetooth) between my arduino and android. i want to recieve the data from the arduino. The ListenInput thread does get started but nothing more
Here is my code
package com.codeyard.teleprompter;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class bleutoothrevivedeletenow extends AppCompatActivity {
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String address = null;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
Button StartConnection;
Button Disconnect;
Button Recieve;
TextView incomingData;
InputStream mmInStream = null;
String incomingMessage;
StringBuilder messages;
Thread ListenInput = new Thread() {
#Override
public void run() {
try {
mmInStream = btSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytes;
Toast.makeText(getApplicationContext(), "Thread started///", Toast.LENGTH_LONG).show();
while (true) {
// Read from the InputStream
try {
if (mmInStream == null) {
Log.e("", "InputStream is null");
}
bytes = mmInStream.read(buffer);
incomingMessage = new String(buffer, 0, bytes);
messages.append(incomingMessage);
Toast.makeText(getApplicationContext(), "incoming message", Toast.LENGTH_LONG).show();
Toast.makeText(bleutoothrevivedeletenow.this, incomingMessage, Toast.LENGTH_LONG).show();
//TODO Remove this
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "128", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "133", Toast.LENGTH_SHORT).show();
}
}
};
private boolean isBtConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bleutoothrevivedeletenow);
messages = new StringBuilder();
SharedPreferences sharedPreferences;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(bleutoothrevivedeletenow.this);
address = sharedPreferences.getString("ADDRESS", "");
StartConnection = findViewById(R.id.button5);
Disconnect = findViewById(R.id.button6);
incomingData = findViewById(R.id.textView);
Recieve = findViewById(R.id.button7);
StartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ConnectBT().execute();
}
});
Disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (btSocket != null) //If the btSocket is busy
{
try {
btSocket.close(); //close connection
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
}
});
Recieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListenInput.start();
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
incomingData.setText(messages);
handler.postDelayed(this, 2000);
}
};
runnable.run();
}
});
}
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() {
Toast.makeText(getApplicationContext(), "Connecting....", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_PRIVILEGED}, 1);
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(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
}
}
}
P.S. i have provided the entire code. this code is actually of this github repo:
https://github.com/IamMayankThakur/android-arduino-using-bluetooth
The code first genereated a IllegalThreadException but after debugging i edited the code and now it doesn't crash but still no incoming data

Android telnet client through apache commons

I am fairly new to Android, i want to write a telnet client app for my Android. I have written the code using Apache commons library for telnet. Now i am able to connect to telnet server (for that i have used Asyctask concept) and able to read login banner after a long time i don't know what is causing that. I have modified the example given in Apache commons to work with my android code.I have two java codes in my "src" folder (MainActivity.java and TelnetClientExample.java). First, i want to get the login prompt and then i want user to interact with it please help, Thanks in advance :)
I am posting my screen capture of what i am getting.
MainActivity.java
package com.example.telnetapp;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity{
public static int port_int_address;
private EditText server,port;
private Button connect;
public static String ip,port_address;
public PrintWriter out;
public static TextView textResponse;
static String response;
public InputStream instr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server = (EditText)findViewById(R.id.edittext1);
port = (EditText)findViewById(R.id.edittext2);
connect = (Button)findViewById(R.id.connect);
textResponse = (TextView)findViewById(R.id.response);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ip = server.getText().toString();
port_address = port.getText().toString();
port_int_address = Integer.parseInt(port_address);
try{
MyClientTask task = new MyClientTask(ip, port_int_address);
task.execute();
}
catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
TelnetClientExample job;
MyClientTask(String inetAddress, int port){
dstAddress = inetAddress;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
job = new TelnetClientExample();
job.backgroundjob();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try {
instr = TelnetClientExample.tc.getInputStream();
byte[] buff = new byte[1024];
int ret_read = 0;
do
{
ret_read = instr.read(buff);
if(ret_read > 0)
{
MainActivity.response += new String(buff, 0, ret_read);
}
}
while (ret_read >= 0);
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from telnet server ! \n";
}
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
TelnetClientExample.java
package com.example.telnetapp;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.telnet.TelnetClient;
public class TelnetClientExample {
public String remoteip = MainActivity.ip;
public int remoteport= MainActivity.port_int_address;
public static TelnetClient tc = null;
public void backgroundjob() throws IOException {
tc = new TelnetClient();
try {
tc.connect(remoteip, remoteport);
}
catch (Exception e) {
}
}
public void close_con(){
try {
tc.disconnect();
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from disconnecting telnet server ! \n";
}
}
}
The problem is in this code snippet . please look into this and help me to get an interactive session.
protected void onPostExecute(Void result) {
try {
instr = TelnetClientExample.tc.getInputStream();
byte[] buff = new byte[1024];
int ret_read = 0;
do
{
ret_read = instr.read(buff);
if(ret_read > 0)
{
MainActivity.response += new String(buff, 0, ret_read);
}
}
while (ret_read >= 0);
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from telnet server ! \n";
}
textResponse.setText(response);
super.onPostExecute(result);
}
The problem i am getting -

When I trying to Click on Paired device list of bluetooth then it will unfortunately , MyApp has stopped message display and my application is closed

When I click on paired device list of Bluetooth, application crashes , and I get a message saying 'MyApp has stopped
When I start my application first time it doesn't show my Paired devices in paired devices list but when i switch off the display and switch it on again it shows.
package com.example.bluetoothapp;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch, buttonOn, buttonDesc, buttonOff;
ArrayAdapter<String> adapter, detectedAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth
* devices; this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
adapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView txt = (TextView) arg1;
Toast.makeText(MainActivity.this,
"" + txt.getText().toString(), 1000).show();
}
});
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if (pairedDevice.size() > 0) {
for (BluetoothDevice device : pairedDevice) {
arrayListpaired.add(device.getName() + "\n"
+ device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
}
class ListItemClicked implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
// bdClass = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : " + bdDevice.toString());
/*
* here below we can do pairing without calling the callthread(), we
* can directly call the connect(). but for the safer side we must
* usethe threading object.
*/
// callThread();
// connect(bdDevice);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if (isBonded) {
// arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
getPairedDevices();
}
} catch (Exception e) {
e.printStackTrace();
}// connect(bdDevice);
Log.i("Log", "The bond is created: " + isBonded);
}
}
class ListItemClickedonPaired implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBonding = removeBond(bdDevice);
if (removeBonding) {
arrayListpaired.remove(position);
}
Log.i("Log", "Removed" + removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* private void callThread() { new Thread(){ public void run() { Boolean
* isBonded = false; try { isBonded = createBond(bdDevice); if(isBonded) {
* arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
* adapter.notifyDataSetChanged(); } } catch (Exception e) { // TODO
* Auto-generated catch block e.printStackTrace(); }//connect(bdDevice);
* Log.i("Log", "The bond is created: "+isBonded); } }.start(); }
*/
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);// , args);// this invoke
// creates the detected
// devices paired.
// Log.i("Log", "This is: "+bool.booleanValue());
// Log.i("Log", "devicesss: "+bdDevice.getName());
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice) throws Exception {
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice) throws Exception {
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT)
.show();
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
// device.getClass().getMethod("setPairingConfirmation",
// boolean.class).invoke(device, true);
// device.getClass().getMethod("cancelPairingUserInput",
// boolean.class).invoke(device);
} catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if (arrayListBluetoothDevices.size() < 1) // this checks if the
// size of bluetooth
// device is 0,then
// add the
{ // device to the arraylist.
detectedAdapter.add(device.getName() + "\n"
+ device.getAddress());
arrayListBluetoothDevices.add(device);
} else {
boolean flag = true; // flag to indicate that particular
// device is already in the arlist
// or not
for (int i = 0; i < arrayListBluetoothDevices.size(); i++) {
if (device.getAddress().equals(
arrayListBluetoothDevices.get(i).getAddress())) {
flag = false;
}
}
if (flag == true) {
detectedAdapter.add(device.getName() + "\n"
+ device.getAddress());
arrayListBluetoothDevices.add(device);
}
}
}
}
};
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
MainActivity.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth() {
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
}

Categories