-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,我會深入研究這些副本 –