2013-07-25 35 views
0

所以我有這個從網站獲取數據的AsyncTask,並且在它的post之後執行它調用一個main函數來爲main的textview設置setText。AsyncTask/Handler lagging UI

這是代碼。

@Override 
protected Void doInBackground(String... arg0) {  
    result = connect(start);//connect to the webpage, start is a URL 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
protected void onPostExecute(Void result) { 
    super.onPostExecute(result); 

    Document doc = Jsoup.parse(this.result); 
    Elements stuff = doc.select("td"); 

    MainActivity.GetData(doc);//set the textview 
} 

我每5秒調用一次處理程序來執行此操作,這裏是處理程序代碼。

hand = new Handler();  
r = new Runnable() { 

    @Override 
    public void run() { 
      dh = new DownloadHelper("http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours"); 
      dh.execute("");// TODO Auto-generated method stub 
      hand.postDelayed(this, 10000); 
     } 
    }; 

hand.post(r); 

會發生什麼,當網站加載時,我的UI滯後很多,幾乎到了凍結的地步。我不知道是什麼導致了這一點,我的用戶界面基於ViewPager,帶有碎片。

我沒有從片段中運行此代碼,但它從我主要活動的onCreate運行。

編輯:我編輯我onPostExecute看起來像這樣

@Override 
protected void onPostExecute(Void result) { 
    // TODO Auto-generated method stub 



    super.onPostExecute(result); 

     Elements stuff = doc.select("td"); 
    String[] arr = new String[stuff.size()]; 
    for(int i = 0 ; i < 3 ; i ++) 
    { 

     arr[i] = stuff.get(79 + i).text(); 

    } 

    MainActivity.GetData(arr); 
    MainActivity.dismissLoading(); 
} 

這是我的GetData

public static void GetData(String[] s) 
{ 

edit.setText(s[0]); 




} 

這是連接()

public static String connect(String l) 
{ 

    String url = l; 
    HttpURLConnection connect; 
    String result; 
    String result2 = null; 
    BufferedReader br; 

    try { 
     connect = (HttpURLConnection) (new URL(url)).openConnection(); 
     br = new BufferedReader(new InputStreamReader(connect.getInputStream())); 
     while ((result = br.readLine()) != null) 
     { 
      result2 += result; 
     } 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 

      e.printStackTrace(); 
      System.out.print("ERROR"); 
    } 
    return result2; 

} 
+0

你有沒有嘗試在'doInBackground'內執行'Jsoup.parse(this.result)'? – Desert

+0

解析和讀取文件也應在非ui線程中完成。嘗試將調用移動到解析()內doInBackground() –

+0

@SaurabhVerma我試過了,它仍然滯後..可能是因爲處理程序每​​10秒創建一個新的AsyncTask? (我在我的文章中弄錯了,它是10秒而不是5) – user2519193

回答

1

對於任何人究竟是誰偶然發現我的問題,並希望得到答案,我設法修復它在另一個項目上工作。

基本上,在

while ((result = br.readLine()) != null) 
    { 
     result2 += result; 
    } 

環,而不是附加結果直接RESULT2,追加結果一個StringBuffer。然後在循環結束時,將StringBuffer加回到result2。