Please see this thread:

https://groups.google.com/forum/#!topic/android-developers/Buiu0XaUSQs

IOTW,

Change this:


runnable.run();


to this:


new Thread(runnable).start();




On Wednesday, January 16, 2013 10:05:19 AM UTC-6, Antonis Kanaris wrote:
>
>  
>   
> I created an application with bluetooth, but when bluetooth is closed i 
> put enable request for open bt but apk crashing,close after show toast 
> request for user and must restart the apk and I have this error... *
> java.lang.NullPointerException* in *io.webbt.Activity2.openBT.Any idea?I 
> must use OnResume OnActivityResult?How i fix it?*
>
> *  public class Activity2 extends Activity {
>
>     public String strValue;
>     public String strValue2;
>     public String strUrlup;
>
>     public String strValued ="http://";;
>     public String strValue2d ="HC-07";
>     public String strValue3d="";
>      
>     public String data="0";//Temperature (data from arduino)
>     
>     public boolean killMe = false;
>     
>     TextView temptext,txt,myLabel,text,text2,text3,text4; 
>       
>     Handler handler = new Handler();
>     
>     BluetoothAdapter mBluetoothAdapter;
>     BluetoothSocket mmSocket;
>     BluetoothDevice mmDevice;
>     OutputStream mmOutputStream;
>     InputStream mmInputStream;
>     
>     Thread workerThread;
>     byte[] readBuffer;
>     int readBufferPosition;
>     int counter;
>     volatile boolean stopWorker;
>     boolean work = true;
>     private static final int REQUEST_ENABLE_BT = 1;
>     public long refreshtime = 30000;//replay download/upload time 30 secs
>     
>     /** Called when the activity is first created. */
>     public void onCreate(Bundle savedInstanceState) {
>         super.onCreate(savedInstanceState);
>         setContentView(R.layout.activity2);
>  
>         myLabel = (TextView)findViewById(R.id.label);
>         temptext = (TextView)findViewById(R.id.temptxt);
>         
>         SharedPreferences preferences = getSharedPreferences("dataioweb" , 
> MODE_PRIVATE);
>         
>            strValue = preferences.getString("Url",strValued);
>               text = (TextView) findViewById(R.id.txt1);
>               text.setText(strValue);
>            strValue2 = preferences.getString("DevName",strValue2d);
>               text2 = (TextView) findViewById(R.id.txt2);  
>               text2.setText(strValue2); 
>            strUrlup = preferences.getString("Urlup",strValue3d);   
>               text4 = (TextView) findViewById(R.id.txt4);  
>               text4.setText(strUrlup); 
>               
>               //findBT();
>     }
>     
>     private class DownloadWebPageTask extends AsyncTask<String, Void, 
> String> {
>         @Override
>         protected String doInBackground(String... urls) {
>           String response = "";
>           for (String url : urls) {
>             DefaultHttpClient client = new DefaultHttpClient();
>             HttpGet httpGet = new HttpGet(url);
>             try {
>               HttpResponse execute = client.execute(httpGet);
>               InputStream content = execute.getEntity().getContent();
>
>               BufferedReader buffer = new BufferedReader(new 
> InputStreamReader(content));
>               String s = "";
>               while ((s = buffer.readLine()) != null) {
>                 response += s;
>               }
>
>             } catch (Exception e) {
>               e.printStackTrace();
>             }
>           }
>           return response;
>         }
>
>         @Override
>         protected void onPostExecute(String result) {
>             TextView text3 = (TextView) findViewById(R.id.txt3);
>             text3.setText(result);
>             try {
>                 sendData(result);
>             } catch (IOException e) {
>                 // TODO Auto-generated catch block
>                 e.printStackTrace();
>             }
>             
>         }
>       }
>
>    
>     
>     protected void onStart() {
>         super.onStart();
>         
>         try
>         {         
>             findBT();
>             openBT();                            
>         }
>         catch (IOException ex) { }
>         
>         runnable.run();
>         
>   }
>
>     protected void onResume() {
>         super.onResume();
>         
>        
>         
>    }
>     
>   private Runnable runnable = new Runnable()
>   {
>       
>       public void run()
>       {
>           if(killMe)
>               return;
>               DownloadWebPageTask task = new DownloadWebPageTask();
>               task.execute(new String[] { strValue });//Download data 
> on/off
>               
>               beginListenForData();//Listen Bluetooth temperature
>               
>               SimpleHttpPut task2 = new SimpleHttpPut();
>                 task2.execute(new String[] { strUrlup,data });//Upload 
> data class
>         
>           handler.postDelayed(this, refreshtime);//Refresh page time
>       }
>   };
>   
>   void findBT() 
>   {
>       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
>       if(mBluetoothAdapter == null)
>       {
>           myLabel.setText("No bluetooth adapter available");
>       }
>      
>       if(!mBluetoothAdapter.isEnabled())
>       {
>           
>           Intent enableBluetooth = new 
> Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
>           startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
>             
>           //mBluetoothAdapter.enable();
>           
>           
>       }
>      
>       Set<BluetoothDevice> pairedDevices = 
> mBluetoothAdapter.getBondedDevices();
>       if(pairedDevices.size() > 0)
>       {
>           for(BluetoothDevice device : pairedDevices)
>           {
>               if(device.getName().equals(strValue2))
>               {
>                   mmDevice = device;
>                   break;
>               }
>           }
>       }
>       myLabel.setText("Bluetooth Device Found");
>   }
>  
>   void openBT() throws IOException
>   {
>       UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); 
> //Standard SerialPortService ID
>       mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);       
>       mmSocket.connect();
>       mmOutputStream = mmSocket.getOutputStream();
>       mmInputStream = mmSocket.getInputStream();
>                 
>       myLabel.setText("Bluetooth Opened");
>   }
>  
>   void sendData(String msg) throws IOException
>   {
>      
>       msg += "\n";
>       mmOutputStream.write(msg.getBytes());
>       myLabel.setText("Data Sent");
>   }
>  
>   void beginListenForData()
>   {
>       final Handler handler = new Handler(); 
>       final byte delimiter = 10; //This is the ASCII code for a newline 
> character
>       
>       stopWorker = false;
>       readBufferPosition = 0;
>       readBuffer = new byte[1024];
>       workerThread = new Thread(new Runnable()
>       {
>           public void run()
>           {                
>              while(!Thread.currentThread().isInterrupted() && !stopWorker)
>              {
>                   try 
>                   {
>                       int bytesAvailable = 
> mmInputStream.available();                        
>                       if(bytesAvailable > 0)
>                       {
>                           byte[] packetBytes = new byte[bytesAvailable];
>                           mmInputStream.read(packetBytes);
>                           for(int i=0;i<bytesAvailable;i++)
>                           {
>                               byte b = packetBytes[i];
>                               if(b == delimiter)
>                               {
>                                   byte[] encodedBytes = new 
> byte[readBufferPosition];
>                                   System.arraycopy(readBuffer, 0, 
> encodedBytes, 0, encodedBytes.length);
>                                     //final String data = new 
> String(encodedBytes, "US-ASCII");
>                                     data = new String(encodedBytes, 
> "US-ASCII");
>                                     
>                                     
>                                   readBufferPosition = 0;
>                                   
>                                   handler.post(new Runnable()
>                                   {
>                                       public void run()
>                                       {
>                                           temptext.setText(data);
>                                           
>                                       }
>                                  });
>                               }
>                               else
>                               {
>                                   readBuffer[readBufferPosition++] = b;
>                               }
>                           }
>                       }
>                   } 
>                   catch (IOException ex) 
>                   {
>                       stopWorker = true;
>                   }
>              }
>          }
>       });
>
>       workerThread.start();
>   }
>   
>     
>     public void Setup(View view) throws IOException
>     {
>         killMe = true;
>         work=false;
>         stopWorker = true;
>         mmOutputStream.close();
>         mmInputStream.close();
>         mmSocket.close();
>         //mBluetoothAdapter.disable();
>         myLabel.setText("Bluetooth Closed");
>         Intent intent = new Intent();
>         setResult(RESULT_OK, intent);
>         finish();
>     }
>    
>     protected void onStop()
>       {
>            
>         super.onStop();
>         killMe = true;
>         work=false;
>             stopWorker = true;
>           try {
>             mmOutputStream.close();
>              mmInputStream.close();
>               mmSocket.close();
>         } catch (IOException e) {
>             // TODO Auto-generated catch block
>             e.printStackTrace();
>         }
>           
>           mBluetoothAdapter.disable();
>           myLabel.setText("Bluetooth Closed");
>           finish();
>           
>       }
>     
>      @Override
>      protected void onDestroy() {//android has killed this activity
>        //Log.d(logtag,"onDestroy() called");
>        super.onDestroy();
>        mBluetoothAdapter.disable();
>        try {
>             mmOutputStream.close();
>              mmInputStream.close();
>               mmSocket.close();
>         } catch (IOException e) {
>             // TODO Auto-generated catch block
>             e.printStackTrace();
>         }
>        killMe = true;
>        finish();
>        }
> }
> *
>

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to