Question

I need to fetch list of data from server, feed to adapter, and show in list view.

Question is who should do the backend call, activity or adapter or ?

And please elaborate why. This question is more about why than how.

Please answer in an model view controller or similar (I know strictly speaking android does not have MVC) context.

Edit:

It's now obvious to me adapter is very bad place to fetch data (imagine how un-flexible it will be. E.g., what if there are two end points for similar kind of data. Or I have two adapter for same data set, it make no sense to let one of the adapters fetch data). Other component should be fetching data and filling adapter. Activity is a good component to do so.

The accepted answer provides an illustration of doing it.

Was it helpful?

Solution

Never fetch data from an Activity because it will block the UI.

You should extend AsyncTask with parameters and return type as you wish. Do your work on the method doInBackground (@Override it) and on the method onPostExecute (@Override it), call some public method on your Activity to give to it the data you fetched.

Finally, the Activity with the fresh data should feed it to do Adapter.

This is how I always get my data and I get the results 100% as I want (add a progressBar and make it visible before fetching the data and make it invisible after you give it to the adapter).

Hope I was clear enough to you. If you want some code as an example, please ask.

Workflow:

1 - Activity -> new MyAsyncTask(...).execute(); //get the data @Override doInBackGround

2 - MyAsyncTask.onPostExecute() {myActivity.giveFreshData(...)} //deliver the data

3 - Activity.giveFreshData(...) {MyListAdapter.giveMyData(...)}

Altough it isn't MVC this is how you should separate the UI from the data consumption and the data representation.

OTHER TIPS

Neither of them, I would create a class that make the requests and transfom it into objects, then the activity take this objects and pass them to the adapter.

Actually you can fetch data directly from an activity, only if this is an async task. (but it would generate duplicated code)

The Adapter class it is usually used to transform objects into something visible in lists and stuff like that

The activity would be like a controller, that interacts with the class that fetch data from the server and the adapter.

then you will need a class to fetch the data and return it into java objects (is it not necessary, but if you are using MVC it is the ost correct way to do it). Also if you call directly an asynctask from the activity, if exists more activities that need to do this same request, then you will have duplicated code (and everybody know that it is never good). Then it is that why we need another class that will transform requests into objects in a callback captured by the activity, this class can be reused from all activities or classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top