mercredi 19 août 2015

screen freezing on making big sqlite request using asyncTask

I am trying to make a complex SQLite query using AsyncTask and it results in ANR. I can get where the problem is. Here is my AsyncTask class:

private void callBackground(String type, int page, Date date){
    SetParamsForQuery params = new SetParamsForQuery(type, page, date);
    backgroundTask backgroundTask = new backgroundTask();
    backgroundTask.execute(params);
}

private static class SetParamsForQuery {
    String type;
    int page;
    Date sDate;

    public SetParamsForQuery(String type, int page, Date date) {
        this.type = type;
        this.page = page;
        this.sDate = date;
    }
}

private class backgroundTask extends AsyncTask<SetParamsForQuery, Void, HashMap<String, ArrayList<ArrayList<esProperty>>>>
{
    @Override protected void onPreExecute()
    {
    }

    @Override protected HashMap<String, ArrayList<ArrayList<esProperty>>> doInBackground(SetParamsForQuery... params) {
        return esData.requestData(params[0].type, params[0].page, params[0].sDate);
    }

    @Override protected void onPostExecute(HashMap<String, ArrayList<ArrayList<esProperty>>>  result)
    {
        Log.d(TAG, " result  "+ result.size());
        if(mode == R.string.today)
            otherChart(result, TODAY);
        if(mode == R.string.week)
            otherChart(result, WEEK);
        if(mode == R.string.month)
            otherChart(result, MONTH);
    }
}

here is my requestData method

 public HashMap<String,ArrayList<ArrayList<esProperty>>> requestData(final String mode, final int page,final Date second){
     es = new esDatabaseHandler();
     HashMap<String, ArrayList<ArrayList<esProperty>>> hash = new HashMap<>();
     try{
         ActiveAndroid.beginTransaction()
         for (int i = 0; i < 24; i++) {
             if (page == 1) {
                 Calendar c = Calendar.getInstance();
                 hash = es.createHash(es.getDayFromToday(c.getTime(), too, page), null, mode);
             } 
             else {
                 hash = es.createHash(es.getDayFromToday(second, too, page), null, mode);
             }
         }
         Log.d(TAG, " Background "+ hash.size());
         ActiveAndroid.setTransactionSuccessful();
     } 
     finally {
         ActiveAndroid.endTransaction();
     }
 }

The method requestData is running queries in loop in SQLite and returning hash. I know the reasons why ANR happens but it seems like I am doing correct

Aucun commentaire:

Enregistrer un commentaire