如何从postexecute循环updateui

时间:2013-10-02 07:06:14

标签: android

如何在使用Asyntask forloop数据时更新Ui:

final View row2 = createRow2 (school5.getJSONObject(i));
table3.addView(row2);

即时更新forloop中的UI但是如果我使用asyntask我该怎么做?

   public class fifthscreen extends Activity {

           @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fifthscreen);

            parseJSONData();

}



   public void parseJSONData() {

    SelectMenuAPI = Utils.dishdescription + dish_name;

    clearData();
    URL = SelectMenuAPI;
    URL2 = URL.replace(" ", "%20");

     try {

        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams
                .setConnectionTimeout(client.getParams(), 15000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
        HttpUriRequest request = new HttpGet(URL2);
        HttpResponse response = client.execute(request);
        InputStream atomInputStream = response.getEntity().getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                atomInputStream));

        String line;
        String str = "";
        while ((line = in.readLine()) != null) {
            str += line;
        }

    final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);

            JSONArray school5 = json2.getJSONArray("dish_ingredient");

            for (int i=0; i<school5.length(); i++) {

                final View row2 = createRow2 (school5.getJSONObject(i));
                table3.addView(row2);





    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        // IOConnect = 1;
        e.printStackTrace();
    } catch (JSONException e) {
         // TODO Auto-generated catch block
        e.printStackTrace();
    }
}






           public View createRow2(JSONObject item) throws JSONException {

      View row2 = getLayoutInflater().inflate(R.layout.row2, null);
        ((TextView) row2.findViewById(R.id.name)).setText(item.getString("name"));
        ((TextView)  
       row2.findViewById(R.id.subingredients)).setText(item.getString("sub_ingredients"));

    return row2;
}

如何在postexecute中像这样更新Ui

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

        getDataTask(){

        }

        @Override
         protected void onPreExecute() {
          // TODO Auto-generated method stub

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            parseJSONData();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

        }
    }

如何在onPostExecute

中显示这两行
    //       final View row2 = createRow2 (school5.getJSONObject(i));
        //      table3.addView(row2);

4 个答案:

答案 0 :(得分:1)

使用MainActivity中的Handler对象并发布可运行的对象。要从背景中使用它,您需要将对象设置为可以在MainActivity之外调用的静态,或者您可以创建活动的静态实例来访问它。

活动内部

    private static Handler handler;


    handler = new Handler();

    handler().post(new Runnable() {

        public void run() {
            //ui stuff here :)
            final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);

            JSONArray school5 = json2.getJSONArray("dish_ingredient");

            for (int i=0; i<school5.length(); i++) {

                final View row2 = createRow2 (school5.getJSONObject(i));
                table3.addView(row2);
        }
    });

    public static Handler getHandler() {
       return handler;
    }

活动之外

MainActivity.getHandler().post(new Runnable() {

        public void run() {
            //ui stuff here :)
        }
    });

答案 1 :(得分:0)

尝试像这样拆分代码。并添加处理程序if if和where ui exeption

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

    getDataTask(){

    }

    @Override
     protected void onPreExecute() {
      // TODO Auto-generated method stub

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        SelectMenuAPI = Utils.dishdescription + dish_name;

clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");

 try {

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams
            .setConnectionTimeout(client.getParams(), 15000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
    HttpUriRequest request = new HttpGet(URL2);
    HttpResponse response = client.execute(request);
    InputStream atomInputStream = response.getEntity().getContent();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            atomInputStream));

    String line;
    String str = "";
    while ((line = in.readLine()) != null) {
        str += line;
    }

final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);

        JSONArray school5 = json2.getJSONArray("dish_ingredient");

        for (int i=0; i<school5.length(); i++) {

            final View row2 = createRow2 (school5.getJSONObject(i));
            table3.addView(row2);





} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    // IOConnect = 1;
    e.printStackTrace();
} catch (JSONException e) {
     // TODO Auto-generated catch block
    e.printStackTrace();
}

}

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
public View createRow2(JSONObject item) throws JSONException {

  View row2 = getLayoutInflater().inflate(R.layout.row2, null);
    ((TextView) row2.findViewById(R.id.name)).setText(item.getString("name"));
    ((TextView)  
   row2.findViewById(R.id.subingredients)).setText(item.getString("sub_ingredients"));
    }
}

答案 2 :(得分:-1)

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        //What you want to do, updating a UI in main thread ect.
    }
});

你也可以参考另一篇文章HERE

答案 3 :(得分:-1)

如果在runInBackGround()中调用parseJSONData(),则可以使用runOnUIThread()。

    runOnUiThread(new Runnable() {
        public void run() {
            final View row2 = createRow2(school5.getJSONObject(i));
            table3.addView(row2);
        }
    });