首页 > 解决方案 > “if (switch.isChecked())”语句使我的应用程序崩溃

问题描述

我正在制作一个蓝牙控制 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.-wrap11 的 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2905) 的 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830) 的空对象引用上。-wrap11(Unknown Source :0) 在 android.os.Handler.dispatchMessage(Handler.java:105) 在 android.os.Looper 的 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)。在 com.android.internal.os.Zygote$MethodAndArgsCaller 的 java.lang.reflect.Method.invoke(Native Method) 的 android.app.ActivityThread.main(ActivityThread.java:6595) 的循环(Looper.java:169)。在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 处运行(Zygote.java:240) 原因:java.lang.NullPointerException:尝试调用虚拟方法 'void java.io.OutputStream.write (byte[])' 在 android.app.Instrumentation 的 com.example.btcar2.MainActivity.onCreate(MainActivity.java:51) 的 android.app.Activity.performCreate(Activity.java:7016) 的空对象引用上。在 android.app.ActivityThread 的 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783) 处调用ActivityOnCreate(Instrumentation.java:1214)。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) 在 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.internal.os.ZygoteInit.main(ZygoteInit.java:767)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.internal.os.ZygoteInit.main(ZygoteInit.java:767)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.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();
    }

}

标签: javaandroidarduino

解决方案


outputStream是 null ,你必须创建一个它的新对象,就像你在做什么BTconnect() outputStream = socket.getOutputStream();


推荐阅读