Search code examples
androidandroid-contextlistadapter

Android async class with setListAdapter


I have an Activity Class with an inner protected class that extends AsyncTask. I am trying to have the AsyncTask load data in background when I click a button and then display a list based on that data.

here is my code for the setListAdapter:

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_row, 
                R.id.rowtextview, testArr.toArray(test2)));

the problem is that I can't just stick setListAdapter into the AsyncTask class because it needs a context for the outer class, and the only place it can go is inside the onCreate() in the outer Activity class. If its inside the onCreate, it can only be used once and isnt dynamic. I am not sure how I would go about making the list re-load every time I click a button and search for something new.


Solution

  • Your custom inner AsyncTask is not marked as static right? That means that it actually holds reference to the parent class, which is you Activity. So you can use:

    setListAdapter(new ArrayAdapter<String>(YourActivity.this, R.layout.list_row, 
                    R.id.rowtextview, testArr.toArray(test2)));