0

在我的应用程序中,我需要执行网络操作,所以我创建了一个AsyncTask类来在后台执行它,但是我需要用我得到的信息填充一些文本视图。

所以我的问题是我可以在主线程中做什么来等待AsyncTask类完成doInBackground操作

这是我的 AsyncTask 类:

public class ObtenerDatos extends AsyncTask<Void, Void, Void> {

    private PuertosSaxParser saxparser;
    private ArrayList<clsPuertos> Puertos;

    /** Return the Puertos info to the main class */
    public ArrayList<clsPuertos> getPuertos() {
        return Puertos;
    }

    /** Get the XML info and do the parse */
    @Override
    protected Void doInBackground(Void... params) {
        try {
            saxparser = new PuertosSaxParser("http://www.androide.comyr.com/valores.xml");
            Puertos = saxparser.parseXML();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

这就是我从主线程中调用它的方式:

try {
    int_datos.execute();
    //HERE I NEED TO WAIT FOR THE AsyncTask TO COMPLETE THE doInBackground OPERATIONS
    Puertos = int_datos.getPuertos();
    //THEN I FILL THE TEXTVIEWs WITH THE INFO OF Puertos
} catch (Exception e) {
    e.printStackTrace();
}

谢谢你的帮助!

编辑:

主类:

ObtenerDatos int_datos = new ObtenerDatos(this);
int_datos.execute();

ObtenerDatos(AsyncTask 类):

public class ObtenerDatos extends AsyncTask<Void, Void, Void> {

    private PuertosSaxParser saxparser;
    private ArrayList<clsPuertos> Puertos;
    private Context contexto;
    final TextView textSanferPleamarHora = new TextView(contexto);

    public ObtenerDatos(Context contexto){
        this.contexto = contexto;
    }

我尝试将上下文从 Main 传递给AsyncTask类以在那里设置,TextViews但我得到了一些错误。

这是正确的吗?

4

2 回答 2

3

所以我的问题是我可以在主线程中做什么来等待 AsyncTask 类完成“doInBackground”操作

不要这样做。使用类似的东西的完整点AsyncTask阻塞主应用程序线程。

onPostExecute()AsyncTask.

于 2013-05-23T20:44:22.233 回答
1

无论您想将什么数据设置为 textView,您都可以简单地在 postExecute 方法中执行,您可以从 doInbackground 共享您的数据,只需将最后一个 void 作为字符串并传递字符串

于 2013-05-23T20:48:53.153 回答