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

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();
}
}

Related

Changing String from buffer to int

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.

Application has Stoppped (Android Studio Bluetooth)

I try to make communication between two devices by using Bluteooth but always the application stopped when i try to test it.
I just try to send simple string (for exemple 'A') but also I have errors.
Also i can't turn on/off bluetooth manually.
the error is : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at com.example.pfe.reglages.onCreate(reglages.java:53).
I need help because it's my project to get graduated
Thank you.
entrainement.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import static android.bluetooth.BluetoothAdapter.getDefaultAdapter;
import static android.content.ContentValues.TAG;
public class entrainement extends AppCompatActivity {
private boolean CONTINUE_READ_WRITE = true;
private boolean CONNECTION_ENSTABLISHED = false;
private boolean DEVICES_IN_LIST = true;
private static String NAME = "pfe.fawez";
private static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
Button btn6, btn7, btn8, btn16, btn9, btn5;
EditText txt;
TextView logview;
ListView lv;
ArrayList<String> listItems;
ArrayAdapter<String> listAdapter;
private BluetoothAdapter adapter;
private BluetoothSocket socket;
private InputStream is;
private OutputStream os;
private BluetoothDevice remoteDevice;
private Set<BluetoothDevice> pairedDevices;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entrainement);
btn6 = findViewById(R.id.button6);
btn7 = findViewById(R.id.button7);
btn8 = findViewById(R.id.button8);
btn16 = findViewById(R.id.button16);
btn9 = findViewById(R.id.button9);
btn5 = findViewById(R.id.button5);
txt = findViewById(R.id.editText2);
logview = findViewById(R.id.textView14);
lv = (ListView)findViewById(R.id.listView);
listItems = new ArrayList<String>(); //shows messages in list view
listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() //list onclick selection process
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(DEVICES_IN_LIST)
{
String name = (String) parent.getItemAtPosition(position);
selectBTdevice(name); //selected device will be set globally
//Toast.makeText(getApplicationContext(), "Selected " + name, Toast.LENGTH_SHORT).show();
//do not automatically call OpenBT(null) because makes troubles with server/client selection
}
else //message is selected
{
String message = (String) parent.getItemAtPosition(position);
txt.setText(message);
}
}
/*adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) //If the adapter is null, then Bluetooth is not supported
{
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_SHORT).show();
finish();
return;
}
list(null);*/
});
btn9.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = txt.getText().toString();
byte[] b = textToSend.getBytes();
try {
os.write(b);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
logview.append("\nConnection !\n");
}
});
btn6.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "R";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn16.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "L";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn7.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "X";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn8.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "Y";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
}
private Runnable writter = new Runnable() {
#Override
public void run() {
while (CONTINUE_READ_WRITE) //reads from open stream
{
try
{
os.flush();
Thread.sleep(2000);
} catch (Exception e)
{
Log.e(TAG, "Writer failed in flushing output stream...");
CONTINUE_READ_WRITE = false;
}
}
}
};
public void list(View v) //shows paired devices to UI
{
CONNECTION_ENSTABLISHED = false; //protect from failing
listItems.clear(); //remove chat history
listAdapter.notifyDataSetChanged();
pairedDevices = adapter.getBondedDevices(); //list of devices
for(BluetoothDevice bt : pairedDevices) //foreach
{
listItems.add(0, bt.getName());
}
listAdapter.notifyDataSetChanged(); //reload UI
}
public void selectBTdevice(String name) //for selecting device from list which is used in procedures
{
if(pairedDevices.isEmpty()) {
list(null);
Toast.makeText(getApplicationContext(), "Selecting was unsucessful, no devices in list." ,Toast.LENGTH_SHORT ).show();
}
for(BluetoothDevice bt : pairedDevices) //foreach
{
if(name.equals(bt.getName()))
{
remoteDevice = bt;
Toast.makeText(getApplicationContext(), "Selected " + remoteDevice.getName(), Toast.LENGTH_SHORT ).show();
}
}
}
public void openBT(View v) //opens right thread for server or client
{
if(adapter == null)
{
adapter = getDefaultAdapter();
Log.i(TAG, "Backup way of getting adapter was used!");
}
CONTINUE_READ_WRITE = true; //writer tiebreaker
socket = null; //resetting if was used previously
is = null; //resetting if was used previously
os = null; //resetting if was used previously
if(pairedDevices.isEmpty() || remoteDevice == null)
{
Toast.makeText(this, "Paired device is not selected, choose one", Toast.LENGTH_SHORT).show();
return;
}
}
public void closeBT(View v) //for closing opened communications, cleaning used resources
{
/*if(adapter == null)
return;*/
CONTINUE_READ_WRITE = false;
CONNECTION_ENSTABLISHED = false;
if (is != null) {
try {is.close();} catch (Exception e) {}
is = null;
}
if (os != null) {
try {os.close();} catch (Exception e) {}
os = null;
}
if (socket != null) {
try {socket.close();} catch (Exception e) {}
socket = null;
}
try {
Handler mHandler = new Handler();
mHandler.removeCallbacksAndMessages(writter);
mHandler.removeCallbacksAndMessages(serverListener);
mHandler.removeCallbacksAndMessages(clientConnecter);
Log.i(TAG, "Threads ended...");
}catch (Exception e)
{
Log.e(TAG, "Attemp for closing threads was unsucessfull.");
}
Toast.makeText(getApplicationContext(), "Communication closed" ,Toast.LENGTH_SHORT).show();
list(null); //shows list for reselection
txt.setText(getResources().getString(R.string.demo));
}
private Runnable serverListener = new Runnable()
{
public void run()
{
try //opening of BT connection
{
android.util.Log.i("TrackingFlow", "Server socket: new way used...");
socket =(BluetoothSocket) remoteDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(remoteDevice,1);
socket.connect();
CONNECTION_ENSTABLISHED = true; //protect from failing
} catch(Exception e) //obsolete way how to open BT
{
try
{
android.util.Log.e("TrackingFlow", "Server socket: old way used...");
BluetoothServerSocket tmpsocket = adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
socket = tmpsocket.accept();
CONNECTION_ENSTABLISHED = true; //protect from failing
android.util.Log.i("TrackingFlow", "Listening...");
}
catch (Exception ie)
{
Log.e(TAG, "Socket's accept method failed", ie);
ie.printStackTrace();
}
}
Log.i(TAG, "Server is ready for listening...");
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
listItems.clear(); //remove chat history
listItems.add(0, String.format(" Server opened! Waiting for clients..."));
listAdapter.notifyDataSetChanged();
}});
try //reading part
{
is = socket.getInputStream();
os = socket.getOutputStream();
new Thread(writter).start();
int bufferSize = 1024;
int bytesRead = -1;
byte[] buffer = new byte[bufferSize];
while(CONTINUE_READ_WRITE) //Keep reading the messages while connection is open...
{
final StringBuilder sb = new StringBuilder();
bytesRead = is.read(buffer);
if (bytesRead != -1) {
String result = "";
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
{
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = is.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
sb.append(result);
}
android.util.Log.e("TrackingFlow", "Read: " + sb.toString());
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
Toast.makeText(entrainement.this, sb.toString(), Toast.LENGTH_SHORT).show();
listItems.add(0, String.format("< %s", sb.toString())); //showing in history
listAdapter.notifyDataSetChanged();
}
});
}
}
catch(IOException e){
Log.e(TAG, "Server not connected...");
e.printStackTrace();
}
}
};
private Runnable clientConnecter = new Runnable()
{
#Override
public void run()
{
try
{
socket = remoteDevice.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
CONNECTION_ENSTABLISHED = true; //protect from failing
Log.i(TAG, "Client is connected...");
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
listItems.clear(); //remove chat history
listItems.add(0, String.format(" ready to communicate! Write something..."));
listAdapter.notifyDataSetChanged();
}});
os = socket.getOutputStream();
is = socket.getInputStream();
new Thread(writter).start();
Log.i(TAG, "Preparation for reading was done");
int bufferSize = 1024;
int bytesRead = -1;
byte[] buffer = new byte[bufferSize];
while(CONTINUE_READ_WRITE) //Keep reading the messages while connection is open...
{
final StringBuilder sb = new StringBuilder();
bytesRead = is.read(buffer);
if (bytesRead != -1)
{
String result = "";
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
{
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = is.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
sb.append(result);
}
android.util.Log.e("TrackingFlow", "Read: " + sb.toString());
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
Toast.makeText(entrainement.this, sb.toString(), Toast.LENGTH_SHORT).show();
listItems.add(0, String.format("< %s", sb.toString()));
listAdapter.notifyDataSetChanged();
}
});
}
}
catch (IOException e)
{
Log.e(TAG, "Client not connected...");
e.printStackTrace();
}
}
};
}
reglages.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class reglages extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVER_BT = 1;
TextView mStatusBlueTv, mPairedTv;
ImageView mBlueIv;
Button mOnBtn, mOffBtn, mDiscoverBtn, mPairedBtn;
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reglages);
mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
mPairedTv = findViewById(R.id.pairedTv);
mBlueIv = findViewById(R.id.bluetoothIv);
mOnBtn = findViewById(R.id.onBtn);
mOffBtn = findViewById(R.id.offBtn);
mDiscoverBtn = findViewById(R.id.discoverableBtn);
mPairedBtn = findViewById(R.id.pairedBtn);
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
//check if bluetooth is available or not
if (mBlueAdapter == null){
mStatusBlueTv.setText("Bluetooth is not available");
}
else {
mStatusBlueTv.setText("Bluetooth is available");
}
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()){
mBlueIv.setImageResource(R.drawable.ic_action_on);
}
else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
//on btn click
mOnBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()){
showToast("Turning On Bluetooth...");
//intent to on bluetooth
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover bluetooth btn click
mDiscoverBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBlueAdapter.isDiscovering()){
showToast("Making Your Device Discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_DISCOVER_BT);
}
}
});
//off btn click
mOffBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()){
mBlueAdapter.disable();
showToast("Turning Bluetooth Off");
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
else {
showToast("Bluetooth is already off");
}
}
});
//get paired devices btn click
mPairedBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()){
mPairedTv.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device: devices){
mPairedTv.append("\nDevice: " + device.getName()+ ", " + device);
}
}
else {
//bluetooth is off so can't get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK){
//bluetooth is on
mBlueIv.setImageResource(R.drawable.ic_action_on);
showToast("Bluetooth is on");
}
else {
//user denied to turn bluetooth on
showToast("could't on bluetooth");
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
//toast message function
private void showToast(String msg){
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
Then change this lines:
//check if bluetooth is available or not
if (mBlueAdapter == null){
mStatusBlueTv.setText("Bluetooth is not available");
}
else {
mStatusBlueTv.setText("Bluetooth is available");
}
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()){
mBlueIv.setImageResource(R.drawable.ic_action_on);
}
else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
To this:
//check if bluetooth is available or not
if (mBlueAdapter == null) {
mStatusBlueTv.setText("Bluetooth is not available");
mBlueIv.setImageResource(R.drawable.ic_action_off);
} else {
mStatusBlueTv.setText("Bluetooth is available");
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()) {
mBlueIv.setImageResource(R.drawable.ic_action_on);
} else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
}
And each time you check isEnabled check for null first, changing:
if (mBlueAdapter.isEnabled()){
to:
if (mBlueAdapter != null && mBlueAdapter.isEnabled()) {
This way you'll prevent having NullPointers when the Bluetooth is not available (mBlueAdapter == null) as you can not check isEnabled() in this cases.

Google translation API problems on Android

I'm trying to use Google Translation API but I'm getting not null pointer error, this is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.speakingtranslator.GoogleTranslateActivity.translte(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.speakingtranslator.MainActivity.translated(MainActivity.java:332)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:310)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:271)
Here is the code
public void translated() {
String translatetotagalog = editText.getText().toString();
Log.v("raw text",translatetotagalog);
String text = translator.translte(translatetotagalog, "en", "yo");
Log.v("translated text", text);
editTranslate.setText(text);
}
Here is the translte
String translte(String text, String from, String to) {
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String urlStr = "https://www.googleapis.com/language/translate/v2?key="+ key +"&q=" + encodedText + "&target=" + to + "&source=" + from;
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream stream;
if (conn.getResponseCode() == 200) //success
{
stream = conn.getInputStream();
} else
stream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
String translatedText = obj.get("data").getAsJsonObject().
get("translations").getAsJsonArray().
get(0).getAsJsonObject().
get("translatedText").getAsString();
return translatedText;
}
}
if (conn.getResponseCode() != 200) {
System.err.println(result);
}
} catch (IOException | JsonSyntaxException ex) {
System.err.println(ex.getMessage());
}
return null;
}
Complete MainActivity.java
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
GoogleTranslateActivity translator;
private TextToSpeech textToSpeech;
private Button btn, button2, trans;
String soundName;
MediaPlayer mp = null;
String text2speak;
private boolean connected;
private static final String API_KEY = "API_KEY";
private EditText editText, editTranslate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
btn = findViewById(R.id.material_icon_button);
button2 = findViewById(R.id.material_icon_yoruba);
trans = findViewById(R.id.material_icon_translate);
checkPermission();
editText = findViewById(R.id.editText);
editTranslate = findViewById(R.id.editTranslate);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int ttsLang = textToSpeech.setLanguage(Locale.US);
if (ttsLang == TextToSpeech.LANG_MISSING_DATA
|| ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "The Language is not supported!");
} else {
Log.i("TTS", "Language Supported.");
}
Log.i("TTS", "Initialization success.");
} else {
Toast.makeText(getApplicationContext(), "TTS Initialization failed!", Toast.LENGTH_SHORT).show();
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String data = editText.getText().toString();
Log.i("TTS", "button clicked: " + data);
int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null);
if (speechStatus == TextToSpeech.ERROR) {
Log.e("TTS", "Error in converting Text to Speech!");
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
soundName = editTranslate.getText().toString();
soundName = soundName.replaceAll("\\s+", "_").toLowerCase();
SoundManager(soundName);
Toast.makeText(getApplicationContext(), soundName, Toast.LENGTH_LONG).show();
}
});
trans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
text2speak = editText.getText().toString();
new EnglishToTagalog().execute();
}
});
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
editText.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.material_icon_mic).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
editText.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
editText.setText("");
editText.setHint("Listening...");
break;
}
return false;
}
});
//Initialize and Assign Variable
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//Set Home Selected
bottomNavigationView.setSelectedItemId(R.id.home);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.messages:
startActivity(new Intent(getApplicationContext(),Messages.class));
overridePendingTransition(0,0);
return true;
case R.id.home:
return true;
case R.id.info:
startActivity(new Intent(getApplicationContext(),Info.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
}
private class EnglishToTagalog extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
protected void onError(Exception ex) {
Toast.makeText(getApplicationContext(),ex.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
try {
translator = new GoogleTranslateActivity(API_KEY);
Thread.sleep(15000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
// start the progress dialog
progress = ProgressDialog.show(MainActivity.this, null,
"Translating...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
translated();
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void translated() {
String translatetotagalog = editText.getText().toString();
Toast.makeText(getApplicationContext(), translatetotagalog, Toast.LENGTH_LONG).show();
Log.v("raw text",translatetotagalog);
String text = translator.translte(translatetotagalog, "en", "yo");
//translatabletext = (TextView) findViewById(R.id.translatabletext);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
Log.v("translated text", text);
editTranslate.setText(text);
}
protected void SoundManager(String sn){
if (mp != null){
mp.reset();
mp.release();
}
switch (sn){
case "e_kaaro":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaaro);
break;
case "e_kaasan":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaasan);
break;
case "e_kaale":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaale);
break;
case "bawo_ni_o_se_n_se":
mp = MediaPlayer.create(getApplicationContext(), R.raw.bawo_ni_o_se_n_se);
break;
case "mo_nife_re":
mp = MediaPlayer.create(getApplicationContext(), R.raw.mo_nife_re);
break;
default:
mp = MediaPlayer.create(getApplicationContext(), R.raw.crowd);
}
//Toast.makeText(getApplicationContext(), "clicked " + sn, Toast.LENGTH_LONG).show();
mp.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
public boolean checkInternetConnection() {
//Check internet connection:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//Means that we are connected to a network (mobile or wi-fi)
connected = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
return connected;
}
}

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

How to call this android bluetooth printing program from phonegap javascript?

i was made a bluetooth printer application (android based) for printing some text using datecs DPP-350 printer device. this program use a datecs external library such as bluetoohconnector and RFComm package. it works nicely, here's the code:
package com.myapp.MobilePrinter1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.djarum.MobilePrinter1.BluetoothConnector;
import com.datecs.api.card.FinancialCard;
import com.datecs.api.printer.Printer;
import com.datecs.api.printer.PrinterInformation;
import com.datecs.api.printer.ProtocolAdapter;
import com.datecs.api.printer.ProtocolAdapter.Channel;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MobilePrinter1Activity extends Activity {
public static final String CONNECTION_STRING = "connection_string";
private final Handler mHandler = new Handler();
private final Thread mConnectThread = new Thread() {
#Override
public void run() {
String connectionString = "bth://00:01:90:E6:40:52";
showProgress("Connecting");
if (connectionString.startsWith("bth://")) {
String address = connectionString.substring(6);
connectBth(address);
} else {
throw new IllegalArgumentException("Unsupported connection string");
}
dismissProgress();
}
void connectBth(String address) {
//setPrinterInfo(R.drawable.help, address);
try {
mBthConnector = BluetoothConnector.getConnector(MobilePrinter1Activity.this);
mBthConnector.connect(address);
mPrinter = getPrinter(
mBthConnector.getInputStream(),
mBthConnector.getOutputStream());
} catch (IOException e) {
//error(R.drawable.bluetooth, e.getMessage());
return;
}
mPrinterInfo = getPrinterInfo();
}
Printer getPrinter(InputStream in, OutputStream out) throws IOException {
ProtocolAdapter adapter = new ProtocolAdapter(in, out);
Printer printer = null;
if (adapter.isProtocolEnabled()) {
Channel channel = adapter.getChannel(ProtocolAdapter.CHANNEL_PRINTER);
InputStream newIn = channel.getInputStream();
OutputStream newOut = channel.getOutputStream();
printer = new Printer(newIn, newOut);
} else {
printer = new Printer(in, out);
}
return printer;
}
PrinterInformation getPrinterInfo() {
PrinterInformation pi = null;
try {
pi = mPrinter.getInformation();
//setPrinterInfo(R.drawable.printer, pi.getName());
} catch (IOException e) {
e.printStackTrace();
}
return pi;
}
};
private BluetoothConnector mBthConnector;
private Printer mPrinter;
private PrinterInformation mPrinterInfo;
private ProgressDialog mProgressDialog;
private BluetoothConnector mConnector;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
mConnector = BluetoothConnector.getConnector(this);
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
finish();
}
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printText();
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printBarcode();
}
});
findViewById(R.id.button3).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printImage();
}
});
}
public void printText() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintText2();
dismissProgress();
}
}.start();
}
public void printBarcode() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintBarcode();
dismissProgress();
}
}.start();
}
public void printImage() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintImage();
dismissProgress();
}
}.start();
}
#Override
protected void onStart() {
super.onStart();
mConnectThread.start();
}
#Override
protected void onStop() {
super.onStop();
if (mBthConnector != null) {
try {
mBthConnector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void showProgress(final String text) {
mHandler.post(new Runnable() {
#Override
public void run() {
mProgressDialog = ProgressDialog.show(
MobilePrinter1Activity.this,
"Please wait",
text,
true);
}
});
}
private void showProgress(int resId) {
showProgress(getString(resId));
}
private void dismissProgress() {
mHandler.post(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
}
});
}
private void doPrintSelfTest() {
try {
mPrinter.printSelfTest();
} catch (IOException e) {
//error(R.drawable.selftest, getString(R.string.failed_print_self_test) + ". " +
//e.getMessage());
}
}
private void doPrintText2() {
EditText EditText1;
EditText1=(EditText)findViewById(R.id.editText1);
String temp;
try {
mPrinter.reset();
mPrinter.printTaggedText(EditText1.getText().toString());
//mPrinter.printTaggedText("Testing Testing!!");
mPrinter.feedPaper(110);
} catch (IOException e) {
//error(R.drawable.text, getString(R.string.failed_print_text) + ". " +
//e.getMessage());
}
}
private void doPrintBarcode() {
EditText EditText1;
EditText1=(EditText)findViewById(R.id.editText1);
try {
mPrinter.reset();
mPrinter.setBarcode(Printer.ALIGN_CENTER, false, 2, Printer.HRI_BOTH, 100);
mPrinter.printBarcode(Printer.BARCODE_CODE128, EditText1.getText().toString());
mPrinter.feedPaper(38);
mPrinter.feedPaper(110);
} catch (IOException e) {
//error(R.drawable.barcode, getString(R.string.failed_print_barcode) + ". " +
//e.getMessage());
}
}
private void doPrintImage() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo_djarum);
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
final int[] argb = new int[width * height];
bitmap.getPixels(argb, 0, width, 0, 0, width, height);
try {
mPrinter.reset();
mPrinter.printImage(argb, width, height, Printer.ALIGN_LEFT, true);
mPrinter.feedPaper(110);
} catch (IOException e) {
Toast.makeText(MobilePrinter1Activity.this, e.getMessage(), 1).show();
}
}
private void dialog(final int id, final String title, final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog dlg = new AlertDialog.Builder(MobilePrinter1Activity.this)
.setTitle(title)
.setMessage(msg)
.create();
dlg.setIcon(id);
dlg.show();
}
});
}
private void error(final int resIconId, final String message) {
mHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog dlg = new AlertDialog.Builder(MobilePrinter1Activity.this)
.setTitle("Error")
.setMessage(message)
.create();
dlg.setIcon(resIconId);
dlg.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
MobilePrinter1Activity.this.finish();
}
});
dlg.show();
}
});
}
private void setPrinterInfo(final int resIconId, final String text) {
mHandler.post(new Runnable() {
#Override
public void run() {
//((ImageView)findViewById(R.id.icon)).setImageResource(resIconId);
//((TextView)findViewById(R.id.name)).setText(text);
}
});
}
}
the main problems now is how to call this program from phonegap? i've tried using droidGap but it will give me error when i start the printer's thread. has anyone know how to solved this?? many thanks..
I dont think that you can invoke too many APIs from the standard android browser (except some like location, contacts n all), but what is possible is other way round embedding a webview in a native app(which can be your above mentioned thread code) and invoking this code from a Javascript event using JavaScript Interface apis of android platform (which is pretty straight forward).

Categories