在主线程中等待AsyncTask

时间:2013-05-23 20:16:10

标签: android android-asynctask

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

所以我的问题是我可以在主线程中做什么来等待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();
}

感谢您的帮助!

修改

MainClass:

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,但是我遇到了一些错误。

这是对的吗?

2 个答案:

答案 0 :(得分:3)

  

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

不要这样做。使用类似AsyncTask之类的完整和完整点阻止主应用程序线程。

请在onPostExecute()的{​​{1}}中“填写一些textview以及我获得的信息。”

答案 1 :(得分:1)

无论您想要设置为textView的数据,您只需在postExecute方法中执行此操作即可从doInbackground共享您的数据,只需将最后一个void作为字符串并只传递字符串

相关问题