Search code examples
javaandroidandroid-asynctask

How to get data from SQLite in asynchronously?


I have in my onCreate() a method which get the needed data for my Activity from database, the issue is that when the Activity starts I can see that it's locked until the data from the database is fetched so I would move to an AsyncTask.

The issue is that I make multiple requests to the DB as I have to get multiple data, how can I achieve it by using AsyncTask?

Would AsyncTask be the best fit for this situation?

Here is how my code looks like:

protected void onCreate(Bundle savedInstanceState) {
    LoadDataDB();
}

public void LoadDataDB() {
    myDB = DataBaseHandler.getInstance(this);
    listMenu = myDB.getMenu();
    listTasti = myDB.getTasti();
    listVarianti = myDB.getVarianti();
    listPrinters = myDB.getPrinters();

    if (isFamiglieEnabled) {
        listFamiglie = myDB.getFamiglie();
    }

    if (isAYCEnabled) {
        listAYCE = myDB.getAYCE();
    }
}

And functions like .getMenu and other looks like this:

public ArrayList<MenuConstructor> getMenu() {
    database = this.getReadableDatabase();
    Cursor cursor = database.query(TABLE_MENU, null, null, null, null, null, null);
    ArrayList<MenuConstructor> menuList = new ArrayList<>();
    MenuConstructor contactModel;
    if (cursor.getCount() > 0) {
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            contactModel = new MenuConstructor(Integer.parseInt(cursor.getString(0)),
                    cursor.getString(1), cursor.getString(2),
                    cursor.getString(3));
            menuList.add(contactModel);
        }
    }
    cursor.close();
    database.close();
    return menuList;
}

Solution

  • Using AsyncTask

    1. create a single asyncTask for every data request. fetch the data in doInBackground and update the UI in postExecute.

    I suggest you can use executor service with Handler. pass the runnable to the executor service execute it and using handler post the result to main thread