This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


2年前关闭。




我使用OnClickListener以这种方式执行方法:
    b= (Button) findViewById(R.id.b);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (on){
                try {sendData("b");} catch (IOException e) {e.printStackTrace();}
            }
            else {Toast.makeText(getApplicationContext(), "You should turn bluetooth on!", Toast.LENGTH_SHORT).show();}
        }
    });
sendData方法:
public void sendData(String s) throws IOException {
    try {
        byte[] byteString = s.getBytes();
        outputStream.write(byteString);
        outputStream.flush();
        Toast.makeText(getApplicationContext(), s + "sent", Toast.LENGTH_SHORT).show();
    }catch (IOException e) {
        Toast.makeText(getApplicationContext(), s + "not sent", Toast.LENGTH_SHORT).show();
        e.printStackTrace();}
}

如果on = true,这会使我的应用崩溃



如何防止它退出?

谢谢!

最佳答案

您只是在捕获IOException。捕获任何Exception,它应该可以工作。我怀疑您的outputStream为空。

08-06 10:16