Search code examples
androidandroid-asynctask

Call Asynctask execute with void and cursor as parameters


I wrote a Asynctask as

private class dboperation extends AsyncTask<Void, Void, Cursor>

I am new to android and wrote by searching a lot in google but got struck on how to call the Async Task from another class with these parameters.

Code

private class dboperation extends AsyncTask<Void, Void, Cursor>{


        @Override
        protected Cursor doInBackground(Void... params) {
            // TODO Auto-generated method stub
            getstocks="Select " + st.column1 + " as _id, " + st.column3 + " From "+ st.tablename;
            a1=Database.getInstance(getApplicationContext()).getWritableDatabase().rawQuery(getstocks, null);


            return null;
        }


        protected void onPostExecute(Cursor result) {
            if(a1.moveToNext())
            {
                displaystocks.setVisibility(View.INVISIBLE);
            }
            final poplist populatestocks=new poplist(getApplicationContext(),a1) ;
            popstocks.setAdapter(populatestocks);
        }

        @Override
        protected void onPreExecute() {
        }

        protected void onProgressUpdate(Void... values) {
        }


    }

when I am calling this way it is giving me error "Void cannot be resolved into variable".

dboperation.execute(Void,Void,a1);

How can I resolve this?


Solution

  • In AsyncTask

    • 1st param means the type you can pass to execute. Void means you can pass nothing

    The class names in Java should start with upper-calse letter. Please rename it for better readability by others.

    So proper call would be

    new DbOperation().execute();
    
    • 2nd param is a type of data you can publish calling publishProgress() from doInBackground(). You don't use publishProgress, so nothing to mention in this case.

    • 3rd param meana s type that will be passed to onPostExecute(). To pass the Cursor to onPostExecute you must return it from doInBackground

      @Override
      protected Cursor doInBackground(Void... params) {
      
          getstocks="Select " + st.column1 + " as _id, " + st.column3 + " From "+ st.tablename;
          return Database.getInstance(getApplicationContext()).getWritableDatabase().rawQuery(getstocks, null);
      }