getRemoteDevice null object reference Error sending bluetooth string - java

I'm trying to send a string to a bluetooth device (HC-06), but I keep recieving the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fiber.sliderapp, PID: 29808
java.lang.RuntimeException: Unable to resume activity {com.fiber.sliderapp/com.fiber.sliderapp.ControleOnlineActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.bluetooth.BluetoothDevice
android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)'
on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3450)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3490)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2749)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1490)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6165)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothDevice
android.bluetooth.BluetoothAdapter.getRemoteDevice(java.lang.String)'
on a null object reference
at com.fiber.sliderapp.ControleOnlineActivity.onResume(ControleOnlineActivity.java:60)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1291)
at android.app.Activity.performResume(Activity.java:6791)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3427)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3490) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2749) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1490) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6165) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
The code I'm using:
package com.fiber.sliderapp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
public class ControleOnlineActivity extends AppCompatActivity {
private static final String TAG = "bluetooth1";
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
public static String address = "98:D3:31:70:0D:0C";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controle_online);
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
Log.d(TAG, "...onResume - try connect...");
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
public void message_Hor_Esq(View v){
EditText par;
par = (EditText) findViewById(R.id.editText_horizontal);
if (TextUtils.isEmpty(par.getText().toString())) {
Toast toast = Toast.makeText(this, "Preencha uma velocidade", Toast.LENGTH_SHORT);
toast.show();
} else {
String msg = "C_H_E_" + par.getText().toString() + "/";
sendData("1");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
}
public void message_Hor_Dir(View v){
EditText par;
par = (EditText) findViewById(R.id.editText_horizontal);
if (TextUtils.isEmpty(par.getText().toString())) {
Toast toast = Toast.makeText(this, "Preencha uma velocidade", Toast.LENGTH_SHORT);
toast.show();
} else {
String msg = "C_H_D_" + par.getText().toString() + "/";
sendData("0");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
}
}
Anyone knows where is the problem?

Related

W/libEGL: EGLNativeWindowType 0x7d358f1010 disconnect failed

package com.example.yj.bluetoothapplication;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth2";
Button btnLed1, btnLed2, btnLed3, btnpado;
TextView txtArduino;
RelativeLayout rlayout;
Handler h;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private static int flag = 0;
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "98:D3:61:FD:59:9D";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLed1 = (Button) findViewById(R.id.btnLed1);
btnLed2 = (Button) findViewById(R.id.btnLed2);
btnLed3 = (Button) findViewById(R.id.btnLed3);
btnpado = (Button) findViewById(R.id.btnPado);
txtArduino = (TextView) findViewById(R.id.txtArduino);
rlayout = (RelativeLayout) findViewById(R.id.layout);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
txtArduino.setText("Data from Arduino: " + sbprint);
if(flag%4==3){
rlayout.setBackgroundColor(Color.rgb(255, 255, 255));
}
else if(flag%4==1){
rlayout.setBackgroundColor(Color.rgb(255, 0, 0));
}
else if(flag%4==2){
rlayout.setBackgroundColor(Color.rgb(0, 255, 0));
}
else if(flag%4==0){
rlayout.setBackgroundColor(Color.rgb(0, 0, 255));
}
flag++;
btnLed1.setEnabled(true);
btnLed2.setEnabled(true);
btnLed3.setEnabled(true);
btnpado.setEnabled(true);
}
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
btnLed1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1");
Toast.makeText(getBaseContext(), "Turn on First LED", Toast.LENGTH_SHORT).show();
}
});
btnLed2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("2");
//Toast.makeText(getBaseContext(), "Turn on Second LED", Toast.LENGTH_SHORT).show();
}
});
btnLed3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("3");
//Toast.makeText(getBaseContext(), "Turn on Third LED", Toast.LENGTH_SHORT).show();
}
});
btnpado.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0");
//Toast.makeText(getBaseContext(), "Turn on all LEDs", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#d1bd8ab, channel: 1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream#218b08, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream#6d4d2a1mSocket: android.net.LocalSocket#a50ecc6 impl:android.net.LocalSocketImpl#3bd5487 fd:java.io.FileDescriptor#ec84fb4, mSocketState: CONNECTED D/ViewRootImpl#3a2e96b[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 1 D/InputMethodManager: prepareNavigationBarInfo() DecorView#a62bffa[MainActivity] getNavigationBarColor() -855310 D/InputTransport: Input channel destroyed: fd=76 W/libEGL: EGLNativeWindowType 0x7d358f2010 disconnect failed D/OpenGLRenderer: eglDestroySurface = 0x7d1f6ac180, 0x7d358f2000 D/ViewRootImpl#3a2e96b[MainActivity]: Relayout returned: old=[0,0][1080,2280] new=[0,0][1080,2280] result=0x5 surface={valid=false 0} changed=true D/ViewRootImpl#3a2e96b[MainActivity]: setWindowStopped(true) old=false D/ViewRootImpl#3a2e96b[MainActivity]: Surface release. android.view.WindowManagerGlobal.setStoppedState:669 android.app.Activity.performStop:7647 android.app.ActivityThread.callActivityOnStop:4378 android.app.ActivityThread.performStopActivityInner:4356 android.app.ActivityThread.handleStopActivity:4431 android.app.servertransaction.StopActivityItem.execute:41 android.app.servertransaction.TransactionExecutor.executeLifecycleState:145 android.app.servertransaction.TransactionExecutor.execute:70 D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#f21e178, channel: 1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream#eefc051, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream#853c0b6mSocket: null, mSocketState: CLOSED Process 30538 terminated.

R.java file is not there

The below given is the code for MyActivity.java file.
package com.technomentis.ledonoff;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.R;
public class MainActivity extends Activity {
private static final String TAG = "LEDOnOff";
Button btnOn, btnOff;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "00:00:00:00:00:00";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "In onCreate()");
setContentView(R.layout.main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast msg = Toast.makeText(getBaseContext(),
"You have clicked On", Toast.LENGTH_SHORT);
msg.show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("0");
Toast msg = Toast.makeText(getBaseContext(),
"You have clicked Off", Toast.LENGTH_SHORT);
msg.show();
}
});
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...In onResume - Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
I am getting following errors,
Error:(46, 32) error: cannot find symbol variable main
Error:(49, 43) error: cannot find symbol variable btnOn
Error:(50, 44) error: cannot find symbol variable btnOff
Btw I am using Android Studio. And new to android development.
Remove this line..
import android.R;
and press CTRL+SHIFT+O to Fix imports.
It means you are missing the xml file
main.xml
click right on layout ->new aml file
and in it,you must insert btnOn and btnoff buttons on this xml file.
Remove this line import android.R;
Go through this steps:-
first :- go cursor on "R" text, it shows hint that many types of packages,then select your package name ,your problem solved.
second:- if your first step is not working then you have implement project again.
I hope it is useful for you. :)

IOException in Java (Android): Transport endpoint is not connected

In my Android application, which was copied from answer to this question (and then slightly changed due to UUID-related problems with Samsung Galaxy tabs) I successfully connect to OBD device via bluetooth.
Then, when I try to send any command (which is done by sendData()), the exception from the title (Transport endpoint is not connected) is thrown and nothing is sent.
When I connected to my computer (the only difference in code is hardware address), I can send command without any problem (of course, I don't get any response, since computer is not OBD-device). Therefore, I believe I got all the permissions I need and UUID address is fine also.
EDIT1:
I installed Komunikacija.apk on the tablet again. I have only added some comments and have encountered two new problems:
mmSocket.connect() in openBT() fails (nothing happens for a long time after the last toast "5")
if bluetooth is turned off, the application shows a request for turning bluetoot on, but then "unfortunately stops".
EDIT2:
I went to the car again and test the app on Samsung phone and again onf the tablet also. Results:
tablet:
when running the application for the first time, connections, mentioned in EDIT1, wasn't made successfully.
I succeed in all of my next attempts, but IOException was thrown:
when I pressed the button SEND for the first time, exception.getMessage() returned Connection reset by peer
every next time, I got message Transport endpoint is not connected
phone: I successfully made a connection already in the first attempt, everything else was the same
EDIT3:
I found out that the OBD-device EML327 was at least part of the problems, because today, I tested get another OBD-device (OBDLink LX) and everything works fine, if I use it. Now, the question is
Why are those two OBD-devices behaving completely different and how to fix errors which occur, if I use OBD327?
EDIT4: I didn't find this important earlier, but the only response from my EML327 was AT+BRSF=24. After googling it around, I found an answer.
My MainActivity.java:
package com.example.komunikacija;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView myLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter, stevec;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button openButton = (Button)findViewById(R.id.open);
Button sendButton = (Button)findViewById(R.id.send);
Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.label);
myTextbox = (EditText)findViewById(R.id.entry);
//Open Button
openButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
try {
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Send Button
sendButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
try{
sendData();
}
catch (IOException ex) {
Toast.makeText(getApplicationContext(), "error when sending:"+ ex.getMessage(), Toast.LENGTH_SHORT).show();;
}
}
});
//Close button
closeButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
try
{
closeBT();
}
catch (IOException ex) { }
}
});
}
void findBT() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){
myLabel.setText("No bluetooth adapter available");
}
else{
if (!mBluetoothAdapter.isEnabled()){
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
Toast.makeText(this, "we found "+Integer.toString(pairedDevices.size()), Toast.LENGTH_SHORT).show();//number of devices found
if(pairedDevices.size() > 0){
for(BluetoothDevice device : pairedDevices){
//computer's addres: "00:22:68:E6:7D:D7"
//obd device's("00:0D:18:00:00:01")
//device.getName().equals("MattsBlueTooth")
if(device.getAddress().equals("00:22:68:E6:7D:D7")) {
Toast.makeText(this, "Found.", Toast.LENGTH_SHORT).show();
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
}
void openBT() throws IOException{
Toast.makeText(this, "openBT.", Toast.LENGTH_SHORT).show();
// UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
UUID uuid = mmDevice.getUuids()[0].getUuid();
BluetoothSocket tmp = null;
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(uuid);
// for others devices its works with:
// Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
// for galaxy tab 2 with:
Method m = mmDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(mmDevice, 1);
} catch (IOException e) {
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();;
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "4", Toast.LENGTH_SHORT).show();;
}
mmSocket = tmp;
Toast.makeText(this, "5", Toast.LENGTH_SHORT).show();;
mmSocket.connect();
// Log.i(TAG, "Client Connected!");
// mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(uuid);
Toast.makeText(this, "before connect", Toast.LENGTH_SHORT).show();
// mmSocket.connect();
Toast.makeText(this, "before stream", Toast.LENGTH_SHORT).show();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
Toast.makeText(this, "before listening", Toast.LENGTH_SHORT).show();
beginListenForData();
myLabel.setText("Bluetooth Opened");
}
void beginListenForData(){
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
final byte konec = 90; //ASCII for char Z
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);
packetBytes[bytesAvailable - 1] = konec;
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == konec)//originally 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()
{
Toast.makeText(getApplicationContext(), "setting " + Integer.toString(stevec++)+data, Toast.LENGTH_SHORT).show();
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
void sendData() throws IOException {
String msg = myTextbox.getText().toString();
Toast.makeText(this, "sending:"+msg, Toast.LENGTH_SHORT).show();;
//msg += "\n"; <-- dont want to have that.
mmOutputStream.write(msg.getBytes());
myLabel.setText("Data Sent");
}
void closeBT() throws IOException {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
}
I didn't just wait and the aswers to questions here and here helped me out of troubles. The problem was that EML327 needed channel 16, so the second argument of the method invoke should be 16.

Error with R class import in android [duplicate]

This question already has answers here:
"R cannot be resolved to a variable"? [duplicate]
(30 answers)
Closed 9 years ago.
Here's my code:
package com.example.connecttest;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import com.example.bttest.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class ConnectTest extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "00:00:00:00:00:00";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
out = (TextView) findViewById(R.id.out);
out.append("\n...In onCreate()...");
btAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBTState();
}
#Override
public void onStart() {
super.onStart();
out.append("\n...In onStart()...");
}
#Override
public void onResume() {
super.onResume();
out.append("\n...In onResume...\n...Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
String message = "Hello from Android.\n";
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
AlertBox("Fatal Error", msg);
}
}
#Override
public void onPause() {
super.onPause();
out.append("\n...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
#Override
public void onStop() {
super.onStop();
out.append("\n...In onStop()...");
}
#Override
public void onDestroy() {
super.onDestroy();
out.append("\n...In onDestroy()...");
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
out.append("\n...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
public void AlertBox( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message + " Press OK to exit." )
.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
}
}
This code has errors recurring every time the importing of R class comes up.
import com.example.bttest.R;
shows that the import cannot be resolved.
setContentView(R.layout.main);
and
out = (TextView) findViewById(R.id.out);
shows that R cannot be resolved to a variable.
Please suggest something to get this working.
Delete the "gen" folder in your project, clean and rebuild. R.java is generated automatically on build

Android Bluetooth Java Control LED On Off

Im new in Android developer. I try create a simple app which is turn on and off LED. Then, I install in my Android phone it work. But when I click the On or Off button it said:
Fatal error- In onResume() and an exception occured during write:socket close.
Hopefully someone help me change my code.
Here my code:
package com.example.ledonoff;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import com.example.ledonoff.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class Main extends Activity {
private static final String TAG = "Main";
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "50:F5:20:42:7F:2B";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "In onCreate()");
setContentView(R.layout.activity_main);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
}
public void buttonOn(View v) {
sendData("1");
Toast msg = Toast.makeText(getBaseContext(),"LED On", Toast.LENGTH_SHORT);
msg.show();
}
public void buttonOff(View v) {
sendData("0");
Toast msg = Toast.makeText(getBaseContext(),"LED Off", Toast.LENGTH_SHORT);
msg.show();
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...In onResume - Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I suppose it's because you get an exception while connecting btSocket, then in the exception handler you catch another exception for btSocket.close() (you can not close it if connect() failed)

Categories

Resources