Recent Posts
- November 2014 (1)
- January 2014 (1)
- October 2013 (1)
- May 2013 (1)
- February 2013 (2)
- October 2012 (1)
- August 2012 (1)
- July 2012 (4)
- June 2012 (13)
Blog Stats
- 36,360 hits
Write your code smartly
Here in this post I will write about how AsyncTask can be created as a single class to make it re useable for other activities. There are some ways to handle the background operations well-known-ed for foreground apps (not services). AsyncTask allows you to execute a specific task such as downloading, loading content from web or communication to server without blocking the main thread (user interface). Writing the code for AsyncTask is quite simple, but what when you have more than one activity to process same piece of code/task in AsyncTask. Now here comes the greatest benefit of Object Oriented Programming concepts and mechanism to write a code which can be re-used. Thanks to an interview question which made me dive into this and get to know how can this be achieved. What we will do here is, create a single AsyncTask and put it in a separate class and make use of it in which ever activity we want. The main problem comes with handling the result of the AsyncTask operation. Lets have a look at how AsyncTask class can be extended to our custom class and we can perform operations required to be done in the background.
First you have to create ad simple class and extend it from AsyncTask
public class myCustomAsyncTask extends AsyncTask{
}
Now myCustomAsyncTask will have a compile time error, stating first suggestion to be : Add unimplemented methods. As you are performing inheritance here and extending the AsyncTask parent class, there is a method defined which must be implemented and that is doInBackground
@Override
protected Object doInBackground(Object... arg0){
return null;
}
doInBackground is the method where the background operation is performed. There are other methods provided by AsyncTask such as onPreExecute, onPostExecute, onCancelled, onProgressUpdate having their own benefits.
If you want to perform some tasks prior to your main background operation such as some parameters initialization, load resources etc, you can do that in onPreExecute method
@Override
protected void onPreExecute(){
// Your code
}
Once we execute AsyncTask, the first method called is onPreExecute and then doInBackground. Now what after the background operations are completed and you want to show some response or play with result. Here comes to use of onPostExecute
protected void onPostExecute(Object o){
// Your code to handle data
}
Note: Updating any UI controls is not allowed in doInBackground method but can be done inside onPostExecute, like update text of a textview or progress bar etc…
So lets create a AsyncTask first.
public class YourAsyncTask extends AsyncTask<Object,Object,Object>{
String s = "";
public YourAsyncTask(){
}
@Override
protected Object doInBackground(Object... arg0) {
return null;
}
protected void onPostExecute(Object o){
}
}
Here we have overridden two AsyncTask methods: doInBackground and onPostExecute. It also have a constructor to get the context of the activity invoking it.
Now there are several ways on handling the response, but without getting out of the Activity context (making activity class members dead (non-static fields)) is what meant here.
Making use of Interface is useful here. Interface helps you implement it when its required by simply using implement following your class name and Interface name.
But before that lets make an interface so we can handle the response of the AsyncTask by implementing its method.
public interface OnTaskCompleted {
void onTaskCompleted(String response);
}
As the above interface shows, there is a method onTaskCompleted which takes an argument of String type must be implemented by any class implementing the interface.
We implement the interface through our activity using
public class MainActivity extends Activity implements OnTaskCompleted {
}
It will ask you to implement unimplemented methods so go ahead with it and you will see the method inside interface onTaskCompleted will be added to the activity class.
public class MainActivity extends Activity implements OnTaskCompleted {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onTaskCompleted(String response) {
}
}
Now using AsyncTask from activity. We will do this inside onCreate method of the activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YourAsyncTask task = new YourAsyncTask(MainActivity.this);
task.execute();
}
Now lets add onTaskCompleted (interface) to the AsyncTask and return the response from onPostExecute. It is also the final code of AsyncTask implementation.
public class YourAsyncTask extends AsyncTask<Object,Object,Object>{
String s = "";
private onTaskCompleted taskCompleted;
public YourAsyncTask(OnTaskCompleted activityContext){
this.taskCompleted = activityContext;
}
@Override
protected Object doInBackground(Object... arg0) {
return null;
}
protected void onPostExecute(Object o){
taskCompleted.onTaskCompleted(s);
}
}
Add the response handling code in the implemented method onTaskCompleted inside activity.
@Override
public void onTaskCompleted(String response) {
// Just showing the response in a Toast message
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
Here is how your final Interface code looks
public interface OnTaskCompleted {
void onTaskCompleted(String response);
}
Activity Full code
public class MainActivity extends Activity implements OnTaskCompleted {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YourAsyncTask task = new YourAsyncTask(MainActivity.this);
task.execute();
}
@Override
public void onTaskCompleted(String response) {
// Just showing the response in a Toast message
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
You can contact me by visiting the about page and picking up the contact details.
Happy coding!