Reputation: 1417
I am working on an android app where I need to send text over Bluetooth. I have come up with a piece of code to achieve this. My problem is that I am not able to pass the address of the another device for creating the socket. the app crashes every time it reaches to the point : BluetoothDevice device = bluetooth.getRemoteDevice(address); where address is the mac address of the device I want to connect to. My full code is:
package com.example.blueremote;
public class MainActivity extends Activity {
private BluetoothAdapter bluetooth;
private BluetoothSocket socket;
private Button btnSend;
private ArrayList<BluetoothDevice> foundDevices;
private ArrayAdapter<BluetoothDevice> aa;
private Handler handler = new Handler();
private ListView list;
private TextView tvmsg;
private static int DISCOVERY_REQUEST = 1;
private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
ImageButton up;
private String address = "D8:50:E6:8A:16:0F";
private String text = "up";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent disc;
disc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(disc, DISCOVERY_REQUEST);
up = (ImageButton) findViewById(R.id.btn_up);
registerReceiver(discoveryResult, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("Main Activity", "In up Button");
// Log.v("Main Activity", "Invoking switchUI");
AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
try {
Log.v("Main Activity", " AsyncTask started");
BluetoothDevice device = bluetooth
.getRemoteDevice(address);
socket = device
.createRfcommSocketToServiceRecord(uuid);
Log.v("Main Activity", "Socket Created");
socket.connect();
Log.v("Main Activity", "Socket Connected");
} catch (IOException e) {
Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Log.v("Main Activity", "Invoking switchUI");
switchUI();
}
};
connectTask.execute();
}
});
}
private void switchUI() {
Log.v("Main Activity", "In SwitchUI Method");
Log.v("Main Activity", "Invoking sendMessage Method ");
sendMessage(socket, text);
Log.v("Main Activity", "Message Sent");
BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
handler);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void sendMessage(BluetoothSocket socket, String msg) {
msg = "hi";
OutputStream outStream;
try {
Log.v("Main Activity", "Inside sendMessage Method ");
outStream = socket.getOutputStream();
Log.v("Main Activity", "Outstream:" + outStream);
byte[] byteString = (msg + " ").getBytes();
Log.v("Main Activity", "byteString:" + byteString);
outStream.write(byteString);
Log.v("Main Activity", "outstream written:");
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler) {
this.socket = socket;
// this.textView = textView;
this.handler = handler;
}
public void run() {
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "hello";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead == bufferSize)
&& (buffer[bufferSize - 1] != 0)) {
message = message
+ new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message
+ new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
/*
* protected void onActivityResult(int requestCode, int resultCode, Intent
* data) { if (requestCode == DISCOVERY_REQUEST) { boolean isDiscoverable =
* resultCode > 0; if (isDiscoverable) { String name = "bluetoothserver";
* try { final BluetoothServerSocket btserver = bluetooth
* .listenUsingRfcommWithServiceRecord(name, uuid); AsyncTask<Integer, Void,
* BluetoothSocket> acceptThread = new AsyncTask<Integer, Void,
* BluetoothSocket>() {
*
* @Override protected void onPostExecute(BluetoothSocket result) { if
* (result != null) switchUI(); }
*
* @Override protected BluetoothSocket doInBackground( Integer... params) {
* // TODO Auto-generated method stub try { socket =
* btserver.accept(params[0] * 1000); return socket; } catch (IOException e)
* { Log.d("BLUETOOTH", e.getMessage()); } return null; } };
* acceptThread.execute(resultCode); } catch (IOException e) {
* Log.d("BLUETOOTH", e.getMessage()); } } } }
*/
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
BluetoothDevice remoteDevice;
remoteDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetooth.getBondedDevices().contains(remoteDevice)) {
foundDevices.add(remoteDevice);
aa.notifyDataSetChanged();
}
}
};
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(discoveryResult);
}
}
This is what my logcat has to say:
E/AndroidRuntime( 5421): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime( 5421): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime( 5421): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime( 5421): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime( 5421): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime( 5421): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime( 5421): at java.lang.Thread.run(Thread.java:838)
E/AndroidRuntime( 5421): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 5421): at com.example.blueremote.MainActivity$2$1.doInBackground(MainActivity.java:75)
E/AndroidRuntime( 5421): at com.example.blueremote.MainActivity$2$1.doInBackground(MainActivity.java:1)
E/AndroidRuntime( 5421): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
Any idea how can I create a socket would be really appreciated. Thanks in advance
Upvotes: 0
Views: 649
Reputation: 15336
Caused by: java.lang.NullPointerException
at com.example.blueremote.MainActivity$2$1.doInBackground(MainActivity.java:75)
which indicates line
BluetoothDevice device = bluetooth.getRemoteDevice(address);
Problem
bluetooth
isn't initialized.
Upvotes: 1