API calling using AsyncHttpClient

Today we work on AsyncHttpClient for parsing the data from an API

What is AsyncHttpClient?

The AsyncHttpClient can be used to make asynchronous GET, POST, PUT and DELETE HTTP requests in your Android applications. Requests can be made with additional parameters by passing a RequestParams instance, and responses can be handled by passing an anonymously overridden ResponseHandlerInterface instance.



 Here I write an empty class which will hold the model object as per model class.
 Model class is just a getter setter class.

public class DataModel implements Serializable {
}
 
 Lets create an interface which will hold the parsing data 


public interface NotifyTasKDone {
    void onTaskDone(DataModel in);
}
 
 
Add the following line on your gradle file
dependencies {
      compile 'com.loopj.android:android-async-http:1.4.9'
 }
 
  Lets create a class for taskhandler with name NetworkHandler
 
 Here I use a gson library for parsing json data


public class NetworkHandler {
    NotifyTasKDone tasKDone;
    Context context;
    String modelName;
    RequestParams param;
    private AsyncHttpClient client = new AsyncHttpClient();

    DataModel model = null;
    Class<DataModel> cls = null;
    ProgressDialog dialog;
   
    boolean showDialog;

    public NetworkHandler(Context context, String modelName,
    RequestParams param, NotifyTasKDone tasKDone, String action, boolean showDialog) {
        this.context = context;
        this.modelName = modelName;
        this.param = param;
        this.tasKDone = tasKDone;
        this.showDialog = showDialog;
        SharedPreferences_Util objShareData = new SharedPreferences_Util(context);
        param.put("app_version", Constants.CURRENT_APP_VERSION(context));
        param.put("device_type", "android");
        param.put("language", "en");
       
    }

    public void getRequest() {
        System.out.println("URLS:= " + Constants.URL + param.toString());
        client.setTimeout(60000);
        client.get(context, Constants.URL, param, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                dialog = new ProgressDialog(context, R.style.Theme_AppCompat_DayNight_Dialog);
                dialog.setMessage("Loading");
                dialog.setCancelable(false);
                if (showDialog)
                    dialog.show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                if (statusCode == 200) {
                    String response = new String(responseBody);
                    System.out.println("Response:= " + response);

                    try {
                        cls = (Class<DataModel>) Class.forName(modelName);

                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    Gson gson = new Gson();
                    // Gson gson = new GsonBuilder().serializeNulls().create();
                    try {

                        model = gson.fromJson(response, cls);
                    } catch (RuntimeException r) {
                        Constants.TimeOutError = "Data is not in Json Format";
                        System.err.println("Data is not in Json Format");
                    }
                    tasKDone.onTaskDone(model);

                } else {
                    Constants.TimeOutError = "Network error";
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Constants.TimeOutError = "Network error";
                tasKDone.onTaskDone(model);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();
            }
        });
    }

    public void postRequest() {

        System.out.println("URLS:= " + Constants.URL + param.toString());

        client.setTimeout(60000);

        client.post(context, Constants.URL, param, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                dialog = new ProgressDialog(context, R.style.Theme_AppCompat_DayNight_Dialog);
                dialog.setMessage("Loading");
                if (showDialog)
                    dialog.show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                if (statusCode == 200) {
                    String response = new String(responseBody);
                    System.out.println("Response:= " + response);

                    try {
                        cls = (Class<DataModel>) Class.forName(modelName);

                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    Gson gson = new Gson();
                    // Gson gson = new GsonBuilder().serializeNulls().create();
                    try {

                            model = gson.fromJson(response, cls);
                    } catch (RuntimeException r) {
                        Constants.TimeOutError = "Data is not in Json Format";
                        System.err.println("Data is not in Json Format");
                    }
                    tasKDone.onTaskDone(model);

                } else {
                    Constants.TimeOutError = "Network error";
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Constants.TimeOutError = "Network error";
                tasKDone.onTaskDone(model);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();
            }
        });
    }


}

Comments

Popular posts from this blog

Crypto JS Encryption & Decryption in Android

ListView Over GoogleMapView

Android Interview Material