2016-07-06 5 views
0

私はadruinoボードに接続し、いくつかのボタンを押すといくつかの番号を送信するアンドロイドスタジオを使用してアプリケーションを作成しようとしています。残念ながら、あなたのアプリは終了しました(ヌルリファレンス、Bluetoothによって発生)

今は、使用するたびにBluetoothAdapter変数がNULLを返すというエラーを解決できません。私は自分の携帯電話でアプリケーションを試してみましたが、それは実行されませんでした(残念ながら、あなたのアプリは閉じています)。

MainActivity.java:

public class MainActivity extends AppCompatActivity { 
    //variables-not using all of them but some are required in many examples for finding the MAC address 
    Handler bluetoothIn; 
    final int handlerState = 0; 
    private BluetoothAdapter BA; 
    private BluetoothSocket btSocket = null; 
    private ConnectedThread mConnectedThread; 
    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 
    //list for addresses 
    private static final String TAG = "DeviceListActivity"; 
    public static String EXTRA_DEVICE_ADDRESS = "device_address"; 
    private ArrayAdapter<String> mNewDevicesArrayAdapter; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { //here I define my buttons 

     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 

     setResult(Activity.RESULT_CANCELED); 

     final Button Up = (Button) findViewById(R.id.up); 
     Up.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       mConnectedThread.write("1"); 
      } 
     }); 
     final Button Down = (Button) findViewById(R.id.down); 
     Down.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       mConnectedThread.write("2"); 
      } 
     }); 
     final Button Right = (Button) findViewById(R.id.right); 
     Right.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       mConnectedThread.write("3"); 
      } 
     }); 
     final Button Left = (Button) findViewById(R.id.left); 
     Left.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       mConnectedThread.write("4"); 
      } 
     }); 
     final Button Connect = (Button) findViewById(R.id.connect); 
     Connect.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       checkBTState(); 
       doDiscovery(); 
       v.setVisibility(View.GONE); 
      } 
     }); 


     ArrayAdapter<String> pairedDevicesArrayAdapter = 
       new ArrayAdapter<String>(this, R.layout.activity_main); 
     mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_main); 

     ListView pairedListView = (ListView) findViewById(R.id.paired_devices); 
     pairedListView.setAdapter(pairedDevicesArrayAdapter); 
     pairedListView.setOnItemClickListener(mDeviceClickListener); 

     ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); 
     newDevicesListView.setAdapter(mNewDevicesArrayAdapter); 
     newDevicesListView.setOnItemClickListener(mDeviceClickListener); 

     // Register for broadcasts when a device is discovered 
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     this.registerReceiver(mReceiver, filter); 

     // Register for broadcasts when discovery has finished 
     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
     this.registerReceiver(mReceiver, filter); 

     // Get the local Bluetooth adapter 
     BA = BluetoothAdapter.getDefaultAdapter(); 
     checkBTState(); 
     if(BA.isEnabled()) { 
      // Get a set of currently paired devices 
      Set<BluetoothDevice> pairedDevices = BA.getBondedDevices(); 

      // If there are paired devices, add each one to the ArrayAdapter 
      if (pairedDevices.size() > 0) { 
       findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); 
       for (BluetoothDevice device : pairedDevices) { 
        pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
       } 
      } else { 
       String noDevices = getResources().getText(R.string.none_paired).toString(); 
       pairedDevicesArrayAdapter.add(noDevices); 
      } 
     } 

    } 

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { //something I have seen in one example I tried to copy 

     return device.createRfcommSocketToServiceRecord(BTMODULEUUID); 
     //creates secure outgoing connecetion with BT device using UUID 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 

     // Make sure we're not doing discovery anymore 
     if (BA != null) { 
      BA.cancelDiscovery(); 
     } 

     // Unregister broadcast listeners 
     this.unregisterReceiver(mReceiver); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 

     /***************************************************/ // code here 
     BluetoothDevice device = BA.getRemoteDevice(EXTRA_DEVICE_ADDRESS); 

     try { 
      btSocket = createBluetoothSocket(device); 
     } catch (IOException e) { 
      Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show(); 
     } 
     // Establish the Bluetooth socket connection. 
     try { 
      btSocket.connect(); 
     } catch (IOException e) { 
      try { 
       btSocket.close(); 
      } catch (IOException e2) { 
       //insert code to deal with this 
      } 
     } 
     mConnectedThread = new ConnectedThread(btSocket); 
     mConnectedThread.start(); 

     //I send a character when resuming.beginning transmission to check device is connected 
     //If it is not an exception will be thrown in the write method and finish() will be called 
    // mConnectedThread.write("x"); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 
     try { 
      //Don't leave Bluetooth sockets open when leaving activity 
      btSocket.close(); 
     } catch (IOException e2) { 
      //insert code to deal with this 
     } 
    } 

    private class ConnectedThread extends Thread { 
     private final InputStream mmInStream; 
     private final OutputStream mmOutStream; 

     //creation of the connect thread 
     public ConnectedThread(BluetoothSocket socket) { 
      InputStream tmpIn = null; 
      OutputStream tmpOut = null; 

      try { 
       //Create I/O streams for connection 
       tmpIn = socket.getInputStream(); 
       tmpOut = socket.getOutputStream(); 
      } catch (IOException e) { 
      } 

      mmInStream = tmpIn; 
      mmOutStream = tmpOut; 
     } 

     public void run() { 
      byte[] buffer = new byte[256]; 
      int bytes; 

      // Keep looping to listen for received messages 
      while (true) { 
       try { 
        bytes = mmInStream.read(buffer);   //read bytes from input buffer 
        String readMessage = new String(buffer, 0, bytes); 
        // Send the obtained bytes to the UI Activity via handler 
        bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget(); 
       } catch (IOException e) { 
        break; 
       } 
      } 
     } 

     //write method 
     public void write(String input) { 
      byte[] msgBuffer = input.getBytes();   //converts entered String into bytes 
      try { 
       mmOutStream.write(msgBuffer);    //write bytes over BT connection via outstream 
      } catch (IOException e) { 
       //if you cannot write, close the application 
       Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show(); 
       finish(); 
      } 
     } 
    } 

    private void doDiscovery() { 
     Log.d(TAG, "doDiscovery()"); 

     // Indicate scanning in the title 
     setProgressBarIndeterminateVisibility(true); 

     // If we're already discovering, stop it 
     if (BA.isDiscovering()) { 
      BA.cancelDiscovery(); 
     } 

     // Request discover from BluetoothAdapter 
     BA.startDiscovery(); 
    } 

    /** 
    * The on-click listener for all devices in the ListViews 
    */ 
    private AdapterView.OnItemClickListener mDeviceClickListener 
      = new AdapterView.OnItemClickListener() { 
     public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { 
      // Cancel discovery because it's costly and we're about to connect 
      BA.cancelDiscovery(); 

      // Get the device MAC address, which is the last 17 chars in the View 
      String info = ((TextView) v).getText().toString(); 
      String address = info.substring(info.length() - 17); 

      // Create the result Intent and include the MAC address 
      Intent intent = new Intent(); 
      intent.putExtra(EXTRA_DEVICE_ADDRESS, address); 

      // Set result and finish this Activity 
      setResult(Activity.RESULT_OK, intent); 
      finish(); 
     } 
    }; 

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 

      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       // If it's already paired, skip it, because it's been listed already 
       if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 
        mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
       } 
       // When discovery is finished, change the Activity title 
      } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
       setProgressBarIndeterminateVisibility(false); 
       setTitle(R.string.select_device); 
       if (mNewDevicesArrayAdapter.getCount() == 0) { 
        String noDevices = getResources().getText(R.string.none_found).toString(); 
        mNewDevicesArrayAdapter.add(noDevices); 
       } 
      } 
     } 
    }; 

    private void checkBTState() { 
     // Check device has Bluetooth and that it is turned on 
     BA=BluetoothAdapter.getDefaultAdapter(); 
     if(BA==null) { 
      Toast.makeText(getBaseContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show(); 
     } else { 
      if (BA.isEnabled()) { 
       Log.d(TAG, "...Bluetooth ON..."); 
      } else { 
       //Prompt user to turn on Bluetooth 
       Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
       startActivityForResult(enableBtIntent, 1); 
      } 
     } 
    } 

} 

Logcat:

com.example.mihaianca.helloword, PID: 13051 
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mihaianca.helloword/com.example.mihaianca.helloword.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference 
    at com.example.mihaianca.helloword.MainActivity.onCreate(MainActivity.java:113) 
    at android.app.Activity.performCreate(Activity.java:6237) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

    I/Process: Sending signal. PID: 13051 SIG: 9 

ありがとうございました!私はこのようにそれを使用してい

BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); 
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); 

とそれが正常に働いています:

+0

[こちら(お問い合わせください)](http://stackoverflow.com/help/how-to-ask)と[this(mcve)](http://stackoverflow.com/help/mcve)をお読みください。 )あなたがコミュニティからより多くの、より良い答えを得るのを助けるので、質問する前に。あなたの質問を編集し、そこにログを追加するだけでなく、メインを追加します。人々は通常、質問のビット全体を検索する気にしません。あなたにはNPE(Null Pointer Exception)があります。また、変数名には大文字を使用しないでください。 – Bonatti

+0

logcatはそこにあります。メインコードから何を切り離すべきかわからないので、それは意味をなさないでしょう。問題がどこから始まるのかわからないので、私はここにすべて掲載しました。 –

+0

問題: '原因:java.lang.NullPointerException:仮想オブジェクト 'boolean android.bluetooth.BluetoothAdapter.isEnabled()'をヌルオブジェクト参照で呼び出しようとしました'行からif(BA.isEnabled() )) 'BluetoothAdapter.getDefaultAdapter();が何ができるのかを確認します。あなたのBA変数はnullです。最後に、 'Left'や' Connect'のような最初の大文字はクラスのためのものではありません。 – Bonatti

答えて

0

あなたはこのようにBluetoothアダプタを取得しようとすることができます。

+0

同じことをしていますが、マネージャーを使用しています。返品としてまだヌルです –

+0

あなたは文脈の使い方を教えていただけますか?どこでどのように宣言すべきですか?私の以前の回答を申し訳ありませんが、私は良いAPIレベルを使用していないことを認識しました。 –

関連する問題