KIO
Kreative Ideen online
AsyncTask

AsyncTask

An AsyncTask lets you perform operations in the background. When they’ve finished running, it then allows you to update views in the main event thread. If the task is repetitive, you can even use it to publish the progess of the task while it’s running.

You create an AsyncTask by extending the AsyncTask class, and implementing its doInBackground() method. The code in this method runs in a backgorund thread, so it’s the perfect place for you to put database code.They AsyncTask class also has an onPreExecut() method that runs before doInackground(), and an onPostExecute() method that runs afterward. There’s an onProgessUpdat() method if need to publish task progeress.

//You ann your AsyncTask class as an inner class to the activity that needs to use it
private class MyAsyncTask extend AsyncTask<Params, Progress, Result>{

   //optional. it runs before the code you want to run un the background.  
   protected void onPreExecute(){
     //Code to run before executing the task
    }

   //You must implement this method.It conains the code you want to run in the background.
   protected Result doInBackground(Params ... params){
     //Code that you want to run in a background thread
   }

   //optional.It lets you publish rogress of teh code running in the background
   protected void onProgressUpdate(Progress...values){
     //Code that you want to run to publish the progress of your task
   }

   //optional.It runs after the code has finished runnin in the background
   protected vooid onPostExecute(Result result){
      //Code that you want to run when the task is complete
   }
}

AsyncTask is defined by three generic parameters:Params,Progress, and Results.

  • Params is the type of object used to pass any task parameters tot the doInBackground() method.
  • Progress is the type of object used to indicate task progress,and Result is the type of the task result ou can set anay of these to Void if youre not to use them
  • Result
private class UpdateDrinkTask extends AsyncTask<Integer, Void,Boolean> {
        private ContentValues drinkValues;

        protected void onPreExecute(){
            CheckBox favorite = (CheckBox) findViewById(R.id.favorite);
            drinkValues = new ContentValues();
            drinkValues.put("FAVORITE",favorite.isChecked());
        }

        protected Boolean doInBackground(Integer... drinks){
            int drinkId = drinks[0];
            SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(DrinkActivity.this);
            try {
                SQLiteDatabase db = starbuzzDatabaseHelper.getWritableDatabase();
                db.update("DRINK",drinkValues,"_id = ?",new String[]{Integer.toString(drinkId)});
                db.close();
                return true;
            } catch (SQLiteException e) {
                return false;
            }
        }
        protected void onPostExecute(Boolean success){
            if(!success){
                Toast toast = Toast.makeText(DrinkActivity.this,"Database unavailable", Toast.LENGTH_SHORT);
                toast.show();
            }
            else{
                Toast toast = Toast.makeText(DrinkActivity.this,"Applied changes",Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }

Full activity code for context:

package eu.kio.starbuzz;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;

public class DrinkActivity extends Activity {

    public static final String EXTRA_DRINKID = "drinkId";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

    }

    //Update the database when the checkbox is clicked
    public void onFavoriteClicked(View view) {
        int drinkId = (Integer) getIntent().getExtras().get(EXTRA_DRINKID);
        new UpdateDrinkTask().execute(drinkId);
    }

    //Inner class to update the drink.
    private class UpdateDrinkTask extends AsyncTask<Integer, Void,Boolean> {
        private ContentValues drinkValues;

        protected void onPreExecute(){
            CheckBox favorite = (CheckBox) findViewById(R.id.favorite);
            drinkValues = new ContentValues();
            drinkValues.put("FAVORITE",favorite.isChecked());
        }

        protected Boolean doInBackground(Integer... drinks){
            int drinkId = drinks[0];
            //SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(DrinkActivity.this);

            SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(DrinkActivity.this);

            try {

                SQLiteDatabase db = starbuzzDatabaseHelper.getWritableDatabase();
                db.update("DRINK",drinkValues,"_id = ?",new String[]{Integer.toString(drinkId)});
                db.close();

                /*SQLiteDatabase db = starbuzzDatabaseHelper.getWritableDatabase();
                db.update("DRINK",drinkValues,"_id = ?", new String[]{Integer.toString(drinkId)});
                db.close();*/
                return true;
            } catch (SQLiteException e) {
                return false;
            }
        }

        protected void onPostExecute(Boolean success){
            if(!success){
                Toast toast = Toast.makeText(DrinkActivity.this,"Database unavailable", Toast.LENGTH_SHORT);
                toast.show();
            }
            else{
                Toast toast = Toast.makeText(DrinkActivity.this,"Applied changes",Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *