-1

I use a OnClickListener to execute a method this way :

    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 method :

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();}
}

this makes my app crashes if on = true

03-28 08:37:09.733 28841-28841/com.android.map.brasrobotique E/AndroidRuntime: FATAL EXCEPTION: main Process: com.android.map.brasrobotique, PID: 28841 java.lang.NullPointerException at com.android.map.brasrobotique.MainActivity.sendData(MainActivity.java:221) at com.android.map.brasrobotique.MainActivity$2.onClick(MainActivity.java:77) at android.view.View.performClick(View.java:4633) at android.view.View$PerformClick.run(View.java:19270) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:146) at android.app.ActivityThread.main(ActivityThread.java:5602) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) at dalvik.system.NativeStart.main(Native Method)

how to prevent it from exiting?

thank you!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Takichiii
  • 453
  • 4
  • 14
  • 27

2 Answers2

1

Try :

b= (Button) findViewById(R.id.b);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (on){
                    try {sendData("b");} catch (IOException | NullPointerException e) {e.printStackTrace();}
                }
                else {Toast.makeText(getApplicationContext(), "You should turn bluetooth on!", Toast.LENGTH_SHORT).show();}
            }
        });

This will catch NullPointerException and IOException

Benkerroum Mohamed
  • 1,867
  • 3
  • 13
  • 19
0

You're just catching IOExceptions. Catch any Exception and it should work. I suspect that your outputStream is null.

mbrandau
  • 544
  • 3
  • 14