how to add data in list view from background class

I am getting this exception

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Below is the code:

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 {

        }
 }

I'm only a beginner, so please forgive me for asking possibly a stupid question.

Answers


What line is giving the error? The problem is that you update a view created in the main thread, in your AsyncTask (a different thread). You should update this view in the onPostExecute of your AsyncTask (this is done in your main thread). I don't see immediately where you update the view.

EDIT: Your problem should be solved if you put these two lines

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

below this line:

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

or in the:

protected void onPostExecute(Object s)

Test that:

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

you can try use Handler with sendEmptyMessage() inside asynctask to pass by exception.

ex.

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

note for code bellow:

//call mHandler.sendEmpyMessage() in asynctask:

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

Need Your Help

Divider issue in android xml layout

android xml layout divider buttonbar

My goal is to get the layout like the sample about. However, I can't get the small line above the button bar.

UITextField being clipped during CABasicAnimation with keyPath of bounds.size.width

ios uitextfield core-animation cabasicanimation

I have a somewhat of an odd issue on hand. I have UITextField. This TextField has it’s width resized when a button is tapped. To do that I first did the following: