2014-10-02 89 views
-1

我正在處理一個應用程序,它將按下按鈕時通過藍牙發送一個字符串。從onCreate創建類方法的實例

藍牙連接正常工作,我可以發送數據正常,但是我在創建write()方法的實例時遇到了一些麻煩,我在按鈕的單擊處理程序中,特別是我應該使用的上下文,這是我得到一個空指針異常。

這裏是我的代碼:

package sjtech.rompa.wifi;

public class Wifi extends Activity implements OnItemClickListener { 

     ArrayAdapter<String> listAdapter; 
     ListView listView; 
     BluetoothAdapter btAdapter; 
     Set<BluetoothDevice> devicesArray; 
     ArrayList<String> pairedDevices; 
     ArrayList<BluetoothDevice> devices; 
     public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 
     protected static final int SUCCESS_CONNECT = 0; 
     protected static final int MESSAGE_READ = 1; 
     IntentFilter filter; 
     BroadcastReceiver receiver; 
     String tag = "debugging"; 


     private Button currentcolour; 
     private Button redbtn; 
     private Button grnbtn; 
     private Button bluebtn; 
     private Button yellowbtn; 
     private Button orangebtn; 
     private Button purplebtn; 
     private Button pinkbtn; 
     private Button whitebtn; 
     private Button resetbtn; 
     private Button blueleftarrow; 
     public BluetoothDevice mBluetoothAdapter; 
     public String outputStream;   
     public InputStream inStream; 
     public ImageView btoff; 
     MediaPlayer sndred; 
     MediaPlayer sndgrn; 
     MediaPlayer sndblue; 
     MediaPlayer sndyel; 
     MediaPlayer sndwht; 
     MediaPlayer sndpnk; 
     MediaPlayer sndpple; 
     MediaPlayer sndorng; 
     MediaPlayer sndrst; 

Handler mHandler = new Handler(){ 
      @Override 
      public void handleMessage(Message msg) { 
       // TODO Auto-generated method stub 
       Log.i(tag, "in handler"); 
       super.handleMessage(msg); 
       switch(msg.what){ 
       case SUCCESS_CONNECT: 
        // DO something 
     ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj); 
        Toast toast= Toast.makeText(getApplicationContext(),  
           "CONNECT", Toast.LENGTH_SHORT); 
           toast.setGravity(Gravity.CENTER, 0, 0); 
           toast.show(); 
        String s = "successfully connected"; 
        connectedThread.write(s.getBytes()); 
        Log.i(tag, "connected"); 
        break; 
       case MESSAGE_READ: 
        byte[] readBuf = (byte[])msg.obj; 
        String string = new String(readBuf); 
    Toast toast2= Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT); 
        toast2.setGravity(Gravity.CENTER, 0, 0); 
        toast2.show(); 

        break; 

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




        currentcolour= (Button) findViewById(R.id.currentcolour);     

      init(); 
      if(btAdapter==null){             //if no BT then show toast and close.     Toast toast3= Toast.makeText(getApplicationContext(), "No bluetooth detected", Toast.LENGTH_SHORT); 
      toast3.setGravity(Gravity.CENTER, 0, 0); 
      toast3.show(); 


       finish(); 
      } 
      else{ 
       if(!btAdapter.isEnabled()){            //if BT available but not enabled turn on BT. 
        turnOnBT(); 
       } 

       getPairedDevices(); 
       startDiscovery(); 
      } 

     //**********************************************RED BUTTON*********** *************************************** 
      sndred = MediaPlayer.create(Wifi.this, R.raw.sndred); // create instance of mediaPlayer 
      redbtn = (Button) findViewById(R.id.redbtn);  // Get a reference to the button 
      redbtn.setOnClickListener(new View.OnClickListener() { // Set the click listener to run the code. 
      @Override 
      public void onClick(View v) {      // red button's click event 

      sndred.start();        // play red sound     
      currentcolour.setBackgroundColor(Color.RED);         //set currentColour to red. 

      ConnectedThread con = new ConnectedThread(null);   

      con.write("".getBytes());     //Send string via bluetooth.           
     // con.write(new byte[] {0x30, 0x38,});   //Send byte via bluetooth. 

      } 
      }); 

    } 
      }); 





     } 
     private void startDiscovery() { 
      // TODO Auto-generated method stub 
      btAdapter.cancelDiscovery(); 
      btAdapter.startDiscovery(); 

     } 
     private void turnOnBT() { 
      // TODO Auto-generated method stub 
      Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(intent, 1); 
     } 
     private void getPairedDevices() { 
      // TODO Auto-generated method stub 
      devicesArray = btAdapter.getBondedDevices(); 
      if(devicesArray.size()>0){ 
       for(BluetoothDevice device:devicesArray){ 
        pairedDevices.add(device.getName()); 

       } 
      } 
     } 
     private void init() { 
      // TODO Auto-generated method stub 
      listView=(ListView)findViewById(R.id.listView); 
      listView.setOnItemClickListener(this); 
      listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0); 
      listView.setAdapter(listAdapter); 
      btAdapter = BluetoothAdapter.getDefaultAdapter(); 
      pairedDevices = new ArrayList<String>(); 
      filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
      devices = new ArrayList<BluetoothDevice>(); 
      receiver = new BroadcastReceiver(){ 
       @Override 
       public void onReceive(Context context, Intent intent) { 
        // TODO Auto-generated method stub 
        String action = intent.getAction(); 

        if(BluetoothDevice.ACTION_FOUND.equals(action)){ 
         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
         devices.add(device); 
         String s = ""; 
         for(int a = 0; a < pairedDevices.size(); a++){ 
          if(device.getName().equals(pairedDevices.get(a))){ 
           //append 
           s = "(Paired)"; 
           break; 
          } 
         } 

         listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress()); 
        } 

        else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){ 
         Toast toast= Toast.makeText(getApplicationContext(), //Show toast that bluetooth is already disabled. 
            "STARTED DEVICE DISCOVERY", Toast.LENGTH_SHORT); 
            toast.setGravity(Gravity.CENTER, 0, 0); 
            toast.show(); 
        } 
        else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ 
         Toast toast= Toast.makeText(getApplicationContext(), //Show toast that bluetooth is already disabled. 
            "FINISHED DEVICE DISCOVERY!", Toast.LENGTH_SHORT); 
            toast.setGravity(Gravity.CENTER, 0, 0); 
            toast.show(); 



        } 
        else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){ 
         if(btAdapter.getState() == btAdapter.STATE_OFF){ 
          turnOnBT(); 
         } 
        } 

       } 
      }; 

      registerReceiver(receiver, filter); 
      filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED); 
      registerReceiver(receiver, filter); 
      filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
      registerReceiver(receiver, filter); 
      filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); 
      registerReceiver(receiver, filter); 
     } 


     @Override 
     protected void onPause() { 
      // TODO Auto-generated method stub 
      super.onPause(); 
      unregisterReceiver(receiver); 
     } 

      @Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
       // TODO Auto-generated method stub 
       super.onActivityResult(requestCode, resultCode, data); 
       if(resultCode == RESULT_CANCELED){ 
     Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show(); 
        finish(); 
       } 
      } 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, //when discovered item in listview is selected then: cancel discovery, start connection 
        long arg3) { 
       // TODO Auto-generated method stub 

       if(btAdapter.isDiscovering()){ 
        btAdapter.cancelDiscovery(); 
       } 
       if(listAdapter.getItem(arg2).contains("Paired")){ 

        BluetoothDevice selectedDevice = devices.get(arg2); 
        ConnectThread connect = new ConnectThread(selectedDevice); 
        connect.start(); 
        Log.i(tag, "in click listener"); 
       } 
       else{ 
      Toast.makeText(getApplicationContext(), "device is not paired", 0).show(); 
       } 
      } 

      private class ConnectThread extends Thread { 

       private final BluetoothSocket mmSocket; 
       private final BluetoothDevice mmDevice; 

       public ConnectThread(BluetoothDevice device) { 
        // Use a temporary object that is later assigned to mmSocket, 
        // because mmSocket is final 
        BluetoothSocket tmp = null; 
        mmDevice = device; 
        Log.i(tag, "construct"); 
        // Get a BluetoothSocket to connect with the given BluetoothDevice 
        try { 
         // MY_UUID is the app's UUID string, also used by the server code 
         tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
        } catch (IOException e) { 
         Log.i(tag, "get socket failed"); 

        } 
        mmSocket = tmp; 
       } 

       public void run() { 
        // Cancel discovery because it will slow down the connection 
        btAdapter.cancelDiscovery(); 
        Log.i(tag, "connect - run"); 
        try { 
         // Connect the device through the socket. This will block 
         // until it succeeds or throws an exception 
         mmSocket.connect(); 
         Log.i(tag, "connect - succeeded"); 

      } catch (IOException connectException) { Log.i(tag, "connect failed"); 
         // Unable to connect; close the socket and get out 
         try { 
          mmSocket.close(); 
         } catch (IOException closeException) { } 
         return; 
        } 

        // Do work to manage the connection (in a separate thread) 

        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget(); 
       } 



       /** Will cancel an in-progress connection, and close the socket */ 
       public void cancel() { 
        try { 
         mmSocket.close(); 
        } catch (IOException e) { } 
       } 
      } 

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

       public ConnectedThread(BluetoothSocket socket) { 
        mmSocket = socket; 
        InputStream tmpIn = null; 
        OutputStream tmpOut = null; 

        // Get the input and output streams, using temp objects because 
        // member streams are final 
        try { 
Null pointer points here>>>> tmpIn = socket.getInputStream(); <<<<******************* 
         tmpOut = socket.getOutputStream(); 
        } catch (IOException e) { } 

        mmInStream = tmpIn; 
        mmOutStream = tmpOut; 


       } 

       public void run() { 
        byte[] buffer; // buffer store for the stream 
        int bytes; // bytes returned from read() 

        // Keep listening to the InputStream until an exception occurs 
        while (true) { 
         try { 
          // Read from the InputStream 
          buffer = new byte[1024]; 
          bytes = mmInStream.read(buffer); 
          // Send the obtained bytes to the UI activity 
          mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
            .sendToTarget(); 

         } catch (IOException e) { 
          break; 
         } 
        } 
       } 

       /* Call this from the main activity to send data to the remote device */ 
       public void write(byte[] bytes) { 
        try { 
         mmOutStream.write(bytes); 
        } catch (IOException e) { 
         e.printStackTrace(); 

        } 
       } 

       /* Call this from the main activity to shutdown the connection */ 
       public void cancel() { 
        try { 
         mmSocket.close(); 
        } catch (IOException e) { } 
       } 
      } 

我調用write()這樣的:

ConnectedThread con = new ConnectedThread(what context to use??); //Create an instance of ConnectedThread 

    con.write("ABC".getBytes());      //Send string via bluetooth.           
// con.write(new byte[] {0x30, 0x38,});    //Send byte via bluetooth. 

這裏有來自logcat中的臺詞:

10-02 08:02:44.539: E/AndroidRuntime(23489): FATAL EXCEPTION: main 
10-02 08:02:44.539: E/AndroidRuntime(23489): java.lang.NullPointerException 
10-02 08:02:44.539: E/AndroidRuntime(23489): at sjtech.rompa.wifi.Wifi$ConnectedThread.<init>(Wifi.java:491) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at sjtech.rompa.wifi.Wifi$2.onClick(Wifi.java:158) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at android.view.View.performClick(View.java:4452) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at android.widget.Button.performClick(Button.java:148) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at android.view.View$PerformClick.run(View.java:18428) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at android.os.Handler.handleCallback(Handler.java:725) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at android.os.Handler.dispatchMessage(Handler.java:92) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at android.os.Looper.loop(Looper.java:176) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at android.app.ActivityThread.main(ActivityThread.java:5365) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at java.lang.reflect.Method.invokeNative(Native Method) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at java.lang.reflect.Method.invoke(Method.java:511) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 
10-02 08:02:44.539: E/AndroidRuntime(23489): at dalvik.system.NativeStart.main(Native Method) 

ID真的在這裏得到一些幫助,我是新在這個和不能理解上下文,不幸的是我沒有選擇,只能得到這個工作!

在此先感謝,併爲任何能幫助我的人提供一個大金星。

回答

0

「ConnectedThread con = new ConnectedThread(使用什麼上下文??);」

構造函數接受BluetoothSocket實例。假設是這樣的:

public void connected(BluetoothSocket socket) {    
    ConnectedThread = new ConnectedThread(socket);    
} 

「不過我有一些麻煩,在我的點擊處理程序創建write()方法的一個實例,」

你應該寫字節DATAS到流不ConnectedThread實例。

mmOutStream.write("ABC".getBytes()); 
+0

感謝您的答案,雖然我不知道如何使用您的建議,我想訪問我的onCreate中的ConnectedThread類的write()方法 – user3812950 2014-10-02 14:07:53