【问题标题】:how to update Ui from background task如何从后台任务更新 UI
【发布时间】:2013-10-08 11:45:17
【问题描述】:

我的应用无法在 android 版本 4.1 上运行,出现 android.os.NetworkOnMainThreadException 之类的异常

我在 stackoverflow 上搜索过建议我在后台做网络线程 AsyncTask 所以在使用 backgroundtask 之前, 我的屏幕看起来像这样 http://imgur.com/PlhS03i 在使用 backgroundtask 后在营养和成分标签中显示多行 我的屏幕看起来像这样 http://imgur.com/zUvxNpy 在成分和营养标签中只显示单行

在后台任务代码之前是这样的,见下文

public class fifthscreen extends Activity {
String num = null;
TextView ingredient;

long Menu_ID;
String dish_name;

String status;

HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;

TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;

static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();

public static String allergen2;
private AQuery androidAQuery;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fifthscreen);
    ingredient = (TextView) findViewById(R.id.ingredient);
    img1 = (ImageView) findViewById(R.id.test_button_image);

    txt1 = (TextView) findViewById(R.id.menuname);
    txt3 = (TextView) findViewById(R.id.description);

    Intent iGet = getIntent();

    ImageView options = (ImageView) findViewById(R.id.options5);
    androidAQuery = new AQuery(this);

    options.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent iMenuList = new Intent(fifthscreen.this,
                    LinkButtons.class);
            startActivity(iMenuList);
        }
    });

    dish_name = iGet.getStringExtra("dish_name");

    listview = (HorizontalListView) this.findViewById(R.id.listview2);

    cla = new CategoryListAdapter3(fifthscreen.this);
    listview.setAdapter(cla);

    parseJSONData();

}

void clearData() {
    Category_ID.clear();
    Category_name.clear();
    Category_image.clear();

}

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;
        }

        JSONObject json2 = new JSONObject(str);

        status = json2.getString("status");
        if (status.equals("1")) {

            JSONArray school2 = json2.getJSONArray("data");

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

                String name = school2.getJSONObject(0).getString("name");
                txt1.setText(name);

                String description = school2.getJSONObject(0).getString(
                        "description");

                txt3.setText(description);

                String url1 = school2.getJSONObject(0).getString("image");

                androidAQuery.id(img1).image(url1, false, false);

            }

            JSONObject school3 = json2.getJSONObject("dish_nutrition");

            final TableLayout table = (TableLayout) findViewById(R.id.table2);

            for (int j = 0; j < school3.length(); j++) {

                String s = String.valueOf(j + 1);

                final View row = createRow(school3.getJSONObject(s));
                table.addView(row);

            }

            JSONArray school4 = json2.getJSONArray("dish_allergen");
            //
            for (int i = 0; i < school4.length(); i++) {
                JSONObject object = school4.getJSONObject(i);

                Category_ID.add((long) i);
                Category_name.add(object.getString("name"));
                Category_image.add(object.getString("image"));
                listview.setAdapter(cla);

            }

    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);

            }

        }

        else {

            JSONArray school2 = json2.getJSONArray("data");
            for (int i = 0; i < school2.length(); i++) {
                JSONObject object = school2.getJSONObject(i);

                Category_ID.add((long) i);
                Category_name.add(object.getString("name"));

            }

        }

    } 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 createRow(JSONObject item) throws JSONException {
    View row = getLayoutInflater().inflate(R.layout.rows, null);
    ((TextView) row.findViewById(R.id.localTime)).setText(item
            .getString("qty"));
    ((TextView) row.findViewById(R.id.apprentTemp)).setText(item
            .getString("name"));

    return row;
}

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;
}

    }

使用AsyncTask后看下面这段代码

 public class fifthscreen extends Activity {
String num = null;
TextView ingredient;

long Menu_ID;
String dish_name;

String status;

HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;

TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
String description;

int IOConnect = 0;
String name;
String url1;
TableLayout table;
LinearLayout table3;
View row;
View row2;

static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fifthscreen);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    ingredient = (TextView) findViewById(R.id.ingredient);
    img1 = (ImageView) findViewById(R.id.test_button_image);

    txt1 = (TextView) findViewById(R.id.menuname);
    // txt2 = (TextView) findViewById(R.id.test_button_text1);
    txt3 = (TextView) findViewById(R.id.description);

    table = (TableLayout) findViewById(R.id.table2);
    table3 = (LinearLayout) findViewById(R.id.table3);

    Intent iGet = getIntent();

    ImageView options = (ImageView) findViewById(R.id.options5);
    androidAQuery = new AQuery(this);

    options.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent iMenuList = new Intent(fifthscreen.this,
                    LinkButtons.class);
            startActivity(iMenuList);
        }
    });

    dish_name = iGet.getStringExtra("dish_name");

    listview = (HorizontalListView) this.findViewById(R.id.listview2);

    cla = new CategoryListAdapter3(fifthscreen.this);

    new getDataTask().execute();

    // listview.setAdapter(cla);

    ImageView btnback = (ImageView) findViewById(R.id.btnback);

    btnback.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    parseJSONData();

}

void clearData() {
    Category_ID.clear();
    Category_name.clear();
    Category_image.clear();

}

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) {
        // TODO Auto-generated method stub
        txt1.setText(name);
         txt3.setText(description);
        androidAQuery.id(img1).image(url1, false, false);

        table.addView(row);
        table3.addView(row2);
        listview.setAdapter(cla);

    }
}

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;
        }

        JSONObject json2 = new JSONObject(str);

        status = json2.getString("status");
        if (status.equals("1")) {

            JSONArray school2 = json2.getJSONArray("data");

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

                name = school2.getJSONObject(0).getString("name");

                description = school2.getJSONObject(0).getString(
                        "description");

                url1 = school2.getJSONObject(0).getString("image");

            }

            JSONObject school3 = json2.getJSONObject("dish_nutrition");

            for (int j = 0; j < school3.length(); j++) {

                String s = String.valueOf(j + 1);

                row = createRow(school3.getJSONObject(s));

            }

            JSONArray school4 = json2.getJSONArray("dish_allergen");
            //
            for (int i = 0; i < school4.length(); i++) {
                JSONObject object = school4.getJSONObject(i);

                Category_ID.add((long) i);
                Category_name.add(object.getString("name"));
                Category_image.add(object.getString("image"));

            }

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

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

                row2 = createRow2(school5.getJSONObject(i));

            }

        }

        else {

            JSONArray school2 = json2.getJSONArray("data");
            for (int i = 0; i < school2.length(); i++) {
                JSONObject object = school2.getJSONObject(i);

                Category_ID.add((long) i);
                Category_name.add(object.getString("name"));

            }

        }

    } 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 createRow(JSONObject item) throws JSONException {
    View row = getLayoutInflater().inflate(R.layout.rows, null);
    ((TextView) row.findViewById(R.id.localTime)).setText(item
            .getString("qty"));
    ((TextView) row.findViewById(R.id.apprentTemp)).setText(item
            .getString("name"));

    return row;
}

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 row2 = createRow2(school5.getJSONObject(i)); 中更新
  • 为什么要调用 parsejsondata 两次?在 asynctask 和 oncreate 中
  • 在 oncreate 我忘记删除只告诉我如何显示这个循环值 row = createRow(school3.getJSONObject(s));在执行后
  • 你真的很聪明吗? :) 检查:android.os.NetworkOnMainThreadException
  • paresh 只是告诉我在使用 asyntask 之前在 forloop 中更新了我的 ui,然后在此行中使用 asyntask final View row = createRow(school3.getJSONObject(s));如何从 postexecute 像这样更新 Ui

标签: android android-asynctask androidhttpclient networkonmainthread


【解决方案1】:

使用 MainActivity 中的 Handler 对象并发布一个可运行文件。要从背景中使用它,您需要使对象成为静态对象,您可以在 MainActivity 之外调用它,或者您可以创建 Activity 的静态实例来访问它。

活动内部

    private static Handler handler;


    handler = new Handler();

    handler().post(new Runnable() {

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

    public static Handler getHandler() {
       return handler;
    }

活动之外

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

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

【讨论】:

  • 在 MainActivity 中将处理程序创建为静态,然后创建静态 getter,以便您可以从后台调用该方法
  • 在您操作 UI 内容(如设置文本)时使用此方法。
【解决方案2】:

您需要创建 AsyncTask 类并使用它 在这里阅读更多:AsyncTask

示例如下所示:

private class UploadTask extends AsyncTask<Void, Void, Void>
{
    private String in;

    public UploadTask(String input)
    {
        this.in = input;
    }

    @Override
    protected void onPreExecute()
    {
        //start showing progress here
    }

    @Override
    protected Void doInBackground(Void... params)
    {
      //do your work
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        //stop showing progress here
    }

}

然后像这样开始任务:

UploadTask ut= new UploadTask(input); ut.execute();

【讨论】:

  • 但看到我的代码我在 parsemethod 中使用 forloop 并添加 row2 = createRow2(school5.getJSONObject(i));此行不适用于 postexecute 方法,仅显示单行
  • 我已经这样做了 add row2 = createRow2(school5.getJSONObject(i));并在执行后显示像这样 table3.addView(row2);
  • 如何显示这个循环值 row = createRow(school3.getJSONObject(s));从 parseJSONData();在执行后显示
【解决方案3】:

你可以像这样使用**runOnUiThread()**

try {
   // code runs in a thread
   runOnUiThread(new Runnable() {
       @Override
       public void run() {

         // YOUR CODE

       }
  });
} catch (final Exception ex) {
     Log.i("---","Exception in thread");
}

【讨论】:

  • 如何在 postexecute 中使用 forloop 更新 UI
【解决方案4】:

您正在使用这些方法处理 ui

public View createRow(JSONObject item) throws JSONException {
    View row = getLayoutInflater().inflate(R.layout.rows, null);
    ((TextView) row.findViewById(R.id.localTime)).setText(item
            .getString("qty"));
    ((TextView) row.findViewById(R.id.apprentTemp)).setText(item
            .getString("name"));

    return row;
}

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;
}

在后台线程中调用

如果可能,请在 onPostExecute 中执行,或者您可以使用 runOnUiThreadHandler

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多