mercredi 2 décembre 2015

AsyncTask vs ContentProvider. What to use when accessing SQLite database?

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?

Aucun commentaire:

Enregistrer un commentaire