调用asynctask时runOnUiThread崩溃

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

标签: android

即时通讯使用runOnUiThread显示UI fromasyntask但我的应用程序崩溃请帮助我,我该怎么办?我如何直接在postexecute上显示你的Ui ???我很困惑为什么runOnUiThread崩溃????如何在屏幕上显示我的textview值?

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

// TextView ingredient;

View row4;
int IOConnect = 0;
View row3;

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;
    TableLayout table;
String name;
    LinearLayout table3;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fifthscreen);
            table = (TableLayout) findViewById(R.id.table2);
           table3 = (LinearLayout) findViewById(R.id.table3);
}

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

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        parseJSONData();
    }
}

public void parseJSONData() {

    SelectMenuAPI = Utils.dishdescription;

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

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

        JSONObject json2 = new JSONObject(str);

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

            row3 = getLayoutInflater().inflate(R.layout.rows, null);
            ((TextView) row3.findViewById(R.id.localTime)).setText(school3
                    .getJSONObject(s).getString("qty"));
((TextView) row3.findViewById(R.id.apprentTemp))

       .setText(school3.getJSONObject(s).getString("name"));

            //fifthscreen.this.runOnUiThread(new Runnable() {
                //public void run() {
                    table.addView(row3);
                //}
            //});

        }

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

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

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

            row4 = getLayoutInflater().inflate(R.layout.row2, null);
            ((TextView) row4.findViewById(R.id.name)).setText(school5
                    .getJSONObject(i).getString("name"));
            ((TextView) row4.findViewById(R.id.subingredients))
                    .setText(school5.getJSONObject(i).getString(
                            "sub_ingredients"));

            // table3.addView(row2);

            //fifthscreen.this.runOnUiThread(new Runnable() {
            //  public void run() {
                    table3.addView(row4);
                //}
            //});

        }

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

  }

8 个答案:

答案 0 :(得分:0)

runUIthread本身就是一个线程,我认为你不能再运行另一个AsyncTask线程。
您无法在doInBackground中更新UI

答案 1 :(得分:0)

在doInBackground中,您有parseJSONData()

parseJSONData()中,您有以下

 ((TextView) row3.findViewById(R.id.apprentTemp))

   .setText(school3.getJSONObject(s).getString("name"));

您正在doInBackground()更新用户界面。你可能会遇到异常。您无法从未与UI线程同步的后台线程更新UI。

您已将textview声明为类成员。所以在onCreate初始化。您的asynctask是您的活动类的内部类。

因此返回doInbackground中的json对象。 doInbackground计算的结果是onPostExecute的参数。因此,根据结果更新onPostExecute

中的textview

您需要初始化这些txt1, txt2, txt3。我也看到你在parseJSONData()中夸大了一个新的布局。我不知道为什么。您可以在onCreate中初始化文字视图。您可以在txt1, txt2, txt3更新onPostExecute

答案 2 :(得分:0)

you are Accessing UI Element into you are do in background...remove it..
1) 
you can return the values from you method public JSonObject parseJSonData()..
2)
now change the AsynTask<Void,Void,String>
public String doInBackGround(Void..arg){}
public onPostExecute(String...arg)

{
//use the TextField here to print the data
}

Try it..this could help...

答案 3 :(得分:0)

当您使用AsyncTask时,无法在doInBackground()内调用UI活动。

我希望您使用onPostExecute()

protected void onPostExecute(Void results) {

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //  update GUI here
            }
        }, 50); // dummy delay

    }

BTW,AsyncTask有onProgressUpdate。您可以将其用作回调:

 @Override
    protected void onProgressUpdate(String... values) { /***/}

<强> [编辑]

BTW,在添加新视图

之前添加类似table.removeAllViews();的内容
public class fifthscreen extends Activity {
    String num = null;
    // TextView ingredient;
    private RatingBar ratingBar;
    // TextView ingredient;
    long Menu_ID;
    String dish_name;
    View row4;
    int IOConnect = 0;
    View row3;

    String status;
    private  Handler mHandler;
    HorizontalListView listview;
    CategoryListAdapter3 cla;
    String DescriptionAPI;
    // ImageLoader2 imgLoader;
    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;
    String name;

    String description;
    String url1;

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

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

        androidAQuery = new AQuery(this);

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

        cla = new CategoryListAdapter3(fifthscreen.this);

        new getDataTask().execute();

    }

    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
            if (IOConnect == 0) {
                txt1.setText(name);
                txt3.setText(description);
                androidAQuery.id(img1).image(url1, false, false);
                listview.setAdapter(cla);

            }
        }
    }

    public void parseJSONData() {

        SelectMenuAPI = "http://198.57.208.46/~school/api/index/getDishDiscription?dish_name=testingdish";

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

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

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

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

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

                    row3 = getLayoutInflater().inflate(R.layout.rows, null);
                    ((TextView) row3.findViewById(R.id.localTime))
                    .setText(school3.getJSONObject(s).getString("qty"));
                    ((TextView) row3.findViewById(R.id.apprentTemp))
                    .setText(school3.getJSONObject(s).getString("name"));

                    mHandler.post(new Runnable() {

                        public void run() {
                            table.removeAllViews();
                            table.addView(row3);
                        }
                    });

                }

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

                }

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

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

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

                    row4 = getLayoutInflater().inflate(R.layout.row2, null);
                    ((TextView) row4.findViewById(R.id.name)).setText(school5
                            .getJSONObject(i).getString("name"));
                    ((TextView) row4.findViewById(R.id.subingredients))
                    .setText(school5.getJSONObject(i).getString(
                            "sub_ingredients"));

                    mHandler.post(new Runnable() {

                        public void run() {
                            table3.removeAllViews();
                            table3.addView(row4);
                        }
                    });

                }

            }

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

答案 4 :(得分:0)

我想问题出在你的下面的代码中。

  fifthscreen.this.runOnUiThread(new Runnable() {
            public void run() {
                table3.addView(row4);
            }
        });

您无法在线程上更新UI,因此只需删除runOnUiThread即可更新UI并直接添加视图。

答案 5 :(得分:0)

从doInbackground()中删除parseJSONData()此方法,因为不允许asInctask从doInBackground方法更新UI。把这个方法放在onPostExecute()那里它肯定会起作用。因为您无法在doInBackground()方法中更新UI。

答案 6 :(得分:0)

请勿在{{1​​}}。

中更新您的观看次数

全局声明全部布局,TextView。

创建doInBackground(),&amp;将您的值存储在其中。

ArrayList<String> myArraylist1,myArraylist2

添加所有值&amp;查看for (int i = 0; i < school5.length(); i++) { myArraylist1.add(school5 .getJSONObject(i).getString("name")); myArraylist2.school5.getJSONObject(i).getString( "sub_ingredients")); }

onPostExecute()

答案 7 :(得分:0)

在此方法中无需更改UI,您可以简单地调用包含相同活动和更改的UI更改的方法。你可以在onPostExecute方法中调用该方法。

最好在doInBackground()中调用parseJSONData()而不更改UI。