我正在编写一个应用程序,它是Arduino机器人手臂的蓝牙控制器。
当我按下“开始”按钮(b7)时,它应启用蓝牙功能。 但是app停止了,在logcat中,我得到了:
“尝试在空对象引用上调用虚方法'java.util.Set android.bluetooth.BluetoothAdapter.getBondedDevices()'。
这是代码:
package trombertlabs.essai1;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import java.util.Set;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends ActionBarActivity {
ImageButton b, b0, b1, b2, b3, b4;
Button b5, b6, b7;
BluetoothAdapter bA;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (ImageButton)findViewById(R.id.upbb);
b0 = (ImageButton)findViewById(R.id.upba);
b1 = (ImageButton) findViewById(R.id.downba);
b2 = (ImageButton)findViewById(R.id.downbb);
b3 = (ImageButton)findViewById(R.id.leftb);
b4 = (ImageButton)findViewById(R.id.rightb);
b5 = (Button)findViewById(R.id.closeb);
b6 = (Button)findViewById(R.id.openb);
b7 = (Button)findViewById(R.id.startb);
b7.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
BtInterface();
}
});
}
public void BtInterface () {
if (!bA.isEnabled()) {
bA.enable();
}
else {
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
实际上,有“导入”和按钮未使用,但这是针对项目的其余部分。
答案 0 :(得分:0)
您应初始化BluetoothAdapter bA;
,例如
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ba = BluetoothAdapter.getDefaultAdapter();