Reputation: 24998
I have a simple database in my Android app that contains information about countries. One of the things I have to do is to populate a dropdown menu with the names of the countries.
So, I wrote some simple code like so:
public class FetchCountryAsync extends AsyncTask<String,Void,Cursor> {
private Context con;
private CountryConsumer consumer;
//----------------------------------------------------------------------------------------------
public FetchCountryAsync(Context con, CountryConsumer consumer) {
this.con = con;
this.consumer = consumer;
}
//----------------------------------------------------------------------------------------------
@Override
protected Cursor doInBackground(String... params) {
CountryDatabaseHelper helper = new CountryDatabaseHelper(con);
Cursor countries = helper.getCountries();
return countries;
}
//----------------------------------------------------------------------------------------------
@Override
public void onPostExecute(Cursor countries){
if(!isCancelled()){
consumer.setCountries( countries );
}
}
//----------------------------------------------------------------------------------------------
}
There's a lot of mumbo-jumbo that I did to make it work - an AsyncTask
, an interface
.
My question is, would it have been a better approach to write my own ContentProvider
and avoid the hassle of AsyncTask
altogether?
Upvotes: 3
Views: 1283
Reputation: 121
It depends on you and what your plans are for your app.
Writing a ContentProvider would likely have been more work but it would provide a much more thorough, flexible access point to the data that you can reuse across your app. Eg query, insert, update, delete methods accessible via Uri.
ContentProviders allow you to centralize and abstract access to DB/other data in your app. This way if the db structure ever changes there's one access point to update for managing information. It just makes things cleaner in my experience. Also, if you ever decide to share the info to other apps the ContentProvider implementation will make that easy.
If its just a 1-off information retrieval task for a single activity in the app, what you have seems fine. If you'll be using it across the app and updating/inserting data in the db or doing more complex queries, it's probably worth the extra time/complexity to make a ContentProvider.
There's another good discussion related to this topic here.
Upvotes: 1