android - 安卓中的蓝牙

标签 android bluetooth nullpointerexception

我目前正在开发一个使用蓝牙进行通信的软件。

这是我的蓝牙类(class):

public class btClass extends Activity  implements View.OnClickListener
{
    private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    private static final int REQUEST_ENABLE_BT = 10;
    private Context context;
    private btReceiver mReceiver = new btReceiver();
    private String[] result = new String[]{""};
    private Activity hangar;

    public btClass()
    {
        if (!this.adapter.isEnabled())
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

            startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);

            int result = 0;
            onActivityResult(REQUEST_ENABLE_BT, result, enableBtIntent);
            if(result != RESULT_OK)
            {
                String exception = "Bluetooth failure!\r\nEnabling bluetooth adapter failed!";

                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this.context);
                dlgAlert.setMessage(exception);
                dlgAlert.setTitle("Hangar error");
                dlgAlert.setPositiveButton("OK", null);
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();
            }
        }
    }

    @Override
    protected void onCreate(Bundle intent)
    {
        super.onCreate(intent);

        this.hangar = this.getParent();

        this.context = this.getApplicationContext();
    }

    public void onClick(View v) 
    {
        doDiscovery();      
    }

    private void doDiscovery()
    {
        if(this.adapter.isDiscovering())
            this.adapter.cancelDiscovery();

        if(!this.adapter.startDiscovery())
        {
            String exception = "Bluetooth failure!\r\nDiscovering bluetooth devices failed!";

            AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this.context);
            dlgAlert.setMessage(exception);
            dlgAlert.setTitle("Hangar error");
            dlgAlert.setPositiveButton("OK", null);
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
        }

        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        try
        {
            this.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestr
        }
        catch(Exception e)
        {
            String exception = "'registerReceiver' threw Exception of type '" + e.getMessage();
            StackTraceElement[] trace = e.getStackTrace();
            for(int i = 0; i < trace.length; i++)
                exception = exception + "\r\n" + trace[i];

            AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
            dlgAlert.setMessage(exception);
            dlgAlert.setTitle("Hangar error");
            dlgAlert.setPositiveButton("OK", null);
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
        }

        while(this.adapter.isDiscovering())
            ;

        unregisterReceiver(this.mReceiver);

        result = new String[]{""};
        if(this.mReceiver != null)
            result = this.mReceiver.foundDevicesNames();
    }

    public String[] getBluetoothDevices()
    {       
        return result;
    }
}

现在的问题是,当我在第 16 行调用 startActivityForResult 时,我捕获了一个“nullPointerException”。

我的错在哪里?

问候 亨里克

编辑: 新代码:

package de.schweigstill.hangar;

import android.bluetooth.*;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.app.Activity;
import android.app.AlertDialog;

public class btClass extends Activity  implements View.OnClickListener
{
    private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    private static final int REQUEST_ENABLE_BT = 10;
    private Context context;
    private btReceiver mReceiver = new btReceiver();
    private String[] result = new String[]{""};
    private HangarActivity hangar;

    public btClass(Context context)
    {
        super();
    }

    @Override
    public void onCreate(Bundle intent)
    {
        super.onCreate(intent);

        this.hangar = (HangarActivity)this.getParent();

        this.context = this.getApplicationContext();
    }

    public void onClick(View v) 
    {
        if (!this.adapter.isEnabled())
        {
            Intent enableBtIntent = new intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);

            int result = 0;
            onActivityResult(REQUEST_ENABLE_BT, result, enableBtIntent);
            if(result != RESULT_OK)
            {
                String exception = "Bluetooth failure!\r\nEnabling bluetooth adapter failed!";

                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this.context);
                dlgAlert.setMessage(exception);
                dlgAlert.setTitle("Hangar error");
                dlgAlert.setPositiveButton("OK", null);
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();
            }
        }

        doDiscovery();      
    }

    private void doDiscovery()
    {
        try
        {           
            if(this.adapter.isDiscovering())
                this.adapter.cancelDiscovery();

            if(!this.adapter.startDiscovery())
            {
                String exception = "Bluetooth failure!\r\nDiscovering bluetooth devices failed!";

                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this.context);
                dlgAlert.setMessage(exception);
                dlgAlert.setTitle("Hangar error");
                dlgAlert.setPositiveButton("OK", null);
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();
            }

            // Register the BroadcastReceiver
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

            this.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestr

            while(this.adapter.isDiscovering())
                ;

            unregisterReceiver(this.mReceiver);

            result = new String[]{""};
            if(this.mReceiver != null)
            {
                result = this.mReceiver.foundDevicesNames();
                for(int i = 0; i < result.length; i++)
                    this.hangar.aAd.add(result[i]);
            }
        }
        catch(Exception e)
        {
            String exception = "In 'doDiscovery()' has an Exception of type '" + e.toString() + "' been thrown \r\n Trace:";//.getMessage();
            StackTraceElement[] trace = e.getStackTrace();
            for(int i = 0; i < trace.length; i++)
                exception = exception + "\r\n" + trace[i];

            AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
            dlgAlert.setMessage(exception);
            dlgAlert.setTitle("Hangar error");
            dlgAlert.setPositiveButton("OK", null);
            dlgAlert.setCancelable(true);
            dlgAlert.create().show();
        }
    }

    public String[] getBluetoothDevices()
    {       
        return result;
    }
}

最佳答案

btReceiver类的代码是什么?

试试这个:

从您的 btClass 中删除以下行:

private btReceiver mReceiver = new btReceiver();

在您的 btClass 中像这样创建一个 BroadcastReceiver:

 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };

关于android - 安卓中的蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8560759/

相关文章:

Android 图像按钮淡入淡出

android - 如何更新Dart类变量并刷新抖动状态?

Android:蓝牙获取端口号失败

java - 无法访问 onItemClick 方法中的 Activity 项目

java - 我的程序中出现 NullPointerException

android - 为eclipse创建一个8英寸平板电脑模拟器android

java.lang.ClassCastException : cannot be cast to RssLargeViewHolder

linux - 在 Linux 中通过蓝牙访问 Neurosky Mindset 的串行数据

php - 如何从 php 运行 Python 脚本

java - 我在 IntelliJ IDEA 和 TomCat 中收到 java.lang.NullPointerException