当我尝试实现从一个活动向扩展服务的BluetoothService Activity发送字符串消息的代码时,为什么会出现NullPointerException错误。
以下是发送字符串所涉及的代码的主要部分:
private BluetoothService mChatService = null;
public void onCaptureButtonClicked(View view) throws IOException{
try{
sendMessage("1");
}catch(NullPointerException e){
e.printStackTrace();
}
takePhoto(1);
}
}
private void sendMessage(String message) {
if (mChatService.getState() != BluetoothService.STATE_CONNECTED) {
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
mChatService.write(send);
}
}
这是错误logcat:
02-15 18:21:19.960: W/System.err(1252): java.lang.NullPointerException
02-15 18:21:19.960: W/System.err(1252): at com.example.application.parss.CameraActivity.sendMessage(CameraActivity.java:751)
02-15 18:21:19.960: W/System.err(1252): at com.example.application.parss.CameraActivity.onCaptureButtonClicked(CameraActivity.java:245)
02-15 18:21:19.960: W/System.err(1252): at java.lang.reflect.Method.invokeNative(Native Method)
02-15 18:21:19.960: W/System.err(1252): at java.lang.reflect.Method.invoke(Method.java:507)
02-15 18:21:19.960: W/System.err(1252): at android.view.View$1.onClick(View.java:2180)
02-15 18:21:19.960: W/System.err(1252): at android.view.View.performClick(View.java:2585)
02-15 18:21:19.960: W/System.err(1252): at android.view.View$PerformClick.run(View.java:9299)
02-15 18:21:19.960: W/System.err(1252): at android.os.Handler.handleCallback(Handler.java:587)
02-15 18:21:19.960: W/System.err(1252): at android.os.Handler.dispatchMessage(Handler.java:92)
02-15 18:21:19.960: W/System.err(1252): at android.os.Looper.loop(Looper.java:130)
02-15 18:21:19.960: W/System.err(1252): at android.app.ActivityThread.main(ActivityThread.java:3691)
02-15 18:21:19.960: W/System.err(1252): at java.lang.reflect.Method.invokeNative(Native Method)
02-15 18:21:19.970: W/System.err(1252): at java.lang.reflect.Method.invoke(Method.java:507)
02-15 18:21:19.970: W/System.err(1252): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
02-15 18:21:19.970: W/System.err(1252): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670)
02-15 18:21:19.970: W/System.err(1252): at dalvik.system.NativeStart.main(Native Method)
编辑:
我以这种方式推介了mChatSession:
mChatService = new BluetoothService(this, mHandler);
并称之为: mChatService.write(发送);
但类似的NullPointerException错误仍然存在。
答案 0 :(得分:0)
我猜你得到了例外,因为你还没有初始化BluetoothService
。
private BluetoothService mChatService = null;
您在mChatService.getState()
方法中使用sendMessage()
而未初始化。
答案 1 :(得分:0)
尝试
if(mChatService == null)
return;
if (message.length() > 0 && mChatService.getState() == BluetoothService.STATE_CONNECTED) {
byte[] send = message.getBytes();
mChatService.write(send);
}
答案 2 :(得分:0)
BluetoothService mChatService = new BluetoothService(args);
您需要在某个时刻为变量分配一个实例。