The application crashes if the blues on the device is not enabled

D/bluetooth: onResume - попытка соединения E/BluetoothDevice: Bluetooth is not enabled D/bluetooth: ....соединяемся... D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.jeka.toolcarcontrol, PID: 21370 java.lang.RuntimeException: Unable to resume activity {com.example.jeka.toolcarcontrol/com.example.jeka.toolcarcontrol.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.BluetoothSocket.connect()' on a null object reference at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4221) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426) at android.app.ActivityThread.access$1100(ActivityThread.java:229) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:7325) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.BluetoothSocket.connect()' on a null object reference at com.example.jeka.toolcarcontrol.MainActivity.onResume(MainActivity.java:110) at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287) at android.app.Activity.performResume(Activity.java:7015) at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426) at android.app.ActivityThread.access$1100(ActivityThread.java:229) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:7325) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) I/Process: Sending signal. PID: 21370 SIG: 9 Application terminated. 

Here is the application code

 import android.annotation.SuppressLint; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; public class MainActivity extends Activity { private static final String Tag = "bluetooth"; ImageButton img_button_up, img_button_down; TextView parameter1; Handler handler; private static final int REQUEST_ENABLE_BT = 1; BluetoothAdapter bluetoothAdapter; BluetoothSocket bluetoothSocket; OutputStream outputStream; private StringBuilder stringBuilder = new StringBuilder(); private ConectionTread conectionTread; private static final UUID my_uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final String module_adress = "20:13:01:29:12:61"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_xml_land); img_button_up = (ImageButton) findViewById(R.id.img_but_up); img_button_down = (ImageButton) findViewById(R.id.img_but_down); parameter1 = (TextView) findViewById(R.id.parm1); handler = new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what){ case 1: byte[] readBuffer = (byte[]) msg.obj; String strIncom = new String(readBuffer, 0, msg.arg1); int end_of__line_indx = stringBuilder.indexOf(";"); //not working, return -1 Log.d(Tag, strIncom); Log.d(Tag, String.valueOf(end_of__line_indx)); if (end_of__line_indx > 0){ String strBuild_print = stringBuilder.substring(0, end_of__line_indx); //get text, from 0 index to last index stringBuilder.delete(0, stringBuilder.length()); parameter1.setText("param 1: " + strBuild_print); Log.d(Tag, strIncom); } } } }; bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); chackBluetoothState(); img_button_up.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { conectionTread.write("1"); // Send 1 to module } }); img_button_down.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { conectionTread.write("0"); } }); } @Override public void onStart(){ super.onStart(); if (!bluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } } @Override public void onResume(){ super.onResume(); Log.d(Tag, " onResume - попытка соединения"); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(module_adress); try { bluetoothSocket = device.createRfcommSocketToServiceRecord(my_uuid); } catch (IOException e) { errorExit("Fatal Error", "Ошибка в onResume, проблема создания сокета " + e.getMessage()); } Log.d(Tag, " ....соединяемся..."); try { bluetoothSocket.connect(); Toast.makeText(this,"Соединение установлено", Toast.LENGTH_LONG).show(); Log.d(Tag, "...Соединение установлено и готово к передаче данных..."); } catch (IOException e) { try { bluetoothSocket.close(); } catch (IOException e1) { Log.d(Tag, "..Ошибка закрытия порта..."); } Toast.makeText(this,"Соединение не установлено", Toast.LENGTH_LONG).show(); Log.d(Tag, "...Соединение не установлено..."); } Log.d(Tag, "..Создание Сокета.."); try { outputStream = bluetoothSocket.getOutputStream(); } catch (IOException e) { errorExit("Fatal Error", " Ошибка в onResume, не удалось создать выходной поток " + e.getMessage()); } conectionTread = new ConectionTread(bluetoothSocket); conectionTread.start(); } @Override public void onPause(){ super.onPause(); Log.d(Tag, "...InPause.."); if (outputStream != null) { try { outputStream.flush(); } catch (IOException e) { errorExit("Fatal Error", "ошибка в onPause(), не удалось очистить выходной поток " + e.getMessage()); } } try { bluetoothSocket.close(); } catch (IOException e1) { errorExit("Fatal Error", " ошибка в onPause, не удалось закрыть сокет" + e1.getMessage()); } } private void chackBluetoothState() { if (bluetoothAdapter == null){ errorExit("Fatal Error", "Bluetooth не поддерживается"); finish(); } } private void errorExit(String title, String massage) { Toast.makeText(getBaseContext(), title + " - " + massage, Toast.LENGTH_LONG).show(); finish(); } class ConectionTread extends Thread{ private final BluetoothSocket mmSocket; private final InputStream mmInputStream; private final OutputStream mmOutStream; public ConectionTread(BluetoothSocket socket){ mmSocket = socket; InputStream streamIn = null; OutputStream streamOut = null; try { streamIn = socket.getInputStream(); streamOut = socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } mmInputStream = streamIn; mmOutStream = streamOut; } public void run(){ byte[] buffer = new byte[256]; int bytes; while (true){ try { //Read InputStream if (mmInputStream != null) { bytes = mmInputStream.read(buffer); // get byteArray in "buffer" handler.obtainMessage(1, bytes, -1, buffer).sendToTarget(); // send message to Handler } } catch (IOException e) { e.printStackTrace(); break; } } } public void write(String message){ Log.d(Tag, "...Данные для отправки: " + message ); byte[] msgBuffer = message.getBytes(); try { if(mmOutStream != null) mmOutStream.write(msgBuffer); } catch (IOException e) { e.printStackTrace(); Log.d(Tag, "...Ошибка отправки данных: " + e.getMessage() + "..."); } } public void cancel(){ try { mmSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } 

    1 answer 1

    And what's the problem? You do not understand why the program crashes?

    So in the stack-trace it is clearly written:

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.BluetoothSocket.connect()' on a null object reference 

    That is, you have bluetoothSocket == null .

    UPD. You can check if bluetooth turned on like this :

     BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth } else { if (!mBluetoothAdapter.isEnabled()) { // Bluetooth is not enable :) } } 

    Further, if bluetooth turned off, then you can ask the user to turn it on, if the device does not support bluetooth , then show the corresponding notification.

    UPD 2 . In the onStart() method, you ask the user to enable bluetooth starting startActivityForResult(enableIntent, REQUEST_ENABLE_BT); , but the fact is that the onResume() method (in which you are trying to connect) works before the user turns on bluetooth (if it turns on at all). You need in the onActivityResult(...) method to get the result, and if the user has turned on bluetooth , then make a connection.

    • I understand this) I need to first ask the user to turn on the bluetooth and then continue to work, and it turns out that the socket == null, sorry I did not describe the problem properly - UjinUkr
    • @UjinUkr, See UPD . - post_zeew
    • if you look into my code, or rather into the chackBluetoothState () and onStart () methods, you will understand that I do almost the same thing that you described - UjinUkr
    • @UjinUkr, So you have a connection before you turn on bluetooth . - post_zeew 10:49
    • And anyway, I don’t really understand why you are connecting to onResume() . Here you start startActivityForResult(enableIntent, REQUEST_ENABLE_BT); and depending on what it returns to you, you must either connect or not. - post_zeew