【问题标题】:"if (switch.isChecked())" statement makes my app crash“if (switch.isChecked())”语句使我的应用程序崩溃
【发布时间】:2018-11-10 12:45:37
【问题描述】:

我正在制作一个蓝牙控制 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: 致命异常: 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();
    }

}

【问题讨论】:

  • 能否添加更多出现在 Logcat 中的崩溃消息?
  • 完整的堆栈跟踪可能会有所帮助
  • 我现在已经编辑好了,所以你可以看到所有的崩溃信息
  • 考虑到这个声明:on_off_switch.isChecked() 我们真的有什么方法吗? isChecked() 在 Android 的 Switch 类中?好吧,我认为 CheckBox 类确实有。

标签: java android arduino


【解决方案1】:

正如 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
}

【讨论】:

    【解决方案2】:

    outputStream 为空,你必须为其创建一个新对象,就像你在BTconnect() outputStream = socket.getOutputStream(); 中所做的那样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      相关资源
      最近更新 更多