我正在开发一个应用程序,其中蓝牙控制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 进程: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(未知来源: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(本机方法) 在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void java.io.OutputStream.write(byte [])' 在com.example.btcar2.MainActivity.onCreate(MainActivity.java:51) 在android.app.Activity.performCreate(Activity.java:7016) 在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2905) 在android.app.ActivityThread.-wrap11(未知来源: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(本机方法) 在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240) com.android.internal.os.ZygoteInit.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();
}
}
答案 0 :(得分:0)
outputStream
为null,您必须为其创建一个新对象,就像您在BTconnect()
outputStream = socket.getOutputStream();
答案 1 :(得分:0)
正如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
}