I am trying to Send a Bluetooth Device Discovered in an activity to another class to Perform Further Functionality......while trying to do so with the Help of a Constructor I am getting nullPointerException for the Bluetooth Device.
below is the code for ScanActivity wherein, the BroadcastReceiver is used to Discover the nearby Bluetooth devices, after receiving the device, the name and address are initialized to the device model class and then sent to the recyclerViewAdapter(Bluetooth_adapter) to set it in the View Holder.
public class ScanActivity extends AppCompatActivity {
private static final String TAG = "ScanActivity";
private static final int REQUEST_BT_ENABLE = 1;
private static final int disrequestCode = 5;
RecyclerView recyclerViewSD;
BluetoothAdapter bluetoothAdapter;
ArrayList<BluetoothDeviceModel> data;
SnackBarShowing snackBarShowing;
Bluetooth_adapter Adapter;
LinearProgressIndicator linearProgressIndicator;
View rootView;
BluetoothClass bluetoothClass;
private CircularProgressIndicator indicator;
AsignLogo asignLogo;
private ImageView reloadButton;
private Handler handler = new Handler();
private IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@RequiresApi(api = Build.VERSION_CODES.S)
@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);
if (ActivityCompat.checkSelfPermission(ScanActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 1);
}
String deviceName = device.getName();
String deviceAddress = device.getAddress();
linearProgressIndicator.setVisibility(View.GONE);
//-------for logo---------
bluetoothClass = device.getBluetoothClass();
asignLogo = new AsignLogo(bluetoothClass);
int logoResourse = asignLogo.getDeviceLogoResource(bluetoothClass);
//------------------------
data.add(new BluetoothDeviceModel(deviceName, deviceAddress, logoResourse));
Adapter = new Bluetooth_adapter(data, getApplicationContext());
recyclerViewSD.setAdapter(Adapter);
handler.postDelayed(new Runnable() {
@Override
public void run() {
indicator.setVisibility(View.GONE);
reloadButton.setVisibility(View.VISIBLE);
}
}, 4000);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: Starts");
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scan);
recyclerViewSD = (RecyclerView) findViewById(R.id.Scan_devices_RV);
recyclerViewSD.setLayoutManager(new LinearLayoutManager(this));
snackBarShowing = new SnackBarShowing();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
data = new ArrayList<BluetoothDeviceModel>();
linearProgressIndicator = (LinearProgressIndicator) findViewById(R.id.progress_indicator);
rootView = this.getWindow().getDecorView().findViewById(android.R.id.content);
indicator = (CircularProgressIndicator) findViewById(R.id.CPI);
reloadButton = (ImageView) findViewById(R.id.reload_btn);
reloadButton.setVisibility(View.GONE);
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device", Toast.LENGTH_SHORT).show();
finish();
}
// Request necessary permissions if not granted already
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
startDiscovery();
reloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
reload();
}
});
}
private void reload(){
cancelDiscovery();
unregisterReceiver(receiver);
data.clear();
startDiscovery();
registerReceiver(receiver, filter);
reloadButton.setVisibility(View.GONE);
new Handler().postAtTime(new Runnable() {
@Override
public void run() {
indicator.setVisibility(View.VISIBLE);
}
}, 3000);
}
private void establishConnection(){
}
private void startDiscovery() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.BLUETOOTH_SCAN}, 1);
} else {
bluetoothAdapter.startDiscovery();
Toast.makeText(this, "Scanning for devices...", Toast.LENGTH_SHORT).show();
Log.d(TAG, "startDiscovery: Discovery: " + bluetoothAdapter.startDiscovery());
}
}
private void cancelDiscovery() {
if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
Log.d(TAG, "cancelDiscovery: Discovery Cancelled");
}
}
@RequiresApi(api = Build.VERSION_CODES.S)
void enableDiscover() {
Intent discoverableIntent =
new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 180);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADVERTISE} , disrequestCode);
}
startActivityForResult(discoverableIntent, disrequestCode);
}
public void checkBluetooth() {
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
startActivityForResult(intent, REQUEST_BT_ENABLE);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: Request Code: " + requestCode);
if (requestCode == REQUEST_BT_ENABLE && requestCode == disrequestCode) {
Log.d(TAG, "onActivityResult: REQcode: " + requestCode);
if (resultCode == RESULT_OK) {
Log.d(TAG, "onActivityResult: ResultCode: " + resultCode);
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
} else {
Log.d(TAG, "onActivityResult: Result Code : " + resultCode);
Log.d(TAG, "onActivityResult: ResultOK: " + RESULT_OK);
snackBarShowing.showSnackbar(rootView, "Bluetooth needs to be Enabled", Snackbar.LENGTH_SHORT, "enable", new View.OnClickListener() {
@Override
public void onClick(View v) {
checkBluetooth();
}
});
}
}
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
cancelDiscovery();
}
@Override
protected void onStart() {
super.onStart();
checkBluetooth();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
int discoverableMode = bluetoothAdapter.getScanMode();
Log.d(TAG, "onStart: DiscoverableMode: " + discoverableMode);
Log.d(TAG, "onStart: Scan mode Connectable_Discoverable: " + BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
Log.d(TAG, "onStart: Scan mode Connectable: " + BluetoothAdapter.SCAN_MODE_CONNECTABLE );
if (discoverableMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE || discoverableMode ==BluetoothAdapter.SCAN_MODE_CONNECTABLE){
return;
}else{
enableDiscover();
}
}
}
}
How to pass the Bluetooth Device discovered in ScanActivity to the adapter class below.
public class Bluetooth_adapter extends RecyclerView.Adapter<BluetoothViewHolder> {
BluetoothDevice selectedDevice;
ArrayList<BluetoothDeviceModel> data;
Context context;
AsignLogo asignLogo;
AdapterType adapterType;
private clickListener clickListener;
private List<BluetoothDevice> devices;
public Bluetooth_adapter(AdapterType adapterType) {
this.adapterType = adapterType;
}
public Bluetooth_adapter(List<BluetoothDevice> devices, clickListener clickListener) {
this.devices = devices;
this.clickListener = clickListener;
}
public Bluetooth_adapter(ArrayList<BluetoothDeviceModel> data, Context context) {
this.data = data;
this.context = context;
}
@NonNull
@Override
public BluetoothViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// This will create a blank box of Defined XMl File
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view1 = inflater.inflate(R.layout.pair_devices, parent, false);
View view2 = inflater.inflate(R.layout.devices, parent, false);
// In the fields we are passing the views from the View Holder.
return new BluetoothViewHolder(view1);
}
@Override
public void onBindViewHolder(@NonNull BluetoothViewHolder holder, int position) {
BluetoothDeviceModel deviceModel = data.get(position);
//BluetoothDevice device = devices.get(position);
Log.d(TAG, "onBindViewHolder: Adapter List: " + devices);
String name = data.get(position).getName();
String address = data.get(position).getAddress();
int imgresource = data.get(position).getImageresouce();
holder.dropdownImgPD.setImageResource(imgresource);
if (name == null) {
holder.deviceNamePD.setText(address);
} else {
holder.deviceNamePD.setText(name);
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//clickListener.on_Click_Listener(device);
}
};
holder.cardViewPD.setOnClickListener(listener);
}
@Override
public int getItemCount() {
return data.size();
}
}