Last updated on July 31st, 2016 at 11:14 am
AsyncTasks in android is the most common when we need to load data. This class allows to perform in background operations and publish results on the UI thread without having to manipulate threads and/or handlers. AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. We need AsyncTask no of time in our app to make call to server and load data in different activity. In this post i create ReUsable AsyncTasks class we use in our project and load data from server we have no need to implement multiple time AsyncTask class to load data from server.
Before you start please read about Dependency Injection in java.
Sample code: ReUsable AsyncTasks class in Android
Step 1. First create new class in your project you create and name that class you like i name that class AsyncReuse.java and copy/paste this code.
*Note: Please use updated class i add updated code at the end of this page.
package com.trinitytuts.Utils; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * Created by Aneh Thakur on 29-01-2015. */public class AsyncReuse AsyncTask<Void, Void, Void> { HttpClient client; HttpResponse Server_response; String response; public GetResponse getResponse = null; JSONObject jsonObject; String URLs; boolean dialogE = true; Activity activity; // Dialog builder private ProgressDialog Dialog; public AsyncReuse(String url, boolean dialog, Activity activity1) { URLs = url; dialogE = dialog; activity = activity1; } public void getObjectQ(JSONObject object) { jsonObject = object; } @Override protected void onPreExecute() { super.onPreExecute(); if (dialogE) { Dialog = new ProgressDialog(activity); Dialog.setMessage("Wait.."); Dialog.setCancelable(false); Dialog.show(); } } @Override protected Void doInBackground(Void... voids) { try { client = new DefaultHttpClient(); HttpPost post = new HttpPost(URLs); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); List<NameValuePair> nVP = new ArrayList<NameValuePair>(); nVP.add(new BasicNameValuePair("oauth", jsonObject.toString())); reqEntity.addPart("oauth", new StringBody(jsonObject.toString())); post.setEntity(reqEntity); Server_response = client.execute(post); if (Server_response != null) { InputStream in = Server_response.getEntity().getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(in, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } in.close(); response = sb.toString(); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (Server_response.getStatusLine().getStatusCode() == 200) { getResponse.getData(response); } else { Toast.makeText(activity, "Unable to reach server try again", Toast.LENGTH_LONG).show(); } if (dialogE) { Dialog.dismiss(); } } }
Above code is easy to understand if you familiar with AsyncTask. In above class i extends AsyncTask and implement its method PreExecute, DoInbackground and PostExecute. I create this class dynamic so i send parameter in this class from outside using its object.
Step 2. Now we need to interface in our project in which we can pass data from AsyncReuse.java class as shown above first i create a object and call its method inside onPostExecute() method.
public GetResponse getResponse = null;
@Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (Server_response.getStatusLine().getStatusCode() == 200) { getResponse.getData(response); } else { Toast.makeText(activity, "Unable to reach server try again", Toast.LENGTH_LONG).show(); } if (dialogE) { Dialog.dismiss(); } }
Now create interface like this
package com.trinitytuts.Utils; /** * Created by Aneh Thakur on 29-01-2015. */ public interface GetResponse { public Void getData(String objects); }
Step 3. Now every thing we need is done, we call this class any where in our project where we need AsyncTask. Here how i call this class in my project.
public class MainActivity extends Activity implements GetResponse { AsyncReuse requestServer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); executeServerReq(); JSONObject jObject = new JSONObject(); try { jObject.put("username", "Aneh"); jObject.put("password", "test12345"); } catch (JSONException e) { e.printStackTrace(); } requestServer.getObjectQ(jObject); requestServer.execute(); } }); } // Execute async task class public void executeServerReq() { requestServer = new RequestServer("yourlogin.php", true, MainActivity.this); requestServer.getResponse = this; } @Override public Void getData(String objects) { Log.e("Response", "----------"+objects); return null; } }
Hope this helps a lot in your project.Please comment if any issue you face implementing this in your project.
Update
Updated AsyncTask Class with Timeout feature dialog box null pointer exception issue and other update:-)
import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * Created by Aneh Thakur 3 on 23-04-2015. */ public class AsyncReuse extends AsyncTask<Void, Void, Void> { public GetResponse getResponse = null; HttpClient client; HttpPost method; HttpResponse Server_response; String response = "{\"status\":\"0\",\"msg\":\"Sorry something went wrong try again\"}"; JSONObject jsonObject; String URLs; boolean dialogE = true; Activity activity; // Dialog builder private ProgressDialog Dialog; public AsyncReuse(String url, boolean dialog, Activity activity1) { URLs = url; dialogE = dialog; activity = activity1; } public AsyncReuse(String url, boolean dialog) { URLs = url; dialogE = dialog; } public void getObjectQ(JSONObject object) { jsonObject = object; } @Override protected void onPreExecute() { super.onPreExecute(); if (dialogE) { Dialog = new ProgressDialog(activity); Dialog.setMessage("Please Wait.."); Dialog.setCancelable(false); Dialog.show(); } } @Override protected Void doInBackground(Void... voids) { /*try { //Dialog.dismiss(); client = new DefaultHttpClient(); HttpPost post = new HttpPost(URLs); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); List<NameValuePair> nVP = new ArrayList<NameValuePair>(); nVP.add(new BasicNameValuePair("r", jsonObject.toString())); reqEntity.addPart("r", new StringBody(jsonObject.toString())); post.setEntity(reqEntity); Server_response = client.execute(post); if (Server_response != null) { InputStream in = Server_response.getEntity().getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(in, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } in.close(); response = sb.toString(); } } catch (Exception e) { e.printStackTrace(); }*/ try { // set the connection timeout value to 30 seconds (30000 milliseconds) client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 60000); HttpConnectionParams.setSoTimeout(httpParams, 60000); client = new DefaultHttpClient(); method = new HttpPost(URLs); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("r", new StringBody(jsonObject.toString())); method.setEntity(reqEntity); Server_response = client.execute(method); StatusLine statusLine = Server_response.getStatusLine(); if (Server_response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); Server_response.getEntity().writeTo(out); response = out.toString(); out.close(); Dialog.dismiss(); } else if (Server_response.getStatusLine().getStatusCode() != HttpStatus.SC_BAD_REQUEST) { Dialog.dismiss(); } else if (Server_response.getStatusLine().getStatusCode() != HttpStatus.SC_REQUEST_TIMEOUT) { response = "{\"status\":\"0\",\"msg\":\"Connection timeout.\"}"; Dialog.dismiss(); } else { Server_response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (UnsupportedEncodingException e) { // Unsporting error } catch (ClientProtocolException e) { //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (Dialog != null) { Dialog.dismiss(); } getResponse.getData(response); } }