Search code examples
androidandroid-asynctasklistadapter

Call setListAdapter from a different class file


I have a class file like this:

public class Search_Results extends SherlockListActivity{

     String result = "";
     SearchView searchView;
     Context context = this;
     private Intent intent = null;
     private String searchThis = "";

      @Override
      protected void onCreate(Bundle savedInstanceState){
             super.onCreate(savedInstanceState);
             setTheme(R.style.Sherlock___Theme_DarkActionBar);
             setContentView(R.layout.search_results);
             ListView myList=(ListView)findViewById(android.R.id.list);
             ProgressBar progress = (ProgressBar)findViewById(R.id.progress_spin);
             intent = getIntent();
             searchThis = intent.getStringExtra(Home.SEARCH_SERVICE);
             new Retrieve(context, progress, searchThis, myList).execute("");
      }//onCreate
}

This calls new Retrieve() that's on another java file and extends AsyncTask

public class Retrieve extends AsyncTask <String, Integer, ArrayList<String>>{

     private Context context;
     private String title = "";
     private ArrayList<String> list = null;
     private ArrayList<NameValuePair> nameValuePairs = null;
     private String result = "";
     private ProgressBar progress;
     private String searchThis;
     private ListView mylist;

     //constructor
     public Retrieve(Context context, ProgressBar progress, String searchThis, ListView myList) {
         this.context = context;
         this.progress = progress;
         this.searchThis = searchThis;
         this.mylist = myList;
     }
protected ArrayList<String> doInBackground(String... params){
            progress.setVisibility(View.VISIBLE);
            InputStream is = null;
            list = new ArrayList<String>();
            nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("searchThis", searchThis));
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }
            catch(Exception e){
                Log.e("CONNECTION_ERROR", "Error in http connection "+e.toString());
            }
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null){
                    sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
            }
            catch(Exception e){
                Log.e("BUFFER_ERROR", "Error converting result "+e.toString());
            }
            if(result.equalsIgnoreCase("null\n")){
                list.add("empty");
            }
            else{
                try{
                    JSONArray jArray = new JSONArray(result);
                    for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        title = json_data.getString("title");
                        list.add(title);
                    }
                }
                catch(JSONException e){
                    Log.e("DATA_PARSING_ERROR", "Error parsing data "+e.toString());
                }
            }
            return list;
        }

     @Override
     protected void onPostExecute(ArrayList<String> list){
         progress.setVisibility(View.GONE);
         ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(context, R.layout.list_display, list);
         //PROBLEM
         mylist.setAdapter(mArrayAdapter);
     }

 }//Retrieve

I first tried only setListAdapter(mArrayAdapter) but obviosly java doesn't know wich list to update, then i tried passing the list to the constructor doing

ListView myList=(ListView)findViewById(android.R.id.list);

And I get this error:

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

Maybe because I'm trying to change a view from another class? How can I solve this issue? Should the onPostExecute function return the mArrayAdapter? How can this be accomplished?


Solution

  • you are getting Only the original thread that created a view hierarchy can touch its views. because you are trying to access UI elements from doInBackground . so just move it outside from doInBackground and move it inside onPreExecute as :

     @Override
        protected void onPreExecute() {
            super.onPreExecute();
             progress.setVisibility(View.VISIBLE); //<< set here
        }