2011-12-20 78 views
1

我有一段代碼查詢我的web服務器xml解析返回的數據並在我的GUi中填充相關數據的文本域。之前我有我的oncreate函數中的這個代碼工作正常。不過,我想向用戶顯示一個加載對話框,所以我將Web服務器和xml解析操作移到了asynctask中。現在的問題是,當我用我的解析數據填充我的GUI文本字段時,我得到了一個錯誤。任何人都可以看到我在做什麼錯android asynctask edittext

new BackgroundAsyncTask().execute(); /// called from the oncreate function 

,我的後臺任務的代碼如下

public class BackgroundAsyncTask extends 
AsyncTask<Void, Integer, Void> { 
int myProgress; 

@Override 
protected void onPostExecute(Void result) { 
MyDialog.dismiss(); 
} 

@Override 
protected void onPreExecute() { 
MyDialog = ProgressDialog.show(attraction_more_info.this, " " , " Loading. Please wait ... ", true); 

} 

@Override 
protected Void doInBackground(Void... params) { 

       xml query and parse stuff on here ... 


    // Populate page now 

    TextView titlefield = (TextView) findViewById(R.id.att_title); 
    TextView add1field = (TextView) findViewById(R.id.att_address1); 
    TextView add2field = (TextView) findViewById(R.id.att_address2); 
    TextView townfield = (TextView) findViewById(R.id.att_town); 
    TextView postcodefield = (TextView) findViewById(R.id.att_postcode); 
    TextView phonefield = (TextView) findViewById(R.id.att_phone); 
    WebView webview = (WebView) findViewById(R.id.webview1); 

       MY ERRORS START HERE 
    titlefield.setText(attraction_name); 
    add1field.setText(attraction_address1); 
    add2field.setText(attraction_address2); 
    townfield.setText(attraction_town); 
    postcodefield.setText(attraction_postcode); 
    phonefield.setText(attraction_phone); 
    webview.loadData(attraction_description, "text/html", null); 

return null; 
} 

@Override 
protected void onProgressUpdate(Integer... values) { 
} 

} 

任何人都可以幫我嗎?

+0

還沒有讀取您的代碼,但錯誤是什麼,它發生在哪裏?請提供日誌。 – 2011-12-20 23:39:04

回答

4

您無法從非UI線程更新UI元素。嘗試移動所有的setText()調用和webview.loadData()來onPostExecute()

你必須保存在類對象的查詢結果做

+0

但是我們已經讀過,我們可以從異步task.UI更新更新UI是不可能在線程中。 – Sameer 2011-12-21 04:30:41

+0

@TofeeqAhmad您可以通過doInBackground()以外的方法從異步任務更新UI(或從doInBackground()中調用)doInBackground在單獨的線程中運行。 – antlersoft 2011-12-21 17:43:36

0

試試這個,

add1field.post(new Runnable() { 
    public void run() {    
     add1field.setText(attraction_address1); 
    } 
});