null指针异常-findviewbyid()

zdwk9cvp  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(365)

**结案。**此问题不可复制或由打字错误引起。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

12天前关门了。
改进这个问题
我试图使一个蓝牙扫描仪应用程序,但我有问题。应用程序启动时自动关闭。它给了我一个错误:
原因:java.lang.nullpointerexception:尝试在com.example.bluetoothscanner.mainactivity.oncreate(mainactivity)上的空对象引用上调用虚拟方法“android.view.view android.widget.listview.findviewbyid(int)”。java:40)
第40行是我从布局中调用listview的地方,我不知道如何修复它。
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...");
            }
        }
    };

活动\u main.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>
h6my8fg2

h6my8fg21#

发生错误的原因是DeviceList对象中没有此类函数调用findviewbyid。为了将listview传递到deviceslist中,必须像这样传递它。

devicesList = findViewById(R.id.bluetoothList);
lc8prwob

lc8prwob2#

findviewbyid用作

devicesList = findViewById(R.id.bluetoothList);

不象

devicesList.findViewById(R.id.bluetoothList);

相关问题