-1

我目前正在编程一个应用程序,它是一个Arduino机器人手臂的蓝牙控制器。'BluetoothAdapter空对象引用'(与logcat) - Android

当我按下'开始'按钮(b7)时,它应该启用蓝牙。 但该应用程序停止并在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

你可以发布你使用过的代码吗? – Bek

回答

0

您应该初始化您的BluetoothAdapter bA;,例如,

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ba = BluetoothAdapter.getDefaultAdapter(); 
+0

谢谢潜水员!我初始化它'最终BluetoothAdapter bA = BluetoothAdapter.getDefaultAdapter();'谢谢Tunaki,我会深入研究这些副本 –