thanks for your help in advance. I'm building an application that allows me to send messages from one device to another using the bluetooth. this is the code that I have.
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
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.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configureBluetooth();
setupListView();
setupSearchButton();
setupListenButton();
}
private BluetoothAdapter bluetooth;
private BluetoothSocket socket;
private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
private void configureBluetooth() {
bluetooth = BluetoothAdapter.getDefaultAdapter();
}
private Handler handler = new Handler();
private void switchUI() {
final TextView messageText = (TextView)findViewById(R.id.messageview);
final EditText textEntry = (EditText)findViewById(R.id.messagetext);
messageText.setVisibility(View.VISIBLE);
list.setVisibility(View.GONE);
textEntry.setEnabled(true);
textEntry.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
sendMessage(socket, textEntry.getText().toString());
textEntry.setText("");
return true;
}
return false;
}
});
BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] stringAsBytes = (msg + " ").getBytes();
stringAsBytes[stringAsBytes.length - 1] = 0;
outStream.write(stringAsBytes);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
private static int DISCOVERY_REQUEST = 1;
private void setupListenButton() {
Button listenButton = (Button) findViewById(R.id.listen_button);
listenButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent disc;
disc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(disc, DISCOVERY_REQUEST);
}
});
}
@Override
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 BluetoothSocket doInBackground(Integer... params) {
try {
socket = btserver.accept(params[0] * 1000);
return socket;
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(BluetoothSocket result) {
if (result != null)
switchUI();
}
};
acceptThread.execute(resultCode);
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
}
}
}
private ArrayList<BluetoothDevice> foundDevices;
private ArrayAdapter<BluetoothDevice> aa;
private ListView list;
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice remoteDevice;
remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetooth.getBondedDevices().contains(remoteDevice)) {
foundDevices.add(remoteDevice);
aa.notifyDataSetChanged();
}
}
};
private void setupListView() {
aa = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1, foundDevices);
list = (ListView) findViewById(R.id.list_discovered);
list.setAdapter(aa);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view,
int index, long arg3) {
AsyncTask<Integer, Void, Void> connectTask =
new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... params) {
try {
BluetoothDevice device = foundDevices.get(params[0]);
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
} catch (IOException e) {
Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
switchUI();
}
};
connectTask.execute(index);
}
});
}
private void setupSearchButton() {
Button searchButton = (Button) findViewById(R.id.search_button);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
if (!bluetooth.isDiscovering()) {
foundDevices.clear();
bluetooth.startDiscovery();
}
}
});
}
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, TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = - 1;
String message = "";
while (true) {
message = "";
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());
}
}
}
}
And this is the error that I'm getting
04-17 18:56:40.457 6684-6684/universityofhouston.dtntext E/AndroidRuntime: FATAL EXCEPTION: main Process: universityofhouston.dtntext, PID: 6684 java.lang.RuntimeException: Unable to start activity ComponentInfo{universityofhouston.dtntext/universityofhouston.dtntext.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3155) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3263) at android.app.ActivityThread.access$1000(ActivityThread.java:197) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6897) 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:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330) at android.widget.ListView.setAdapter(ListView.java:502) at universityofhouston.dtntext.MainActivity.setupListView(MainActivity.java:160) at universityofhouston.dtntext.MainActivity.onCreate(MainActivity.java:39) at android.app.Activity.performCreate(Activity.java:6550) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3108) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3263) at android.app.ActivityThread.access$1000(ActivityThread.java:197) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6897) 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:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
I think the error is here and is related to the Parcelable. I was reading a lot of posts related to this issue and i found a line of code that it might help me, but i don't know how to implement it in my code.
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice remoteDevice;
remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetooth.getBondedDevices().contains(remoteDevice)) {
foundDevices.add(remoteDevice);
aa.notifyDataSetChanged();
}
}
};
private void setupListView() {
aa = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1, foundDevices);
Here is the code that i found.
ArrayList<MyClass> mObjList;
public void writeToParcel(Parcel out, int flags) {
out.writeTypedList(mObjList);
}
protected MyClass(Parcel in) {
mObjList = new ArrayList<>(); //non-null reference is required
in.readTypedList(mObjList, MyClass.CREATOR);
}
If any here knows how to implement this code or help me to find another way to fix this problem i would appreciate it. Sorry for the long post i just wanted to be as more as specific as i could so that would help you to find a better way to approach this issue.