Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
2021-06-26 05:10:29.573 24952-24952/c.bawp.securemessenger D/AndroidRuntime: Shutting down VM
2021-06-26 05:10:29.587 24952-24952/c.bawp.securemessenger E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.bawp.securemessenger, PID: 24952
android.content.ActivityNotFoundException: Unable to find explicit activity class {c.bawp.securemessenger/c.bawp.securemessenger.ChatController}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:574)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:560)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at c.bawp.securemessenger.ChooseActivity$1.onClick(ChooseActivity.java:26)
at android.view.View.performClick(View.java:6597)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2021-06-26 05:10:29.657 24952-24952/c.bawp.securemessenger I/Process: Sending signal. PID: 24952 SIG: 9
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = 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) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}
Related
My app keeps crashing when I try to log in (after LoginActivity file). Here's the code. I"d really appreciate some help with this.
MainActivity (opens the register/login screen)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText username, password, repassword;
Button signup, signin;
DBHelper DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
repassword = (EditText) findViewById(R.id.repassword);
signup = (Button) findViewById(R.id.btnsignup);
signin = (Button) findViewById(R.id.btnsignin);
DB = new DBHelper(this);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
String repass = repassword.getText().toString();
if(user.equals("")||pass.equals("")||repass.equals(""))
Toast.makeText(MainActivity.this, "Please enter all the fields", Toast.LENGTH_SHORT).show();
else{
if(pass.equals(repass)){
Boolean checkuser = DB.checkusername(user);
if(checkuser==false){
Boolean insert = DB.insertData(user, pass);
if(insert==true){
Toast.makeText(MainActivity.this, "Registered successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(MainActivity.this, "User already exists! please sign in", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Passwords not matching", Toast.LENGTH_SHORT).show();
}
} }
});
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
}
}
LoginActivity (once registered then proceed to login)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText username, password;
Button btnlogin;
DBHelper DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username1);
password = (EditText) findViewById(R.id.password1);
btnlogin = (Button) findViewById(R.id.btnsignin1);
DB = new DBHelper(this);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
if(user.equals("")||pass.equals(""))
Toast.makeText(LoginActivity.this, "Please enter all the fields", Toast.LENGTH_SHORT).show();
else{
Boolean checkuserpass = DB.checkusernamepassword(user, pass);
if(checkuserpass==true){
Log.d("mytag","1");
Toast.makeText(LoginActivity.this, "Sign in successfull", Toast.LENGTH_SHORT).show();
Log.d("mytag","2");
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
Log.d("mytag","3");
startActivity(intent);
}else{
Toast.makeText(LoginActivity.this, "Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
HomeActivity (this should open the main screen of the app. The app has a add button which adds items using recyclerview)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class HomeActivity extends Activity {
RecyclerView recyclerView;
FloatingActionButton add_button;
ImageView empty_imageview;
TextView no_data;
MyDatabaseHelper myDB;
ArrayList<String> book_id, book_title, book_author, book_pages;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
empty_imageview = findViewById(R.id.empty_imageview);
no_data = findViewById(R.id.no_data);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this, AddActivity.class);
startActivity(intent);
}
});
myDB = new MyDatabaseHelper(HomeActivity.this);
book_id = new ArrayList<>();
book_title = new ArrayList<>();
book_author = new ArrayList<>();
book_pages = new ArrayList<>();
storeDataInArrays();
customAdapter = new CustomAdapter(HomeActivity.this,this, book_id, book_title, book_author,
book_pages);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
recreate();
}
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
empty_imageview.setVisibility(View.VISIBLE);
no_data.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
book_id.add(cursor.getString(0));
book_title.add(cursor.getString(1));
book_author.add(cursor.getString(2));
book_pages.add(cursor.getString(3));
}
empty_imageview.setVisibility(View.GONE);
no_data.setVisibility(View.GONE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.delete_all){
confirmDialog();
}
return super.onOptionsItemSelected(item);
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete All?");
builder.setMessage("Are you sure you want to delete all Data?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabaseHelper myDB = new MyDatabaseHelper(HomeActivity.this);
myDB.deleteAllData();
//Refresh Activity
Intent intent = new Intent(HomeActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jovanovic.stefan.sqlitetutorial">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".UpdateActivity"
android:parentActivityName=".HomeActivity"/>
<activity android:name=".HomeActivity"
android:label="GDSC Items App"/>
<activity android:name=".LoginActivity"
android:label="GDSC Items App"/>
<activity
android:name=".AddActivity"
android:label="Add Item"
android:parentActivityName=".HomeActivity" />
<activity
android:name=".MainActivity"
android:label="GDSC Items App">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Error log
2022-01-27 20:31:01.505 3354-3354/com.jovanovic.stefan.sqlitetutorial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jovanovic.stefan.sqlitetutorial, PID: 3354
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jovanovic.stefan.sqlitetutorial/com.jovanovic.stefan.sqlitetutorial.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.jovanovic.stefan.sqlitetutorial.HomeActivity.onCreate(HomeActivity.java:45)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
Make sure you setting the correct layout inside the setContentView() method
For example:
setContentView(R.layout.activity_home);
Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = 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) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}
I have a small problem where when I click a certain button within my app, the app completely crashes each time without fail.
I am using android studio 2.3.3 and the app is a barcode scanner, here is the error message I get:
android.content.ActivityNotFoundException: No Activity found to handle
Intent { act=android.intent.action.VIEW dat=5010029217902 }
Here is the section of code that is causing the error:
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
startActivity(browserIntent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
The result when you scan a barcode is often not a valid URL. It is often just a string with several digits. It has no schema or protocol, so it is (very possibly) not defined "what type of resource locator it is". Android's ACTION_VIEW intent is mostly use this information to decide "start which app/activity to open this URL". With a lack of the important information, Android has no idea to open it.
You may specify some cases for handling the result. For example, if the result begins with "http://" or "https://", directly use your code to handle, but if it is just a string of numbers, display it directly, or append it after some string before it is used for Uri.parse, for example "https://google.com/search?q=", to search this barcode's value as you may wanted, or other things you want to do with that 13 digit result.
For example, (the code below written in mobile hasn't been tested, just show the idea):
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent;
if (myResult.startsWith("http://") || myResult.startsWith("https://"))
browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
else
browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com/search?q=" + myResult));
startActivity(browserIntent);
}
package com.example.priyanka.qrbarcodescanner;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.content.ClipboardManager;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
private ZXingScannerView scannerView;
private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
int currentApiVersion = Build.VERSION.SDK_INT;
if(currentApiVersion >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
}
else
{
requestPermission();
}
}
}
private boolean checkPermission()
{
return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission()
{
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
#Override
public void onResume() {
super.onResume();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if(scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted){
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void handleResult(Result result) {
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
final static String myResult = result.getText();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
startActivity(browserIntent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
}
package com.example.priyanka.qrbarcodescanner;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.content.ClipboardManager;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static String myResult;
private static final int REQUEST_CAMERA = 1;
private ZXingScannerView scannerView;
private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
int currentApiVersion = Build.VERSION.SDK_INT;
if(currentApiVersion >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
}
else
{
requestPermission();
}
}
}
private boolean checkPermission()
{
return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission()
{
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
#Override
public void onResume() {
super.onResume();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if(scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted){
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void handleResult(Result result) {
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
myResult = result.getText();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
startActivity(browserIntent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
}
I'm developing a project with a BLE device(RN-4871 - Bluetooth 4.2 Low-Energy module) connected to the target board.
RN-4871 device is visible and connected to BLE scanner App downloaded from Play Store.
I'm using the snippet downloaded from https://developer.android.com/samples/BluetoothLeGatt/project.html.
I just configured the project to Android Marshmallow(API>21) and used the above downloaded code.
I am using moto c plus(Nougat).
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
But it shows startLeScan and stopLeScan are depreciated. So I am unable to scan the available devices.
Also I just used the below snippet used to connect exact device with UUID.
public static final ParcelUuid MY_UUID =
ParcelUuid.fromString("00002A05-0000-1000-8000-00805F9B34FB");
private void scanLeDevice(final boolean enable) {
if(enable){
ScanFilter aFilter = new ScanFilter.Builder()
.setServiceUuid(BluetoothLeService.MY_UUID).build();
ArrayList<ScanFilter> filters = new ArrayList<>();
filters.add(aFilter);
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
mBluetoothLeScanner.startScan(filters, settings, (ScanCallback) mLeScanCallback);
}
}
this closes the app.
DeviceScanActivity.java
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DeviceScanActivity extends ListActivity {
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);
mHandler = new Handler();
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!mScanning) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
mLeDeviceListAdapter.clear();
scanLeDevice(true);
break;
case R.id.menu_stop:
scanLeDevice(false);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
final Intent intent = new Intent(this, DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
if (mScanning) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = false;
}
startActivity(intent);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
}
How to connect RN-4871 ??
The code examples makes your question confusing.
In the last shown code example you already have a field mBluetoothLeScanner,
but you do not use it.
Just do:
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
mBluetoothLeScanner = mBluetoothAdapter.BluetoothLeScanner;
And int the rest of your code replace
mBluetoothAdapter.stopLeScan(mLeScanCallback)
and
mBluetoothAdapter.startLeScan(mLeScanCallback)
with
mBluetoothLeScanner.stopScan( mLeScanCallback)
and
mBluetoothLeScanner.startScan( mLeScanCallback)
In my code, after I run startDiscovery().
Nothing seems to happen and I don't know why.
As #Mitch suggest, I changed back to using button to do startDiscovery.
But now it seems worse as it crashes right after I press the button.
public class BTActivity extends AppCompatActivity{
private static final String TAG = "BTActivity";
BluetoothAdapter BTAdapter;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
private EcgView mEcgView;
//Create a BroadcastReceiver for
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BTAdapter.ACTION_STATE_CHANGED)){
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BTAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG,"onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG,"onReceive: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG,"onReceive: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG,"onReceive: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)){
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode){
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Enabled");
break;
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Able to receive connection");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Not able to receive connection");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG,"mBroadcastReceiver2: Connecting");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG,"mBroadcastReceiver2: Connected");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "OnReceive: ACTION FOUND");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "OnReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3cases:
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BOUNDED");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING){
Log.d(TAG, "BroadcastReceiver: BOND_BOUNDING");
}
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE){
Log.d(TAG, "BroadcastReceiver: BOND_NONE");
}
}
}
};
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
}
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.enabledisable:
//if BT is enable, turn it off; if not then prompt user to enable BT;
if (!BTAdapter.getDefaultAdapter().isEnabled()) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(i);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(BTAdapter.getDefaultAdapter().isEnabled()) {
BTAdapter.getDefaultAdapter().disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
return true;
case R.id.enablediscoverable:
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(BTAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2, intentFilter);
return true;
case R.id.discover:
Intent intent = new Intent(getApplicationContext(),SearchActivity.class);
startActivity(intent);
/*
Log.d(TAG,"Looking for unpaired devices");
if (BTAdapter.isDiscovering()){
BTAdapter.cancelDiscovery();
Log.d(TAG,"Canceling Discovery");
//checkBTPermissions();
BTAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if (!BTAdapter.isDiscovering()){
//checkBTPermissions();
Log.d(TAG,"Searching Now");
BTAdapter.startDiscovery();
Log.d(TAG,"Still Searching Now");
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
Log.d(TAG,"123");
}
*/
return true;
default:
return false;
}
}
/*
private void checkBTPermissions() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
}
else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK Version < LOLLIPOP");
}
}
}
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4,filter);
//lvNewDevices.setOnItemClickListener(BTActivity.this);
//Check if the phone support BT
BTAdapter = BluetoothAdapter.getDefaultAdapter();
if (BTAdapter == null) {
//System.exit(0);
}
//mConnectThread = new ConnectThread(mDevice);
//mConnectThread.start();
mEcgView = (EcgView) findViewById(R.id.ecgView);
}
public void toMainActivity(View view){
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
So after the click on the Search Devices from the action bar, the app will go to another activity. But when I click on Start Searching in that activity, the app crashes. Don't know why as logic should be the same.
public class SearchActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String TAG = "SearchActivity";
BluetoothAdapter BTAdapter;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
lvNewDevices.setOnItemClickListener(SearchActivity.this);
}
private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "OnReceive: ACTION FOUND");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "OnReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
public void btnDiscover(View view){
Log.d(TAG,"Looking for unpaired devices");
if (BTAdapter.isDiscovering()){
BTAdapter.cancelDiscovery();
Log.d(TAG,"Canceling Discovery");
//checkBTPermissions();
BTAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if (!BTAdapter.isDiscovering()){
//checkBTPermissions();
Log.d(TAG,"Searching Now");
BTAdapter.startDiscovery();
Log.d(TAG,"Still Searching Now");
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
Log.d(TAG,"123");
}
}
public void backToBT(View view){
Intent intent = new Intent(getApplicationContext(),BTActivity.class);
startActivity(intent);
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Cancel Discovery as it's costly
BTAdapter.cancelDiscovery();
Log.d(TAG,"onItemClick:Clicked a Device");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG,"onItemClick: Device Name: " + deviceName);
Log.d(TAG,"onItemClick: Device Address " + deviceAddress);
//Bonding
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
And the manifest is attached
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ted.pawan462">
<user-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BTActivity" />
<activity android:name=".SearchActivity"></activity>
</application>
</manifest>
This is the Logcat
1-07 21:40:39.633 32744-367/com.example.ted.pawan462 I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8974_LA.BF.1.1.3_RB1__release_AU (Ia6c73e7530)
OpenGL ES Shader Compiler Version: E031.29.00.00
Build Date: 12/04/15 Fri
Local Branch: mybranch17080070
Remote Branch: quic/LA.BF.1.1.3_rb1.5
Local Patches: NONE
Reconstruct Branch: NOTHING
01-07 21:40:39.635 32744-367/com.example.ted.pawan462 I/OpenGLRenderer: Initialized EGL, version 1.4
01-07 21:40:41.786 32744-32744/com.example.ted.pawan462 I/ListPopupWindow: Could not find method setEpicenterBounds(Rect) on PopupWindow. Oh well.
01-07 21:40:41.812 32744-32744/com.example.ted.pawan462 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
01-07 21:43:54.309 32744-367/com.example.ted.pawan462 D/OpenGLRenderer: endAllStagingAnimators on 0x9db76280 (MenuPopupWindow$MenuDropDownListView) with handle 0x9d2784b0
01-07 21:43:55.320 32744-32744/com.example.ted.pawan462 D/SearchActivity: Looking for unpaired devices
01-07 21:43:55.327 32744-32744/com.example.ted.pawan462 D/AndroidRuntime: Shutting down VM
01-07 21:43:55.329 32744-32744/com.example.ted.pawan462 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ted.pawan462, PID: 32744
Theme: themes:{default=overlay:com.wsdeveloper.galaxys7, iconPack:com.wsdeveloper.galaxys7, fontPkg:com.wsdeveloper.galaxys7, com.android.systemui=overlay:com.wsdeveloper.galaxys7, com.android.systemui.navbar=overlay:com.wsdeveloper.galaxys7}
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isDiscovering()' on a null object reference
at com.example.ted.pawan462.SearchActivity.btnDiscover(SearchActivity.java:58)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I think I might have made it worse.
The only thing that stands out to me is you have checkBTPermissions() commented out. But I'm assuming you've tried uncommenting that.
Also make sure that your other devices are set to "discoverable" or the phone won't be able to see them.
Other than that I think it looks pretty good. Maybe something weird going on because your using a menu? Not sure :(.