简体   繁体   English

Android 蓝牙崩溃应用程序

[英]Android bluetooth crashing application

Having some trouble using device.getName() .使用device.getName()遇到一些问题。 It's for some reason causing my application to crash.出于某种原因导致我的应用程序崩溃。

What I'm doing is displaying an adapter (holding bluetooth names) in a dialogue box.我正在做的是在对话框中显示一个适配器(保存蓝牙名称)。 When I run the application and adding device.getAdress() instead of - .getName() the application works fine, but when doing it with .getName() it crashes.当我运行应用程序并添加device.getAdress()而不是 - .getName()应用程序工作正常,但使用.getName()它崩溃了。

mBluetoothAdapter.startDiscovery();
receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            toothadapter.add(device.getName());
            toothadapter.notifyDataSetChanged();
        }
    }
};
AlertDialog.Builder builder = new AlertDialog.Builder(bluetooth.this);
builder.setTitle("Nearby Devices:");
builder.setAdapter(toothadapter, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {

    }
});
AlertDialog alert = builder.create();
alert.show();

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);

Really need some help as to why this is happening.真的需要一些帮助来了解为什么会发生这种情况。 The code above this, is all included in onCreate() within a buttonListener .上面的代码全部包含在buttonListener中的onCreate()中。

Really need some help as to why this is happening.真的需要一些帮助来了解为什么会发生这种情况。

It is hardly possible to say for sure what causes the app crash without seeing the stacktrace.在没有看到堆栈跟踪的情况下,很难确定是什么导致了应用程序崩溃。

However note that BluetoothDevice.getName() returns null if "there was a problem" .但是请注意,如果“有问题”BluetoothDevice.getName()将返回null And we know (from the Toast notifications you get) that the method returns null s in the app.我们知道(从您收到的Toast通知中)该方法在应用程序中返回null These null s may or may not be the reason of the crash.这些null可能是也可能不是崩溃的原因。

In addition, the place where null device name cannot cause NPE is ArrayAdapter .另外, null设备名不能导致NPEArrayAdapter When you call new ArrayAdapter<String>(Context, int) the following constructor is invoked:当您调用new ArrayAdapter<String>(Context, int)将调用以下构造函数

public ArrayAdapter(Context context, int resource) {
    init(context, resource, 0, new ArrayList<T>());
}

Data structure used to store your data is ArrayList whose add() 's method implementation allows adding null as opposed to the List<> 's add() method declaration.用于存储数据的数据结构是ArrayListadd()的方法实现允许添加null ,而不是List<>add()方法声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM