由于Null指针错误,Android蓝牙应用程序将无法运行 [英] Android Bluetooth app wont run due to Null pointer error

查看:134
本文介绍了由于Null指针错误,Android蓝牙应用程序将无法运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:启动即时运行服务器:是主进程09-08 22:03:46.416 5869-5869/?E/BluetoothAdapter:蓝牙活页夹为空09-08 22:03:46.416 5869-5869/?D/AndroidRuntime:关闭虚拟机09-08 22:03:46.418 5869-5869/?E/AndroidRuntime:致命异常:main流程:com.example.bluetooth_demoproject,PID:5869java.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 在此处输入代码

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

推荐答案

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

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

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

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

在上面几行中,通过检查对象 mBluetoothAdapter 是否为 == null ,来检查其是否已成功创建.但是之后,您调用其方法: .isEnabled().我认为问题是 mBluetoothAdapter 变为 null ,因此当您尝试访问其方法之一时会引发NullPointerException.

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

这将使启用代码远离值为 null mBluetoothAdapter .

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

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

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.

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

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.

这篇关于由于Null指针错误,Android蓝牙应用程序将无法运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆