[英]"if (switch.isChecked())" statement makes my app crash
我正在制作一个应用程序,其中蓝牙控制 Arduino 汽车。 我正在尝试使用开关来打开和关闭电机(现在是 LED),但是当我使用以下代码运行应用程序时,它崩溃了。
if (on_off_switch.isChecked()) {
command = "1";
try {
outputStream.write(command.getBytes()); //transmits the value of command to the bluetooth module
} catch (IOException e) {
e.printStackTrace();
}
} else {
command = "10";
try {
outputStream.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
但是当我在没有该代码部分的情况下运行应用程序时,它运行得很好。 但是当我用代码运行它时,应用程序没有启动,Logcat 说:
--------- 崩溃开始 2018-11-10 14:22:36.570 3311-3311/com.example.btcar2 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.btcar2, PID: 3311 java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.example.btcar2/com.example.btcar2.MainActivity}: java.lang.NullPointerException: 尝试调用虚拟方法 'void java.io.OutputStream.write(byte[ ])' 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2905) 在 android.app.ActivityThread.-wrap11(Unknown Source) 的空对象引用:0) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) 在 android.os.Handler.dispatchMessage(Handler.java:105) 在 android.os.Looper.loop(Looper.java:169)在 android.app.ActivityThread.main(ActivityThread.java:6595) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)在 com.android.in ternal.os.ZygoteInit.main(ZygoteInit.java:767) 导致:java.lang.NullPointerException:尝试在 com 的空对象引用上调用虚方法“void java.io.OutputStream.write(byte[])” .example.btcar2.MainActivity.onCreate(MainActivity.java:51) at android.app.Activity.performCreate(Activity.java:7016) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) at android.app。 ActivityThread.performLaunchActivity(ActivityThread.java:2783) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2905) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1606) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:169) at android.app.ActivityThread.main(ActivityThread.java: 6595) 在 java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.Zy goteInit.main(ZygoteInit.java:767)
我不知道如何修复它。 如果您有可能对我的情况有所帮助的问题,请写信,谢谢。
这是我的其余代码
public class MainActivity extends AppCompatActivity {
final String DEVICE_ADDRESS = "00:12:12:24:06:48"; //MAC Address of Bluetooth Module
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
Button bluetooth_connect_btn;
String command; //string variable that will store value to be transmitted to the bluetooth module
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch on_off_switch = (Switch) findViewById(R.id.on_off_switch);
on_off_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.v("Switch State=", "" + isChecked);
}
});
if (on_off_switch.isChecked()) {
command = "1";
try {
outputStream.write(command.getBytes()); //transmits the value of command to the bluetooth module
} catch (IOException e) {
e.printStackTrace();
}
} else {
command = "10";
try {
outputStream.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
bluetooth_connect_btn = (Button) findViewById(R.id.bluetooth_connect_btn);
//Button that connects the device to the bluetooth module when pressed
bluetooth_connect_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (BTint()) {
BTconnect();
}
}
});
}
//Initializes bluetooth module
public boolean BTint() {
boolean found = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) //Checks if the device supports bluetooth
Toast.makeText(getApplicationContext(), "Device doesn't support bluetooth", Toast.LENGTH_SHORT).show();
if (!bluetoothAdapter.isEnabled()) //Checks if bluetooth is enabled. If not, the program will ask permission from the user to enable it
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bondedDevices.isEmpty()) //Checks for paired bluetooth devices
Toast.makeText(getApplicationContext(), "Please pair the device first", Toast.LENGTH_SHORT).show();
else {
for (BluetoothDevice iterator : bondedDevices) {
if (iterator.getAddress().equals(DEVICE_ADDRESS)) {
device = iterator;
found = true;
break;
}
}
}
return found;
}
public boolean BTconnect() {
boolean connected = true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID); //Creates a socket to handle the outgoing connection
socket.connect();
Toast.makeText(getApplicationContext(),
"Connection to bluetooth device successful", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
if (connected) {
try {
outputStream = socket.getOutputStream(); //gets the output stream of the socket
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
@Override
protected void onStart() {
super.onStart();
}
}
outputStream
为 null ,您必须为其创建一个新对象,就像您在BTconnect()
outputStream = socket.getOutputStream();
所做的BTconnect()
正如 Amjad Alwareh 所说, outputStream
对象为空。 您可以从 Logcat 中的这条语句中看到:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void java.io.OutputStream.write(byte[])”
通过把这个代码
if (on_off_switch.isChecked()) {
command = "1";
try {
outputStream.write(command.getBytes()); //transmits the value of command to the bluetooth module
} catch (IOException e) {
e.printStackTrace();
}
} else {
command = "10";
try {
outputStream.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
在onCreate
您正在尝试使用蓝牙模块执行某些操作,而无需确保您有连接。
我不知道你的设计以及你想要达到的目标。 但我可以建议将上面的代码放在一个单独的方法中,如下所示:
private void performAction() {
if (on_off_switch.isChecked()) {
command = "1";
try {
outputStream.write(command.getBytes()); //transmits the value of command to the bluetooth module
} catch (IOException e) {
e.printStackTrace();
}
} else {
command = "10";
try {
outputStream.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
然后在BTconnect()
调用它,如果你想在连接建立后立即做一些事情:
// code before
if (connected) {
try {
outputStream = socket.getOutputStream(); //gets the output stream of the socket
performAction(); // call it here
} catch (IOException e) {
e.printStackTrace();
}
}
或者在onCheckedChanged
调用这个方法
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.v("Switch State=", "" + isChecked);
performAction(); // call it here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.