java - 空指针异常 - 调用 ListView 时的 FindViewById()
问题描述
我正在尝试制作蓝牙扫描仪应用程序,但我遇到了问题。该应用程序在启动时自动关闭。它给了我错误:
引起:java.lang.NullPointerException:尝试在 com.example.bluetoothscanner.MainActivity.onCreate(MainActivity.java) 的空对象引用上调用虚拟方法 'android.view.View android.widget.ListView.findViewById(int)' :40)
第 40 行是我从布局中调用列表视图的地方,但我不知道如何修复它。
MainActivity.java:
package com.example.bluetoothscanner;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
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.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// Declaración de clases
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
private ListView devicesList;
private Button scanningBtn;
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> listAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get bluetooth adapter
*devicesList.findViewById(R.id.bluetoothList);*
scanningBtn.findViewById(R.id.button);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Se crea un ArrayAdapter para mostrar los resultados en una lista
listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
devicesList.setAdapter(listAdapter);
//Miramos el estado del bluetooth
checkBluetoothState();
scanningBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(bluetoothAdapter != null && bluetoothAdapter.isEnabled())
{
if(checkCoarseLocationPermission())
{
listAdapter.clear();
bluetoothAdapter.startDiscovery();
}
}else
{
checkBluetoothState();
}
}
});
// Se comprueba permisos al empezar la app
checkCoarseLocationPermission();
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver,new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver,new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver,new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
// Funciones para comprobar los permisos
private boolean checkCoarseLocationPermission(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else{
return true;
}
}
private void checkBluetoothState(){
if (bluetoothAdapter == null){
Toast.makeText(this, "Bluetooth is not available in this device",Toast.LENGTH_SHORT).show();
}else{
if (bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.isDiscovering()){
Toast.makeText(this,"Scanning for bluewtooth devices",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Bluetooth is enabled",Toast.LENGTH_SHORT).show();
scanningBtn.setEnabled(true);
}
}
else{
Toast.makeText(this,"You need to enable bluetooth",Toast.LENGTH_SHORT).show();
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BLUETOOTH);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_ENABLE_BLUETOOTH){
checkBluetoothState();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode) {
case REQUEST_ACCESS_COARSE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Access coarse location enabled, you can scan Bluetooth devices", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Access coare location forbidden, you can not scan Bluetooth devices", Toast.LENGTH_SHORT).show();
}
break;
}
}
// Se implementa el recividor para poder detectar otros dispositivos
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
@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);
listAdapter.add(device.getName() + "\n" +device.getAddress());
} else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
scanningBtn.setText("Scanning Bluetooth Devices");
} else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
scanningBtn.setText("Scanning in progress...");
}
}
};
活动主.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="@string/BtnText"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.837" />
<ListView
android:id="@+id/bluetoothList"
android:layout_width="272dp"
android:layout_height="453dp"
android:layout_marginTop="52dp"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
解决方案
发生错误的原因是deviceList对象中没有findViewById这样的函数调用。为了将 listView 传递给 devicesList,您必须像这样传递它。
devicesList = findViewById(R.id.bluetoothList);
推荐阅读
- cordova - 离子框架:ITMS-90809:UIWebView API 弃用(遵循所有说明,但我收到弃用消息)
- c - 使用 AWS S3 预签名 URL 下载的 Word 文件以“受保护的视图”模式打开
- java - 使用 Spring-Boot 进行分布式事务回滚
- electron - 具有电子支持的 Cordova 插件
- r - 将带有特殊字符的管道分隔 csv 读入 R 时出现问题
- angular - HostListener 'scroll' 事件未触发,但 'mouseenter' 事件正常
- c - 获取 c 核心转储错误并尝试获取随机整数
- entity-framework - 我正在尝试使用 Oracle 数据库在 Entity Framework .NET 中使用数据库优先方法
- python - 如何从 JSON 对象中提取元素
- osgi - 如何在 Apache Felix Web 控制台中启用组件页面