android - 当我尝试打开列表时应用程序崩溃
问题描述
我一直在对蓝牙应用程序进行编程,并且我已经完成了与配对设备的连接列表,没有编译器错误,但是当我尝试在手机上打开它时,应用程序崩溃如果有人可以帮助我,我将不胜感激,下面是列表代码、MainActivity代码和logcat错误:
public class MainActivity extends AppCompatActivity {
BluetoothAdapter BtAdapter = null;
private final int REQUEST_ENABLE_BT = 1;
private final int REQUEST_BT_CONECTION = 2;
boolean conexao = false;
public static String MAC = null;
BluetoothDevice myDevice = null;
BluetoothSocket mySocket = null;
Button Frente, Tras, Esquerda, DIreita, Conectar;
UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BtAdapter = BluetoothAdapter.getDefaultAdapter();
Frente = (Button)findViewById(R.id.Frente);
Tras = (Button)findViewById(R.id.Tras);
Esquerda = (Button)findViewById(R.id.Esquerda);
DIreita = (Button)findViewById(R.id.Direita);
Conectar = (Button)findViewById(R.id.Conectar);
if(BtAdapter == null){
Toast.makeText(getApplicationContext(), "Seu dispositivo nao possui bluetooth", Toast.LENGTH_LONG).show();
} else if(!BtAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Conectar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(conexao){
} else {
Intent openList = new Intent(MainActivity.this, DevicesList.class);
startActivityForResult(openList, REQUEST_BT_CONECTION);
//code not finhished
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case REQUEST_ENABLE_BT:
if(resultCode == Activity.RESULT_OK){
Toast.makeText(getApplicationContext(), "O bluetooth foi ativado com sucesso", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "O bluetooth nao foi ativado com sucesso, o app sera encerado", Toast.LENGTH_LONG).show();
finish();
}
case REQUEST_BT_CONECTION:
if (resultCode == Activity.RESULT_OK){
MAC = data.getDataString();
myDevice = BtAdapter.getRemoteDevice(MAC);
try {
mySocket = myDevice.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException erro) {
}
} else {
Toast.makeText(getApplicationContext(), "Falha ao obter o endereco MAc do dispositivo", Toast.LENGTH_LONG);
}
}
}
}
这是 deviceListActivity:
public class DevicesList extends ListActivity {
public BluetoothAdapter BtAdapter2 = null;
public static String ENDERECO_MAC = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> ArrayBluetooth = new ArrayAdapter<String>(DevicesList.this, android.R.layout.simple_list_item_1);
Set<BluetoothDevice> dispositivosPareados = BtAdapter2.getBondedDevices();
if(dispositivosPareados.size() > 0){
for(BluetoothDevice device : dispositivosPareados){
String nomeBt = device.getName();
String macBt = device.getAddress();
ArrayBluetooth.add(nomeBt + "/n" + macBt);
}
}
setListAdapter(ArrayBluetooth);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String infomacaoGeral = ((TextView) v).getText().toString();
String enderecoMac = infomacaoGeral.substring(infomacaoGeral.length() - 17);
Toast.makeText(getApplicationContext(), "Info:" + infomacaoGeral, Toast.LENGTH_LONG);
Intent retornaMac = new Intent();
retornaMac.putExtra(enderecoMac, ENDERECO_MAC);
setResult(RESULT_OK);
finish();
}
}
这是错误堆栈跟踪:
Process: com.example.lordz.bluetoothproject, PID: 25942 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lordz.bluetoothproject/com.example.lordz.bluetoothproject.DevicesList}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Set android.bluetooth.BluetoothAdapter.getBondedDevices()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2955)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
**Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Set android.bluetooth.BluetoothAdapter.getBondedDevices()' on a null object reference**
at com.example.lordz.bluetoothproject.DevicesList.onCreate(DevicesList.java:29)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
解决方案
您的错误在 onCreate 方法中,正是在这一行:
Set<BluetoothDevice> dispositivosPareados = BtAdapter2.getBondedDevices();
BtAdapter2 为空,因为您已在 Activity 类中声明为空。
public BluetoothAdapter BtAdapter2 = null;
我想你可能想先在 onCreate 中声明 BluetoothAdapter 然后使用它:
// inside onCreate
BtAdapter2 = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> dispositivosPareados = BtAdapter2.getBondedDevices();
您的应用程序还必须检查蓝牙权限,它可能会要求用户提供这些权限。有关更多参考,请访问有关 bt 权限的这个stackoverflow 问题,还可以访问官方文档中的蓝牙概述。
推荐阅读
- mysql - JPA、distinct、order by、null 值和 ONLY_FULL_GROUP_BY sql 模式
- python-3.x - 根据一系列条件创建动态位置
- python - 如何以感知均匀性对 HSV 空间进行采样
- python - 将数据附加到linux上的配置文件
- ansible - Ansible 在世界可写目录 (/vagrant) 中运行,忽略它作为 ansible.cfg 源
- php - 在 BigCommerce HTML href 中回显 PHP(自引用 hreflang 标签)
- java - 线程 java.lang.IllegalStateException 中的异常:密码未初始化
- keyboard - 仅当键本身被按住时,按下停止键或发送键事件
- java - QueueConfiguration 的 JavaDoc 在哪里?
- javascript - Angular:将服务/组件移动到另一个文件夹(在文件夹结构中,而不是在代码中)