Android Bluetooth app wont run due to Null pointer error

给你一囗甜甜゛ 提交于 2021-01-29 10:54:30

问题


Bluetooth app won't run due to Null pointer exceptions. No errors, but I can't see to connect to the emulator as the app just crashes every time. Even if I try sample GitHub codes, it won't run either. I'll post code and catlog and anything else you need. Thank you for your help

package com.example.bluetooth_demoproject;

import android.app.Activity;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.Set;

public class MainActivity extends Activity {


private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVER_BT_ = 1;

TextView mBluetoothStatus, mPairedDevicelist;
ImageView mBluetoothIcon;
Button mOnButton, mOffButton, mDiscoverableButton, mPairedDevices, 
mSendImage;

BluetoothAdapter mBlueAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
    mBluetoothStatus = findViewById(R.id.BluetoothStatus);
    mPairedDevicelist = findViewById(R.id.pairedDeviceList);
    mBluetoothIcon = findViewById(R.id.bluetoothIcon);
    mOnButton = findViewById(R.id.onButton);
    mOffButton = findViewById(R.id.offButton);
    mDiscoverableButton = findViewById(R.id.discoverableButton);
    mPairedDevices = findViewById(R.id.pairedDevices);
    mSendImage = findViewById(R.id.sendImage);


    //adapter
   BluetoothAdapter mBluetoothAdapter = 
  BluetoothAdapter.getDefaultAdapter();

    // check if bluetooth is available
    if(mBluetoothAdapter == null){
        mBluetoothStatus.setText("Bluetooth is not available");
    }
    else {
        mBluetoothStatus.setText("Bluetooth is available");
        }
        //if Bluetooth isnt enabled, enable it
    if (!mBluetoothAdapter.isEnabled()) {
       Intent enableBtIntent = new 
   Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }


    //on button Click
    mOnButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            if (!mBlueAdapter.isEnabled()) {
                showToast("Turning Bluetooth on...");
                // intent to on bluetooth
                Intent intent = new 
  Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent, REQUEST_ENABLE_BT);

            }
            else {
                showToast("Bluetooth is already on");
            }

        }
    });

    //discover Bluetooth button
    mDiscoverableButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            if (!mBlueAdapter.isDiscovering()) {
                showToast("Discovering devices..");
                Intent intent = new 
       Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivityForResult(intent, REQUEST_DISCOVER_BT_);
            }

        }

    });

    // off button click
    mOffButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mBlueAdapter.isEnabled()) {
                showToast("Turning Bluetooth off...");
                // intent to turn off bluetooth
                mBluetoothIcon.setImageResource(R.drawable.action_off);
            }
            else{
                showToast("Bluetooth is already off");
            }

        }
    });



    //get paired device button click


    Set<BluetoothDevice> pairedDevices = 
    mBluetoothAdapter.getBondedDevices();
       if (pairedDevices.size() > 0) {
           // Retrieve the name and address of the paired devices
           for (BluetoothDevice device: pairedDevices) {
               String deviceName = device.getName();
               String deviceAddr = device.getAddress();
           }
       }





}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent 
     data) {
     switch (requestCode) {
        case REQUEST_ENABLE_BT:
            if (resultCode == RESULT_OK){
                //bluetooth is on
                mBluetoothIcon.setImageResource(R.drawable.action_on);
                showToast("Bluetooth is on");
            }
            else {
                //user is denied turning on Bluetooth
                showToast("Unable to turn on Bluetooth");
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

//toast message function
private void showToast(String msg) {
    Toast.makeText(this, msg, Toast.LENGTH_SHORT) .show();
}

   }



    9-08 22:03:46.371 1510-2830/system_process W/ActivityManager: 
  getRunningAppProcesses: caller 10060 does not hold REAL_GET_TASKS; 
    limiting output

09-08 22:03:46.372 5869-5869/? I/InstantRun: starting instant run server: is main process 09-08 22:03:46.416 5869-5869/? E/BluetoothAdapter: Bluetooth binder is null 09-08 22:03:46.416 5869-5869/? D/AndroidRuntime: Shutting down VM 09-08 22:03:46.418 5869-5869/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.bluetooth_demoproject, PID: 5869 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bluetooth_demoproject/com.example.bluetooth_demoproject.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference at com.example.bluetooth_demoproject.MainActivity.onCreate(MainActivity.java:57) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  at android.app.ActivityThread.access$800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  09-08 22:03:46.431 1510-2232/system_process W/ActivityManager: Force finishing activity 1 com.example.bluetooth_demoproject/.MainActivityenter code here


回答1:


It looks like the problem is from line 59: if (!mBluetoothAdapter.isEnabled()) {

Note: The error message says line 57, but in my text editor it says 59.

A few lines above, you check whether the object mBluetoothAdapter was successfully created by checking if it's == null. But after that, you call its method: .isEnabled(). I think the problem is that mBluetoothAdapter is becoming null and therefore throws a NullPointerException when you try to access one of its methods.

If I understand correctly, I think the solution would be something like this:

// check if bluetooth is available
if(mBluetoothAdapter == null){
    mBluetoothStatus.setText("Bluetooth is not available");
}
else {
    mBluetoothStatus.setText("Bluetooth is available");
    //if Bluetooth isnt enabled, enable it
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new 
            Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}

This would keep the enabling code away from a mBluetoothAdapter with a value of null.

Alternativly, you could use return to exit the method if BlueTooth isn't available.

// check if bluetooth is available
if(mBluetoothAdapter == null){
    mBluetoothStatus.setText("Bluetooth is not available");
    return;
}
else {
    mBluetoothStatus.setText("Bluetooth is available");
    }
    //if Bluetooth isnt enabled, enable it
if (!mBluetoothAdapter.isEnabled()) {
   Intent enableBtIntent = new 
       Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
   startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

This would do the same in a little bit of a cleaner way.

I think the next step for you is to find out why BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); is returning null instead of the object you want. I don't think the answer to that is in your MainActivity method. The device isn't finding a default adapter and that could be the result of numerous problems.



来源:https://stackoverflow.com/questions/52239820/android-bluetooth-app-wont-run-due-to-null-pointer-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!