Search This Blog

Monday, November 27, 2017

How to use Android Async Http Client || with real example?


How to use  Android Async Http Client?


A popular third-party library called android-async-http helps handle the entire process of sending and parsing network requests for us in a more robust and easy-to-use way.

Setup

Add this library to our app/build.gradle file:
dependencies {
  compile 'com.loopj.android:android-async-http:1.4.9'
}
If you are upgrading from previous versions, you need to change these import statements for the Header class from:
import org.apache.http.Header;
Replaced with this line:
import cz.msebera.android.httpclient.Header;
If you have any other import statements that start with org.apache.http, you also need to change them to cz.msebera.android.httpclient.
Mac users can use the following shortcut:
brew install gnu-sed
find . -name '*.java' -exec gsed -i 's/org.apache.http/cz.msebera.android.httpclient/g' \{\} +

Sending a Network Request

Now, we just create an AsyncHttpClient, and then execute a request specifying an anonymous class as a callback:
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.Header;

AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
client.get("http://www.google.com", params, new TextHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, String res) {
            // called when response HTTP status is "200 OK"
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        } 
    }
);
This will automatically execute the request asynchronously and fire the onSuccess when the response returns a success code and onFailure if the response does not.

Sending a JSON Request

Similar to sending a regular HTTP request, android-async-http can also be used for sending JSON API requests:
String url = "https://ajax.googleapis.com/ajax/services/search/images";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("q", "android");
params.put("rsz", "8");
client.get(url, params, new JsonHttpResponseHandler() {         
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
       // Root JSON in response is an dictionary i.e { "data : [ ... ] }
       // Handle resulting parsed JSON response here
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
       // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }
});
Assuming the callback uses JsonHttpResponseHandler, the request will be sent out with the appropriate parameters passed in the query string and then the response can be parsed as JSON and made available within onSuccess. Check the Converting JSON to Models guide for more details on parsing a JSON response manually.


Below real Example: 

MainActiviy.class

 public class MainActivity extends AppCompatActivity {  
   String URL="https://api.androidhive.info/contacts/";  
   JSONObject object=new JSONObject();  
   ListView listView;  
   ArrayList<Model>alList=new ArrayList<>();  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     listView=findViewById(R.id.listView);  
     apiCall();  
   }  
   public void apiCall() {  
     final ProgressDialog pd=new ProgressDialog(MainActivity.this);  
     AsyncHttpClient client=new AsyncHttpClient();  
     client.get(URL,new JsonHttpResponseHandler(){  
       @Override  
       public void onStart() {  
         super.onStart();  
         pd.setMessage("Loading.....");  
         pd.setTitle("Get Date");  
         pd.show();  
       }  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, JSONObject res) {  
         super.onSuccess(statusCode, headers, res);  
         Toast.makeText(MainActivity.this  
             , "JSON Response get", Toast.LENGTH_SHORT).show();  
         pd.hide();  
         try {  
           JSONArray array=res.getJSONArray("contacts");  
           for (int i=0;i<array.length();i++){  
             Model m=new Model(array.getJSONObject(i).getString("name"),array.getJSONObject(i).getString("email"));  
             alList.add(m);  
             Adapter adapter=new Adapter(MainActivity.this,alList);  
             listView.setAdapter(adapter);  
           }  
         } catch (JSONException e) {  
           e.printStackTrace();  
         }  
       }  
       @Override  
       public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {  
         super.onFailure(statusCode, headers, responseString, throwable);  
         Toast.makeText(MainActivity.this, "Something Wrong :"+statusCode, Toast.LENGTH_SHORT).show();  
         pd.hide();  
       }  
       @Override  
       public void onFinish() {  
         super.onFinish();  
         pd.dismiss();  
       }  
     });  
   }  
 }