Auro
Auro

Reputation: 1628

App crashes during Bluetooth discovery

What I'm trying to do

I'm trying to create an app that searches all the Bluetooth devices nearby and connects to the ones user wishes to connect to.

I'm trying to create a Connect button in one activity that starts the discovery function in another activity

How I'm trying to do it

So I have this MainActivity.java class / activity that has the Connect button. Upon clicking this button, it should do three things:

  1. Check if the Bluetooth on my Smartphone is on & if it's not, turn it on.
  2. Display a TOAST message to show whether BT has been successfully turned on or not
  3. Start this new activity, called SearchBTDevice.java that looks for nearby BT devices & list them in a ListView

The first two are perfectly working since they're on MainActivity.java & that's where my button has been created.

Problem comes when it creates the new activity & tries to do the 3rd one. The app crashes.

This is what my MainActivity.java looks like

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

This is what my SearchBTDevice.java looks like

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

    }


}

This is what the logcat shows when my app crashes

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) 

So these are my questions:

Thank you for your time!

Upvotes: 2

Views: 390

Answers (1)

Febi M Felix
Febi M Felix

Reputation: 2839

Define your BTArrayAdapter object in SearchBTDevice class. It is null while you call BTArrayAdapter.isEmpty() in onCreate().

Upvotes: 2

Related Questions