Android Basics – Learn how to use an AsyncTask to create a background thread

Like you have seen earlier the code written in the MainActivity class runs in the main thread. If you run the database related code like insert/update etc. on the MainThread then it will slow the App and can lead to bad user experience.

AsyncTask class helps us to overcome this by creating a background thread. Let’s see how to use this.

An AsyncTask has the following methods

  • onPreExecute() : Runs on the main thread and allows you to do initial setup
  • doInBackground() : Runs on a background thread.
  • onPostExecute() : Runs on the Main Thread after the task completes.

Refer to the code segment below in which an inner AsyncTask has been created.

private class SurveyDBAsyncTask extends AsyncTask<String, Void, Long>{

    ContentValues cv;

    @Override
    protected void onPreExecute() {
        Log.v(TAG, "Data entered by the user is "+userNameId.getText()+" "+userAgeId.getText()+" "+userEmailId);

        cv = new ContentValues();
        cv.put(SurveyDBHelper.SURVEY_TABLE_NAME_COLUMN, userNameId.getText().toString());
        cv.put(SurveyDBHelper.SURVEY_TABLE_EMAIL_COLUMN, userEmailId.getText().toString());
        cv.put(SurveyDBHelper.SURVEY_TABLE_AGE_COLUMN, userAgeId.getText().toString());

        super.onPreExecute();
    }

    /**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to {@link #execute}
     * by the caller of this task.
     * <p/>
     * This method can call {@link #publishProgress} to publish updates
     * on the UI thread.
     *
     * @param params The parameters of the task.
     * @return A result, defined by the subclass of this task.
     * @see #onPreExecute()
     * @see #onPostExecute
     * @see #publishProgress
     */
    @Override
    protected Long doInBackground(String... params) {
        long id = 0;

        try {
            SurveyDBHelper surveyDBHelper = new SurveyDBHelper(MainActivity.this);
            SQLiteDatabase db = surveyDBHelper.getReadableDatabase();

            id = db.insert(SurveyDBHelper.SURVEY_TABLE, null, cv);

            db.close();
        }catch (SQLiteException e){
            Log.v(TAG, "Exception "+e.getMessage());
        }
        return id;
    }

    @Override
    protected void onPostExecute(Long id) {
        super.onPostExecute(id);
    }
}

You can find the complete source code here.

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s