I am trying to send a calculated bearing from an android device to an Arduino via Bluetooth every time the location is changed. The app always crashes when trying to use the outPutStream. Here is the code:
public class Location_Informaion extends MainActivity implements LocationListener {
private static final String TAG = "bluetooth1";
TextView desiredDest, currentLatitude, currentLongitude, Distance, Bearing, txtArduino;
private LocationManager locationManager;
String provider, message;
private Location location;
double desLatVal, desLonVal, pi;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String macAddress = "30:14:12:02:16:78";
private ConnectedThread mConnectedThread;
Handler h;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private StringBuilder sb = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pi = 3.14159265359;
setContentView(R.layout.activity_location__informaion);
Bundle extras = getIntent().getExtras();
String desLat = extras.getString("desLat");
String desLon = extras.getString("desLon");
desLatVal = Double.parseDouble(desLat);
desLonVal = Double.parseDouble(desLon);
desiredDest = (TextView) findViewById(R.id.desiredDestination);
desiredDest.setText(desLat + "Lat, " + desLon + "Long.");
message = "180";
currentLatitude = (TextView) findViewById(R.id.currentLat);
currentLongitude = (TextView) findViewById(R.id.currentLon);
txtArduino = (TextView) findViewById(R.id.txtArduino);
Distance = (TextView) findViewById(R.id.Distance);
Bearing = (TextView) findViewById(R.id.Bearing);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider" + provider + "has been selected");
currentLatitude.setText("Searching for lock");
currentLongitude.setText("Searching for lock");
onLocationChanged(location);
} else {
currentLatitude.setText("Location is not available");
currentLongitude.setText("Location is not available");
}
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
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);
}
public void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 0, 0, this);
Log.d(TAG, "...onResume - try connect...");
BluetoothDevice device = btAdapter.getRemoteDevice(macAddress);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
btAdapter.cancelDiscovery();
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() + ".");
}
}
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
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() {
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;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer, 0, msgBuffer.length);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
@Override
public void onLocationChanged(Location location) {
double lat = (location.getLatitude());
double lon = (location.getLongitude());
currentLatitude.setText(String.valueOf(lat));
currentLongitude.setText(String.valueOf(lon));
float R = 6371000;
double latRad = lat / (180 / pi);
double desLatRad = desLatVal / (180 * pi);
double changeLat = (desLatVal - lat) / (180 * pi);
double changeLon = (desLonVal - lon) / (180 / pi);
double a = Math.sin(changeLat / 2) * Math.sin(changeLat / 2) +
Math.cos(latRad) * Math.cos(desLatRad) *
Math.sin(changeLon / 2) * Math.sin(changeLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = R * c / 1000;
String distance = String.valueOf(d);
Distance.setText(distance + "km");
double y = Math.sin(desLonVal - lon) * Math.cos(desLatVal);
double x = Math.cos(lat) * Math.sin(desLatVal) -
Math.sin(lat) * Math.cos(desLatVal) * Math.cos(desLonVal - lon);
double brng = (Math.atan2(y, x)) * 180 / pi;
String bearing = String.valueOf(brng);
Bearing.setText(bearing);
mConnectedThread.write(bearing);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enable new provider " + provider, Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show();
}
}
Any help would be appreciated.
06-17 16:34:35.930 11800-11818/com.example.biggus.system_4 I/OpenGLRenderer﹕ Initialized EGL, version 1.4 06-17 16:34:35.950 11800-11818/com.example.biggus.system_4 I/OpenGLRenderer﹕ HWUI protection enabled for context , &this =0xb3922088 ,&mEglDisplay = 1 , &mEglConfig = 8 06-17 16:34:35.950 11800-11818/com.example.biggus.system_4 D/OpenGLRenderer﹕ Enabling debug mode 0 06-17 16:34:36.090 11800-11800/com.example.biggus.system_4 I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@346384f1 time:13135175 06-17 16:34:37.870 11800-11800/com.example.biggus.system_4 D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN 06-17 16:34:40.740 11800-11800/com.example.biggus.system_4 D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN 06-17 16:34:43.850 11800-11800/com.example.biggus.system_4 D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN 06-17 16:34:43.930 11800-11800/com.example.biggus.system_4 I/Timeline﹕ Timeline: Activity_launch_request id:com.example.biggus.system_4 time:13143016 06-17 16:34:44.060 11800-11800/com.example.biggus.system_4 I/System.out﹕ Providergpshas been selected 06-17 16:34:44.070 11800-11800/com.example.biggus.system_4 D/AndroidRuntime﹕ Shutting down VM 06-17 16:34:44.070 11800-11800/com.example.biggus.system_4 E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.biggus.system_4, PID: 11800 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.biggus.system_4/com.example.biggus.system_4.Location_Informaion}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.biggus.system_4.Location_Informaion$ConnectedThread.write(java.lang.String)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725) at android.app.ActivityThread.access$900(ActivityThread.java:172) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5834) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.biggus.system_4.Location_Informaion$ConnectedThread.write(java.lang.String)' on a null object reference at com.example.biggus.system_4.Location_Informaion.onLocationChanged(Location_Informaion.java:283) at com.example.biggus.system_4.Location_Informaion.onCreate(Location_Informaion.java:89) at android.app.Activity.performCreate(Activity.java:6221) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725) at android.app.ActivityThread.access$900(ActivityThread.java:172) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5834) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Error is at txtArduino.setText("Data from Arduino: " + sbprint);
You have not initialized txtArduino object with respective textview. Please do a findviewByid and get the respective textview into txtArduino object.