在向ListView添加新项目时需要一些帮助,我正在尝试在Android(蓝牙)中“查询配对设备”,并且在添加数据时出现了一些错误...这是我的代码:
public class BlueLightProtoActivity extends ActionBarActivity {
public static final String TAG = "BlueLightProto";
private BluetoothAdapter BTAdapter = null;
private ArrayList adapter;
private ListView listview;
private ToggleButton togglebutton;
private Button btnOn, btnOff;
private OutputStream Out;
private InputStream In;
private static final int EnableBT = 1;
private static final int DiscoverBT = 2;
private static final int DiscDur = 300;
private final UUID SecureUUID = UUID.fromString("3debad23-01b7-4c71-8710-ffb4bfbf0b36");
private final UUID UnsecureUUID = UUID.fromString("fde1b057-5906-4d22-88c5-a0412a0c758e");
private final BroadcastReceiver BcRcv = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice BTDvc = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
adapter.add(BTDvc.getName() + "\n" + BTDvc.getAddress());
}
}
};
/*
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.e(TAG, "OnCreate1" );
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blue_light_proto);
togglebutton = (ToggleButton)findViewById(R.id.toggleButton);
listview = (ListView)findViewById(R.id.listView);
btnOn = (Button)findViewById(R.id.OnBtn);
btnOff = (Button)findViewById(R.id.OffBtn);
btnOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "Button On Pressed!");
sendData("1");
toast("You have clicked ON"); //MUST FIND WAY TO GET FEEDBACK FROM ARDUINO!!!!
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "Button Off Pressed!");
sendData("2");
toast("You have clicked OFF"); //MUST FIND WAY TO GET FEEDBACK FROM ARDUINO!!!!
}
});
BTAdapter = BluetoothAdapter.getDefaultAdapter();
if(BTAdapter == null) {
ExitNoBluetooth();
return;
}
listview.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "onItemClick");
String itemValue = (String) listview.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice BTDvc = BTAdapter.getRemoteDevice(MAC);
ConnectThread C = new ConnectThread(BTDvc);
C.start();
}
}
);
Log.e(TAG, "OnCreate2" );
}
public void onToggleClicked(View view) {
Log.e(TAG, "onToggleClicked1");
//adapter.clear();
ToggleButton togglebutton = (ToggleButton) view;
Log.e(TAG, "onToggleClicked2");
if(togglebutton.isChecked()) {
if(!BTAdapter.isEnabled()) {
Log.e(TAG, "onToggleClicked, request enable BT");
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, EnableBT);
} else {
toast("Your bluetooth is already enabled");
addQuery();
discoverDevices();
makeDiscoverable();
AcceptThread A = new AcceptThread();
A.start();
}
} else {
Log.e(TAG, "onToggleClicked, disabling BT");
BTAdapter.disable();
adapter.clear();
toast("Your device is now disabled");
}
}
public void onActivityResult(int requestCode, int resultCode, Intent Data) {
if(requestCode == EnableBT) {
if(resultCode == Activity.RESULT_OK) {
Log.e(TAG, "onActivityResult, BT enabled");
toast("Bluetooth has been enabled \n Scanning for Remote Bluetooth devices...");
addQuery();
discoverDevices();
makeDiscoverable();
AcceptThread A = new AcceptThread();
A.start();
} else {
Log.e(TAG, "onActivityResult, BT fail to enable");
toast("Bluetooth failed to enable");
togglebutton.setChecked(false);
}
} else if(requestCode == DiscoverBT) {
if(resultCode == DiscDur) {
Log.e(TAG, "onActivityResult, device discoverable");
toast("Your device is now discoverable for " + DiscDur + "seconds");
} else {
toast("Fail to enable discoverability");
}
}
}
public void addQuery() {
Log.e(TAG, "addQuery1");
Set<BluetoothDevice> pairedDevices = BTAdapter.getBondedDevices();
Log.e(TAG, "addQuery2" );
if(pairedDevices.size() > 0) {
Log.e(TAG, "addQuery3" );
int n = 4;
for(BluetoothDevice device : pairedDevices) {
Log.e(TAG, "addQuery" + n + "......." + device.getName() + "......." );
adapter.add(device.getName() + "\n" + device.getAddress());
Log.e(TAG, "addQueryX" );
n++;
}
}
}
public void discoverDevices(){
Log.e(TAG, "discoverDevices");
if (BTAdapter.startDiscovery()) {
toast("Discovering other bluetooth devices");
} else {
toast("Discovery failed to start");
}
}
public void makeDiscoverable() {
Log.e(TAG, "makeDiscoverable");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DiscDur);
startActivityForResult(discoverableIntent, DiscoverBT);
}
//connect as server
private class AcceptThread extends Thread {
private final BluetoothServerSocket BTSvrSckt;
public AcceptThread() {
BluetoothServerSocket temp = null;
try {
temp = BTAdapter.listenUsingRfcommWithServiceRecord("BlueLightProto", SecureUUID);
} catch (IOException e) {}
BTSvrSckt = temp;
}
public void run() {
BluetoothSocket BTSckt = null;
while (true) {
try {
BTSckt = BTSvrSckt.accept();
} catch (IOException e) {
break;
}
if (BTSckt != null) {
//manageConnectedSocket(BTSckt); //Do work to manage the connection in a separate thread
try {
BTSvrSckt.close();
} catch (IOException e) {
break;
}
}
}
}
public void cancel() {
try {
BTSvrSckt.close();
} catch (IOException e) {}
}
}
//Connect as Client
private class ConnectThread extends Thread {
private final BluetoothSocket BTSckt;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket temp = null;
try {
temp = device.createRfcommSocketToServiceRecord(SecureUUID);
} catch (IOException e) {}
BTSckt = temp;
}
public void run() {
BTAdapter.cancelDiscovery();
try {
BTSckt.connect();
} catch (IOException connectException) {
try {
BTSckt.close();
} catch (IOException closeException) {}
return;
}
//manageConnectedSocket(BTSckt)
}
public void cancel() {
try {
BTSckt.close();
} catch (IOException e) {}
}
}
private void sendData(String message) {
byte[] msg = message.getBytes();
Log.e(TAG, "...Sending data: " + message + "...");
try {
Out.write(msg);
} catch (IOException e) {
String stat = "An exception occurred during write: " + e.getMessage();
toast(stat);
}
}
public void toast(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
public void ExitNoBluetooth() {
Log.e(TAG, "ExitNoBluetooth");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Cannot use BlueLightProto without bluetooth")
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("BlueLightProto")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.create().show();
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_blue_light_proto, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这是我的LogCat:
02-15 00:08:23.388 27882-27882/com.ebookfrenzy.bluelightproto I/BlueLightProto﹕ onStart
02-15 00:08:23.388 27882-27882/com.ebookfrenzy.bluelightproto I/BlueLightProto﹕ onResume
02-15 00:08:23.408 27882-27882/com.ebookfrenzy.bluelightproto I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:385>: EGL 1.4 QUALCOMM build: ()
OpenGL ES Shader Compiler Version: E031.24.00.02
Build Date: 01/20/14 Mon
Local Branch: PMH2-KK_3.5-RB1-AU61-554722-586267-set2
Remote Branch:
Local Patches:
Reconstruct Branch:
02-15 00:08:23.438 27882-27882/com.ebookfrenzy.bluelightproto D/OpenGLRenderer﹕ Enabling debug mode 0
02-15 00:08:23.498 27882-27882/com.ebookfrenzy.bluelightproto I/ActivityManager﹕ Timeline: Activity_idle id: android.os.BinderProxy@428db578 time:75247271
02-15 00:08:25.238 27882-27882/com.ebookfrenzy.bluelightproto I/ViewRootImpl﹕ ViewRoot's Touch Event : Touch Down
02-15 00:08:25.318 27882-27882/com.ebookfrenzy.bluelightproto I/ViewRootImpl﹕ ViewRoot's Touch Event : Touch UP
02-15 00:08:25.328 27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ onToggleClicked1
02-15 00:08:25.328 27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ onToggleClicked2
02-15 00:08:25.328 27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ onToggleClicked, request enable BT
02-15 00:08:25.338 27882-27882/com.ebookfrenzy.bluelightproto I/BlueLightProto﹕ onPause
02-15 00:08:28.198 27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ onActivityResult, BT enabled
02-15 00:08:28.198 27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ addQuery1
02-15 00:08:28.208 27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ addQuery2
02-15 00:08:28.208 27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ addQuery3
02-15 00:08:28.208 27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ addQuery4.......U8860.......
02-15 00:08:28.208 27882-27882/com.ebookfrenzy.bluelightproto D/AndroidRuntime﹕ Shutting down VM
02-15 00:08:28.208 27882-27882/com.ebookfrenzy.bluelightproto W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4188de48)
02-15 00:08:28.208 27882-27882/com.ebookfrenzy.bluelightproto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ebookfrenzy.bluelightproto, PID: 27882
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.ebookfrenzy.bluelightproto/com.ebookfrenzy.bluelightproto.BlueLightProtoActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3382)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3425)
at android.app.ActivityThread.access$1300(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1248)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.ebookfrenzy.bluelightproto.BlueLightProtoActivity.addQuery(BlueLightProtoActivity.java:185)
at com.ebookfrenzy.bluelightproto.BlueLightProtoActivity.onActivityResult(BlueLightProtoActivity.java:155)
at android.app.Activity.dispatchActivityResult(Activity.java:5467)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3378)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3425)
at android.app.ActivityThread.access$1300(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1248)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
我确实在“adapter.add()”中遇到了addQuery()类的问题 但我不知道如何解决它,我只是遵循某些教程的代码。刚开始学习android studio,还需要很多帮助,谢谢之前
答案 0 :(得分:0)
没有行号,它有点棘手,但我的猜测是:
adapter.add(device.getName() + "\n" + device.getAddress());
是第185行。
我没有在你的类中看到你初始化名为adapter的变量的任何地方。当你尝试使用它时,这会给你一个空指针异常。在定义适配器时尝试初始化适配器。例如
private ArrayList adapter = new ArrayList();
注意:除此之外,你可能不应该在这里使用原始类型的ArrayList。