我一直在编写一个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);
}
}
}
}
这是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)
答案 0 :(得分:1)
您的错误在onCreate方法中,恰好在此行中:
Set<BluetoothDevice> dispositivosPareados = BtAdapter2.getBondedDevices();
BtAdapter2为空,因为您已在Activy类中将其声明为空。
public BluetoothAdapter BtAdapter2 = null;
我认为您可能想先在onCreate中声明BluetoothAdapter,然后使用它:
// inside onCreate
BtAdapter2 = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> dispositivosPareados = BtAdapter2.getBondedDevices();
您的应用程序还必须检查蓝牙权限,并且可能会要求用户提供蓝牙权限。有关更多参考,请访问此stackoverflow question关于bt权限,也请访问bluetooth overview in official documentation。