Khalid Taha
Khalid Taha

Reputation: 3313

CalledFromWrongThreadException:Only the original thread that created a view hierarchy can touch its views

I tried to change a value of a ListView adapter using a thread, but it throws an exception that is CalledFromWrongThreadException can anyone call a thread that changes a value of any View element? here is my code:

new Thread(new Runnable(){

    public void run() 
    {
        ap=(ArrayList<Application>) getBoughtApps(android_id);
        adapter1 = new MyCustomAdapter(ap);
        listView = ( ListView ) MainActivity.this.findViewById(R.id.listview);
            changeAdapter();    
    }
}).start();

Upvotes: 0

Views: 406

Answers (2)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

First Option :

use runOnUiThread for Updating UI from Non - Ui Thread. change your code as:

new Thread(new Runnable(){

    public void run() 
    {
      ap=(ArrayList<Application>) getBoughtApps(android_id);
       Current_Activity.this.runOnUiThread(new Runnable() {
         public void run() {

           adapter1 = new MyCustomAdapter(ap);
           listView = ( ListView ) MainActivity.this.findViewById(R.id.listview);
           changeAdapter(); 
          //Your code here..
         }
       });

    }
}).start();


Second Option :

You can use AsyncTask instead of a Thread for making Network Operations or if application require to Update Ui from Background. you can change your current code using AsyncTask as :

private class CallwebTask extends AsyncTask<Void, Void, String>
{

    protected ArrayList<Application> doInBackground(String... params) 
    {
        ap=(ArrayList<Application>) getBoughtApps(android_id);
        return ap; // Return ArrayList<Application>
    }

    protected onPostExecute(ArrayList<Application> result) {
        Log.i("OnPostExecute :: ", String.valueOf(result.size()));
        //Put UI related code here
        adapter1 = new MyCustomAdapter(result);
        listView = ( ListView ) MainActivity.this.findViewById(R.id.listview);
        changeAdapter(); 
    }
}

and to start AsyncTask put this line where you are starting Thread:

new CallwebTask().execute();

Upvotes: 3

Durairaj Packirisamy
Durairaj Packirisamy

Reputation: 4725

Views can only be accessed by UI threads. You can try the same from runonUIThread block

runOnUiThread(new Runnable() {
    public void run() {
          ap=(ArrayList<Application>) getBoughtApps(android_id);
        adapter1 = new MyCustomAdapter(ap);
        listView = ( ListView ) MainActivity.this.findViewById(R.id.listview);
            changeAdapter();   
    }
});

Upvotes: 1

Related Questions