0

當按下button2時,我的應用崩潰並且出現錯誤,如下面的GamesFragment活動所示。我希望能夠通過調用TopRated其他TopRated活動中的writeData功能來單擊按鈕並將數據發送到藍牙設備。Android NullPointerException藍牙

public class GamesFragment extends Fragment { 
    public Button chaser; 

    private String dataToSend; 
    View rootView; 


    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 

     chaser = (Button) rootView.findViewById(R.id.button2); 

     chaser.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       switch (view.getId()){ 
        case R.id.button2:{ 
         dataToSend = "on"; 
         TopRatedFragment top = new TopRatedFragment(); 

         top.writeData(dataToSend); 


        } 
       } 
      } 
     }); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 

     rootView = inflater.inflate(R.layout.fragment_games, container, false); 

     return rootView; 
    } 
} 

/******* This is where the writedata function is***/ 

public class TopRatedFragment extends Fragment { 
    private ArrayAdapter<String> mNewDevicesArrayAdapter; 
    private OutputStream outStream = null; 
    private String dataToSend; 

    private BluetoothAdapter bluetoothAdapter; 
    public static String EXTRA_DEVICE_ADDRESS = "device_address"; 
    private BluetoothSocket btSocket = null; 
    public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 

    public Button connect; 
    public Button disconnect; 
    View rootView; 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     final Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); 


     // Initialize array adapters. One for already paired devices and 
     // one for newly discovered devices 
     final ArrayAdapter<String> pairedDevicesArrayAdapter = 
       new ArrayAdapter<String>(getActivity(), R.layout.device_name); 
     mNewDevicesArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.device_name); 
     // Register for broadcasts when a device is discovered 
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     ((MainActivity)getActivity()).registerReceiver(this.mReceiver,filter); 



     // Find and set up the ListView for paired devices 
     ListView pairedListView = (ListView) getActivity().findViewById(R.id.listView); 
     pairedListView.setAdapter(pairedDevicesArrayAdapter); 
     pairedListView.setOnItemClickListener(mDeviceClickListener); 

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




     connect = (Button) rootView.findViewById(R.id.button); 

     connect.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       switch (view.getId()){ 
        case R.id.button:{ 
         Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
         startActivityForResult(intent, 1); 

         doDiscovery(); 
         if (pairedDevices.size() > 0) { 
          for (BluetoothDevice device : pairedDevices) { 
           pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
          } 
         } 

        } 
       } 
      } 
     }); 

    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 


     rootView = inflater.inflate(R.layout.fragment_top_rated, container, false); 

     return rootView; 
    } 


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

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

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

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

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

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

     // Unregister broadcast listeners 
     //this.unregisterReceiver(mReceiver); 
     try { 
      btSocket.close(); 
     } catch (IOException e) { 
     } 
    } 
    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 
      bluetoothAdapter.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); 

      BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); 
      try { 
       btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); 
       btSocket.connect(); 
       Toast.makeText(getActivity(),"Connected " + device.getName() ,Toast.LENGTH_SHORT).show(); 

       //Log.d(TAG, "Connexion r�ussie !!"); 
      } catch (IOException e) { 
       try { 
        btSocket.close(); 
       } catch (IOException e2) { 
        //Log.d(TAG, "Impossible de fermer la connexion."); 
       } 
       //Log.d(TAG, "Cr�ation de socket �chou�e."); 
      } 
      // 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); 
       if (mNewDevicesArrayAdapter.getCount() == 0) { 
        //do nothing 
       } 
      } 
     } 
    }; 

    protected void writeData(String data) { 

     try { 
      outStream = btSocket.getOutputStream(); 
     } catch (IOException e) { 
      //Log.d(TAG, "Bug AVANT l'envoie.", e); 
     } 

     String message = data; 

     byte[] msgBuffer = message.getBytes(); 

     try { 
      outStream.write(msgBuffer); 
     } catch (IOException e) { 
       //Log.d(TAG, "Bug DURANT l'envoie.", e); 
     } 
    } 
} 

這是我得到錯誤:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.OutputStream android.bluetooth.BluetoothSocket.getOutputStream()' on a null object reference 
     at info.androidhive.tabsswipe.TopRatedFragment.writeData(TopRatedFragment.java:207) 
     at info.androidhive.tabsswipe.GamesFragment$1.onClick(GamesFragment.java:44) 
     at android.view.View.performClick(View.java:5197) 
     at android.view.View$PerformClick.run(View.java:20926) 

回答

1

outStream在TopRatedFragment爲null,從不初始化。您必須首先初始化outStream,而不是在寫入數據中使用它。順便說一句,從來沒有使用這樣的片段 - 最好的解決方案是將writeData方法移動到另一個類,並在構造函數或此方法中初始化outStream。