android asynctask edittext

时间:2011-12-20 23:34:56

标签: android android-asynctask

我有一段代码来查询我的webserver xml解析回来的数据并用我的相关数据填充我的GUi上的文本字段。在我的oncreate函数中使用之前,代码工作正常。但是,我想向用户显示加载对话框,因此我将Web服务器和xml解析操作符移动到asynctask。现在,当我用我的解析数据填充我的GUI文本字段时,问题就出现了,我得到一个错误。任何人都可以看到我做错了什么

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) {
}

}

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:4)

您无法从非UI线程更新UI元素。尝试将所有setText()调用和webview.loadData()移动到onPostExecute()

您必须将查询结果保存在类对象中才能执行该操作

答案 1 :(得分:0)

试试这个,

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