2012-08-04 101 views
0

我做我與的AsyncTask程序mutlithreading通過調用一個方法後10秒,而是有此異常:運行時異常的AsyncTask

08-04 11:49:29.565: E/log_tag(885): Error converting result java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 

plz幫助我!

編輯:這是對的AsyncTask代碼:

class Getphonenumber extends AsyncTask<String, Void, Void> { 
     public Void doInBackground(String... p) { 
      while (true) { 
       getPhno(); 
      try { 
      Thread.sleep(10000); 
      } catch (InterruptedException ie) { 
      ie.printStackTrace(); 
      } 
      } 
     } 

     }; 

'getPhno()' 方法:

public void getPhno() 
    { 
     try{ 

      HttpClient httpclient = new DefaultHttpClient(); 
      HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000); //Timeout Limit 
      List<NameValuePair> username = new ArrayList<NameValuePair>(); 
      username.add(new BasicNameValuePair("username", user)); 
      //Web Address 
      HttpPost httppost = new HttpPost("http://www.starretailshop.com/Log/Retrieve.php"); 
      httppost.setEntity(new UrlEncodedFormEntity(username)); 
      HttpResponse response = httpclient.execute(httppost); 
      ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
      String responseBody = httpclient.execute(httppost, 
        responseHandler); 

      Log.i("retrieve postData", response.getStatusLine().toString()); 
      InputStream content = response.getEntity().getContent(); 
      BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); 
      String s = ""; 
      while ((s = buffer.readLine()) != null) { 

       sendMsg(s,msg); 

      } 

      }catch(Exception e){ 

        Log.e("log_tag", "Error converting result "+e.toString()); 
      } 
    } 

'SENDMSG' 方法:

private void sendMsg(String phoneNumber, String message) 
    { 
     try{ 
      String phoneNumber1 = null; 

      if(phoneNumber.startsWith("+")) 
      { 
       phoneNumber1 = phoneNumber.substring(3); 

      } 
      else if(phoneNumber.startsWith("0")) 
      { 
       phoneNumber1 = phoneNumber.substring(1); 
      } 
      else 
      { 
       phoneNumber1=phoneNumber; 
      } 
       PendingIntent pi = PendingIntent.getActivity(this, 0, 
        new Intent(), 0);     
       SmsManager sms = SmsManager.getDefault(); 
       sms.sendTextMessage(phoneNumber1, null, message, pi, null); 
       Toast.makeText(this,"Msg sent to:" + phoneNumber1, Toast.LENGTH_LONG).show(); 
       phnoList.add(phoneNumber); 
       phnoListd.add(phoneNumber1); 
       //phnumber = phoneNumber; 
       //================Update Database===================== 

       try{ 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000); //Timeout Limit 
        List<NameValuePair> updatemsg = new ArrayList<NameValuePair>(); 
        updatemsg.add(new BasicNameValuePair("outmsg1", message)); 
        Calendar cal = Calendar.getInstance(); 
        SimpleDateFormat sdf = new SimpleDateFormat("HH:m:ss dd-MM-yyyy"); 
        String TimeStampDB = sdf.format(cal.getTime()); 
        updatemsg.add(new BasicNameValuePair("currentdatetime1",TimeStampDB)); 
        updatemsg.add(new BasicNameValuePair("mobileno",phoneNumber)); 

        //Web Address 
        HttpPost httppost = new HttpPost("http://www.starretailshop.com/Log/Update1.php"); 
        httppost.setEntity(new UrlEncodedFormEntity(updatemsg)); 
        HttpResponse response = httpclient.execute(httppost); 
        ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
        String responseBody = httpclient.execute(httppost, 
          responseHandler); 
        Log.i("update1 postData", response.getStatusLine().toString()); 
        }catch(Exception e){ 
         Log.e("log_tag", "Error converting result "+e.toString()); 
        } 

        //================================================ 
      }catch(Exception e) 
      { 
       e.printStackTrace(); 
       Toast.makeText(this,"Error occured", Toast.LENGTH_LONG).show(); 
      } 


} 

最後我打電話new Getphonenumber().execute();在Button的onClickListener中。

+2

分享你創建處理程序的代碼部分。 – Siddharth 2012-08-04 06:29:39

+0

@ Siddharth-我用這個例子作爲ia新到AsyncTask ..http://stackoverflow.com/questions/4068984/running-multiple-asynctasks-at-the-same-time-not-possible – 2012-08-04 06:31:10

回答

3

我認爲問題在於,您正嘗試從背景線程更新您的UI組件。

例如,考慮在你的AsyncTask這種方法,

protected Void doInBackground(String ... x) { 
     while (true) { 
     System.out.println(x[0]); 
     try { 
     Thread.sleep(1000); 
     } catch (InterruptedException ie) { 
     ie.printStackTrace(); 
     } 
     } 

,此方法只相當於一個後臺線程。在Andorid中,你可以只更新你的用戶界面,只從主界面線程中進行更新,當你嘗試從其他任何方法來完成時,你會得到這個異常。

所以儘量避免這種情況。如果你想更新你的UI,使用你的AsyncTask的onPostExecute()。

編輯1

這裏是你的問題。從sendMsg方法刪除吐司,它應該工作正常。

+0

@ Andro-Can你給我提供一些鏈接..感謝您的回覆! – 2012-08-04 06:42:56

+0

我編輯了我的答案。請檢查。 – 2012-08-04 06:43:24

+0

@ Andro-U r絕對正確的夥計...非常感謝你! – 2012-08-04 06:53:53

1

而不是在doBackround內部創建睡眠線程,在執行.execute()之前執行。我想這會有所幫助。

2

使用runOnUiThread更新非UI用戶界面Thread.like as code由您提供。你正在顯示來自後臺線程的Toast消息,所以把Toast消息放入runOnUiThread中:

Current_Activity.this.runOnUiThread(new Runnable() { 
    public void run() { 

    Toast.makeText(this,"Msg sent to:" + phoneNumber1, Toast.LENGTH_LONG).show(); 
    } 
}); 
+0

或者你可以嘗試你的代碼後評論吐司消息,我認爲那麼你的代碼工作完美 – 2012-08-04 07:06:03

+0

- 知道了..謝謝男人! – 2012-08-04 07:06:29