简体   繁体   English

当我尝试打开列表时应用崩溃

[英]App crashing when I try to open a list list

I've been progamming a bluettoth app and i've done a list por conect to the paired device, there are no compiler errors, but when i try to open it on my phone the app crashes I would be grateful if someone could help me, here follows the list code, the MainActivity code and the logcat error: 我一直在编写Bluettoth应用程序的程序,并完成了与配对设备的连接列表,没有编译器错误,但是当我尝试在手机上打开它时,应用程序崩溃了,如果有人可以帮助我,我将不胜感激,下面是列表代码,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);

            }
    }

}
}

This is the deviceListActivity: 这是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();

    }
}

This is the error stacktrace: 这是错误堆栈跟踪:

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) 

Your error is in the onCreate method, precisely in this line: 您的错误在于onCreate方法中,恰好在此行中:

Set<BluetoothDevice> dispositivosPareados = BtAdapter2.getBondedDevices();

BtAdapter2 is null because you've declared in Activy class as null. BtAdapter2为null,因为您已在Activy类中将其声明为null。

public BluetoothAdapter BtAdapter2 = null;

I think you may want to first declare the BluetoothAdapter in onCreate and then use it: 我认为您可能想先在onCreate中声明BluetoothAdapter,然后使用它:

// inside onCreate
BtAdapter2 = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> dispositivosPareados = BtAdapter2.getBondedDevices();

Your app has to check also bluetooth permissions and it may ask user for them. 您的应用还必须检查蓝牙权限,并且可能会要求用户提供蓝牙权限。 For more references visit this stackoverflow question about bt permissions and also visit the bluetooth overview in official documentation . 有关更多参考,请访问有关bt权限的stackoverflow问题 ,并访问官方文档中蓝牙概述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试使用Sql表填充列表视图时,应用崩溃 - App crashing when I try to populate a list view with a Sql table 当我尝试打开Goog​​le Maps活动时Android应用程序崩溃 - Android app crashing when I try to open google maps activity 单击列表中的歌曲时,应用程序崩溃 - App is crashing when I click on a Song in List 当我尝试打开使用SQLite的活动时,Contact Manager App崩溃 - Contact Manager App crashing when I try to open an activity that uses SQLite 尝试创建开放式GL ES环境时,我的应用程序不断崩溃 - My App Keeps Crashing When I Try to Create an Open GL ES Enviroment 当我尝试通过 android 应用程序中的通知打开设置时,设置不断崩溃 - Settings keep crashing when I try to open them through my notifications in my android app 当我尝试添加用户定义的对象时,list.add崩溃 - list.add is crashing when I try to add user defined object 当我打开它时,我的应用程序一直崩溃 - My app keeps crashing when i open it 单击列表首选项时应用崩溃 - App Crashing when clicking on list preference 应用程序在滚动列表时崩溃 - App is crashing on scrolling of list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM