如何在后台类的列表视图中添加数据

时间:2016-03-14 17:27:29

标签: java android

我收到此异常

  

android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。

以下是代码:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page2);



        lv = (ListView) findViewById(R.id.list_view);



        btnNew = (Button)findViewById(R.id.btnAddNew);
        btnNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent moveToNewUser = new Intent(getApplication(),ExecutiveInfo2.class);
                moveToNewUser.putExtra("ClickType","1");
                startActivity(moveToNewUser);
            }
        });

        new Connection2().execute();

        // Listview Data
       }

    private class Connection2 extends AsyncTask {

        @Override
        protected Object doInBackground(Object... arg0) {
            test2();
            return null;
        }

        @Override
        protected void onPostExecute(Object s) {
        super.onPostExecute(s);
      }

    }

    public void test2() {
        HttpURLConnection connection = null;
        try {
            sharedpreferences = getSharedPreferences("MyPrefs", this.MODE_PRIVATE);

             String storedUUID = sharedpreferences.getString("UUID", "");

            String url2= "http://crm.xqicai.com/sales/getExecutiveInfo?UUID="+storedUUID;
            //String url = "http://crm.xqicai.com/sales/login";
            URL postUrl = new URL(url2);

            connection = (HttpURLConnection) postUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);

            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编�,�则中文乱�

            while (true) {
                String str = reader.readLine();
                if (str == null) {
                    break;
                }
                System.out.println(str);

                JSONObject mainObject = new JSONObject(str);
                Status = mainObject.getString("status");
                int j=0;
                if(Status.equals("0"))
                {
                    JSONObject uniObject = mainObject.getJSONObject("data");
                    JSONArray a = uniObject.getJSONArray("data");
                    for (int i = 0; i < a.length(); i++) {

                        JSONObject json_obj = a.getJSONObject(i);


                        String demo = json_obj.getString("realName");
                        fetchedNames[j]= demo;
                        j++;

                    }

                    // Adding items to listview

                    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);

                    lv.setAdapter(adapter);
                    }
                else
                {
                    JSONObject mainObject2 = new JSONObject(str);
                    errorMsg = mainObject2.getString("msg");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
        }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
 }

我只是一个初学者,所以请原谅我可能会提出一个愚蠢的问题。

3 个答案:

答案 0 :(得分:0)

错误是哪一行?问题是您在AsyncTask(另一个线程)中更新主线程中创建的视图。您应该在AsyncTask的onPostExecute中更新此视图(这在您的主线程中完成)。我没有立即看到您更新视图的位置。

修改 如果你把这两行放在

上,你的问题就应该解决了
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);

在这一行之下:

lv = (ListView) findViewById(R.id.list_view);

或在:

protected void onPostExecute(Object s)

答案 1 :(得分:0)

测试:

    ListView lv...
    lv.post(new Runnable() {
        @Override
        public void run() {
            //Update UI;
            lv.setAdapter(...);
        }
    })

答案 2 :(得分:0)

你可以尝试在asynctask中使用带有sendEmptyMessage()的Handler来传递异常。

离。

Handler mHandler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(Message inputMessage) {

                    // Adding items to listview

                    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);

                    lv.setAdapter(adapter);   
                }
});

注意以下代码:

//在asynctask中调用mHandler.sendEmpyMessage():

if(Status.equals("0"))
                {
                    JSONObject uniObject = mainObject.getJSONObject("data");
                    JSONArray a = uniObject.getJSONArray("data");
                    for (int i = 0; i < a.length(); i++) {

                        JSONObject json_obj = a.getJSONObject(i);


                        String demo = json_obj.getString("realName");
                        fetchedNames[j]= demo;
                        j++;

                    }

                    // Adding items to listview
                    mHandler.sendEmpyMessage(0); //0 or any number is identify code from you want use to check with every action