由于出现空指针错误,Android蓝牙应用无法运行

时间:2018-09-08 22:18:41

标签: java android android-studio bluetooth

由于Null指针异常,蓝牙应用程序将无法运行。没有错误,但是我看不到连接到模拟器,因为该应用程序每次都崩溃。即使我尝试示例GitHub代码,它也不会运行。我将发布代码和目录,以及您需要的其他任何东西。谢谢您的帮助

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:启动即时运行服务器:是主进程 09-08 22:03:46.416 5869-5869 /? E / BluetoothAdapter:蓝牙活页夹为空 09-08 22:03:46.416 5869-5869 /? D / AndroidRuntime:关闭VM 09-08 22:03:46.418 5869-5869 /? E / AndroidRuntime:致命异常:main     流程:com.example.bluetooth_demoproject,PID:5869     java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.bluetooth_demoproject / com.example.bluetooth_demoproject.MainActivity}:java.lang.NullPointerException:尝试调用虚拟方法'boolean android.bluetooth.BluetoothAdapter.isEnabled()'在空对象引用上         在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)         在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)         在android.app.ActivityThread.access $ 800(ActivityThread.java:151)         在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1303)         在android.os.Handler.dispatchMessage(Handler.java:102)         在android.os.Looper.loop(Looper.java:135)         在android.app.ActivityThread.main(ActivityThread.java:5254)         在java.lang.reflect.Method.invoke(本机方法)         在java.lang.reflect.Method.invoke(Method.java:372)         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903)         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)      原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'boolean android.bluetooth.BluetoothAdapter.isEnabled()'         在com.example.bluetooth_demoproject.MainActivity.onCreate(MainActivity.java:57)         在android.app.Activity.performCreate(Activity.java:5990)         在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)         在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)         在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)         在android.app.ActivityThread.access $ 800(ActivityThread.java:151)         在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1303)         在android.os.Handler.dispatchMessage(Handler.java:102)         在android.os.Looper.loop(Looper.java:135)         在android.app.ActivityThread.main(ActivityThread.java:5254)         在java.lang.reflect.Method.invoke(本机方法)         在java.lang.reflect.Method.invoke(Method.java:372)         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903)         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 09-08 22:03:46.431 1510-2232 / system_process W / ActivityManager:强制完成活动1 com.example.bluetooth_demoproject / .MainActivity enter code here

1 个答案:

答案 0 :(得分:1)

问题似乎出在第59行:if (!mBluetoothAdapter.isEnabled()) {

注意:错误消息显示第57行,但在我的文本编辑器中显示为59。

在上面的几行中,通过检查对象mBluetoothAdapter是否为== null,来检查对象.isEnabled()是否已成功创建。但是之后,您调用其方法:mBluetoothAdapter。我认为问题在于null即将变成// 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); } } ,因此在您尝试访问其方法之一时会引发NullPointerException。

如果我理解正确,我认为解决方案将是这样的:

mBluetoothAdapter

这将使启用代码远离值为null的{​​{1}}。

或者,如果蓝牙不可用,则可以使用return退出该方法。

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

这将以更简洁的方式完成同样的工作。

我认为对您来说下一步是找出为什么BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();返回null而不是您想要的对象的原因。我认为您的MainActivity方法中没有答案。该设备找不到默认适配器,这可能是许多问题的结果。