蓝牙发现过程中应用崩溃

时间:2016-03-17 06:46:34

标签: java android exception-handling bluetooth android-bluetooth

我想做的事

我正在尝试创建一个搜索附近所有蓝牙设备的应用,并连接到用户希望连接的设备。

我试图在一个活动中创建一个Connect按钮,在另一个活动中启动发现功能

我是如何尝试的

所以我有这个具有Connect按钮的 MainActivity.java 类/活动。点击此按钮后,它应该做三件事:

  1. 检查智能手机上的蓝牙是否已开启&如果不是,请将其打开。
  2. 显示TOAST消息以显示BT是否已成功启用
  3. 开始这项名为 SearchBTDevice.java 的新活动,该活动会查找附近的BT设备&将它们列在ListView
  4. 前两个是完美的工作,因为他们在MainActivity.java&那是我的按钮创建的地方。

    当它创建新活动&试图做第三个。该应用程序崩溃。

    这是我 MainActivity.java 的样子

    package vertex2016.mvjce.edu.bluealert;
    
    import android.bluetooth.BluetoothAdapter;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.Gravity;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Toast;
    
    import static java.lang.Thread.sleep;
    
    public class MainActivity extends AppCompatActivity {
    
        public BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
        private int REQ_CODE = 1;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        public void connect(View v)
        {
            if(BA == null)
                Toast.makeText(MainActivity.this, "System Doesn't Support Bluetooth", Toast.LENGTH_SHORT).show();
    
            else if(!BA.isEnabled())
            {
                Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBT, REQ_CODE);
            }
            else {
                Toast.makeText(MainActivity.this, "ALREADY ON!!", Toast.LENGTH_SHORT).show();
                searchBTDevices();
            }
        }
    
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(resultCode!=RESULT_CANCELED) {
                Toast.makeText(MainActivity.this, "TURNED ON!", Toast.LENGTH_SHORT).show();
                searchBTDevices();
            }
            else
                Toast.makeText(MainActivity.this,"FAILED TO ENABLE BLUETOOTH", Toast.LENGTH_LONG).show();
        }
    
    
    
    
        public void searchBTDevices()
        {
            Thread searchThread = new Thread() {
                @Override
                public void run() {
                    Intent searchBT = new Intent(getApplicationContext(), SearchBTDevice.class);
                    startActivity(searchBT);
                }
            };
            searchThread.start();
        }
    }
    

    这是我 SearchBTDevice.java 的样子

    package vertex2016.mvjce.edu.bluealert;
    
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothGattDescriptor;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.bluetooth.BluetoothAdapter;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.AttributeSet;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    
    import java.util.Set;
    
    public class SearchBTDevice extends AppCompatActivity {
    
        public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
        public ArrayAdapter PairedArrayAdapter, BTArrayAdapter;
        public IntentFilter filter = new IntentFilter();
        public ListView devicesFound;
        public Set<BluetoothDevice> pairedDevices;
    
    
        private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                    BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
                    PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
                }
            }
        };
    
    
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_search_btdevice);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            if(!BTArrayAdapter.isEmpty())
                BTArrayAdapter.clear();
    
            searchBTDevices();
    
        }
    
    
        public void searchBTDevices()
        {
            pairedDevices = BlueAdapter.getBondedDevices();
    
            if(pairedDevices.size()>0)
                for(BluetoothDevice device: pairedDevices)
                    PairedArrayAdapter.add(device.getName() + "\t\t" + device.getAddress() + "\n");
    
    
            filter.addAction(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    
            final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                        BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
                        PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
                    }
                }
            };
    
            BlueAdapter.startDiscovery();
    
            devicesFound = (ListView)findViewById(R.id.searchpagelistView);
            devicesFound.setAdapter(BTArrayAdapter);
    
        }
    
    
    }
    

    这是我的应用程序崩溃时 logcat 显示的内容

    03-17 11:51:40.120 19178-19178/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: vertex2016.mvjce.edu.bluealert, PID: 19178
                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{vertex2016.mvjce.edu.bluealert/vertex2016.mvjce.edu.bluealert.SearchBTDevice}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
                                                                                        at android.app.ActivityThread.access$900(ActivityThread.java:154)
                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                                        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:904)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                                     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
                                                                                        at vertex2016.mvjce.edu.bluealert.SearchBTDevice.onCreate(SearchBTDevice.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:2311)
                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) 
                                                                                        at android.app.ActivityThread.access$900(ActivityThread.java:154) 
                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                        at android.os.Looper.loop(Looper.java:135) 
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5292) 
                                                                                        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:904) 
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
    

    所以这些是我的问题:

    • 我哪里错了&amp;我该怎么办?
    • 我可以通过名为BluetoothAdapter的新活动检索MainActivity.java中创建的SearchBTDevice.java吗?
    • 无论如何我可以设置来自另一个活动的一个活动中定义的按钮的onClick操作吗?

    感谢您的时间!

1 个答案:

答案 0 :(得分:2)

在SearchBTDevice类中定义您的BTArrayAdapter对象。在onCreate()中调用BTArrayAdapter.isEmpty()时为null。