0

我正在使用 runOnUiThread 从 asyntask 显示 UI,但我的应用程序崩溃了,请帮助我该怎么办?我如何直接在 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();
    }
}

  }
4

8 回答 8

0

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

于 2013-10-04T06:10:12.227 回答
0

在 doInBackground 你有parseJSONData()

parseJSONData()你有以下

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

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

您正在更新doInBackground(). 你可能会遇到一个例外。您无法从与 UI 线程不同步的后台线程更新 UI。

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

所以返回 json 对象doInbackground。计算的结果doInbackground是一个参数onPostExecute。所以根据结果更新你的文本视图onPostExecute

您需要初始化这些txt1, txt2, txt3. 我也看到你在膨胀一个新的布局parseJSONData()。我不确定为什么。您可以在中初始化您的文本视图您可以在onCreate中更新txt1, txt2, txt3onPostExecute

于 2013-10-04T06:14:02.753 回答
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...
于 2013-10-04T06:15:11.510 回答
0

当您使用时,AsyncTask您不能在doInBackground().

我更喜欢你使用onPostExecute()

protected void onPostExecute(Void results) {

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

    }

顺便说一句,AsyncTask 有onProgressUpdate. 您可以将其用作回调:

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

[编辑]

顺便说一句,添加类似: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();
        }
    }
}
于 2013-10-04T06:19:58.727 回答
0

我想问题出在您的以下代码中。

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

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

于 2013-10-04T06:24:12.233 回答
0

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

于 2013-10-04T06:25:50.550 回答
0

不要在您的doInBackground().

全局声明您的 All 布局 TextView。

在其中创建ArrayList<String> myArraylist1,myArraylist2和存储您的价值观。

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

           myArraylist1.add(school5
                    .getJSONObject(i).getString("name"));
          myArraylist2.school5.getJSONObject(i).getString(
                            "sub_ingredients"));
}

在您的onPostExecute().

textname.setText(myArraylist1.get(0));
于 2013-10-04T06:33:44.823 回答
0

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

您最好在不更改 UI 的情况下在 doInBackground() 中调用 parseJSONData()。

于 2013-10-04T06:59:53.810 回答