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();  
       }  
     });  
   }  
 }  

Tuesday, November 14, 2017

CustomList View With JSONobject and Servlet Using Android Asynchronous Http Client | Tutorial 4

Android Side : Create project in android use EmptyActivity.

Visit First Tutorial for Connection Between Server and Android
click here How to Connect Android App with Java Server?

Add Library  in android side >>http://loopj.com/android-async-http/


YouTube Channel :



MainActivity: put below code in your MainActivity.java

MainActivity

 package com.example.aaru.jsonapp;  
 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.widget.ListView;  
 import android.widget.Toast;  
 import com.loopj.android.http.AsyncHttpClient;  
 import com.loopj.android.http.JsonHttpResponseHandler;  
 import org.json.JSONArray;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import java.lang.reflect.Array;  
 import java.util.ArrayList;  
 import cz.msebera.android.httpclient.Header;  
 public class MainActivity extends AppCompatActivity {  
   ListView listView;  
   ArrayList<StudentBeam>allist;  
   AsyncHttpClient asyncHttpClient;  
   String My_URL="http://192.168.43.157:8080/StudentApp/StudentServlet";  
   StudentBeam beam;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     allist=new ArrayList<>();  
     getData();  
     Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();  
     listView= (ListView) findViewById(R.id.listView);  
   }  
   private void getData() {  
     //add asynhttp client lib.....  
     asyncHttpClient=new AsyncHttpClient();  
     asyncHttpClient.get(My_URL,new JsonHttpResponseHandler(){  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, JSONArray response) {  
         super.onSuccess(statusCode, headers, response);  
         for (int i=0;i<response.length(); i++){  
           try {  
             Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();  
             JSONObject object=response.getJSONObject(i);  
             beam=new StudentBeam(object.get("name").toString(),object.get("address").toString(),object.get("phone").toString());  
             //also check json object key  
             Toast.makeText(MainActivity.this, "onSuccess"+beam.getName().toString(), Toast.LENGTH_SHORT).show();  
             allist.add(beam);  
             CustomAdapter adapter=new CustomAdapter(MainActivity.this,allist);  
             listView.setAdapter(adapter);  
           } catch (JSONException e) {  
             e.printStackTrace();  
           }  
         }  
       }  
       @Override  
       public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {  
         super.onFailure(statusCode, headers, throwable, errorResponse);  
         Toast.makeText(MainActivity.this, "onFailed", Toast.LENGTH_SHORT).show();  
       }  
     });  
   }  
 }  

StudentBeam : Create Java class.Put below data (The Student beam is  Add multiple data in array list).

StudentBeam

 package com.example.aaru.jsonapp;  
 /**  
  * Created by Aaru on 10/9/2017.  
  */  
 public class StudentBeam {  
   public String getName() {  
     return Name;  
   }  
   public void setName(String name) {  
     Name = name;  
   }  
   public String getAddress() {  
     return Address;  
   }  
   public void setAddress(String address) {  
     Address = address;  
   }  
   public String getPhone() {  
     return Phone;  
   }  
   public void setPhone(String phone) {  
     Phone = phone;  
   }  
   String Name;  
   String Address;  
   String Phone;  
   public StudentBeam(String Name,String Address,String Phone){  
     this.Name=Name;  
     this.Address=Address;  
     this.Phone=Phone;  
   }  
 }  


CustomAdapter : Create Java Class name is CustomAdapter and extend with BaseAdapter.

CustomAdapter


 package com.example.aaru.jsonapp;  
 import android.content.Context;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.widget.BaseAdapter;  
 import android.widget.TextView;  
 import java.util.ArrayList;  
 /**  
  * Created by Aaru on 10/9/2017.  
  */  
 public class CustomAdapter extends BaseAdapter {  
   ArrayList<StudentBeam> list;  
   Context context;  
   LayoutInflater inflater;  
   public CustomAdapter(Context context,ArrayList<StudentBeam> list){  
     this.list=list;  
     this.context=context;  
     inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
   }  
   @Override  
   public int getCount() {  
     return list.size();  
   }  
   @Override  
   public Object getItem(int position) {  
     return list.get(position);  
   }  
   @Override  
   public long getItemId(int position) {  
     return position;  
   }  
   @Override  
   public View getView(int position, View convertView, ViewGroup parent) {  
     ViewHolder holder=new ViewHolder();  
     if (convertView==null) {  
       convertView = inflater.inflate(R.layout.raw, null);  
       holder.name= (TextView) convertView.findViewById(R.id.txtName);  
       holder.Address= (TextView) convertView.findViewById(R.id.txtAddress);  
       holder.Phone= (TextView) convertView.findViewById(R.id.txtPhone);  
       convertView.setTag(holder);  
       holder.name.setText(list.get(position).getName());  
       holder.Address.setText(list.get(position).getAddress());  
       holder.Phone.setText(list.get(position).getPhone());  
     }else {  
       holder= (ViewHolder) convertView.getTag();  
     }  
     return convertView;  
   }  
   private class ViewHolder{  
     TextView name;  
     TextView Address;  
     TextView Phone;  
   }  
 }  

>>>>>>>>>>>>>>>>>>>Run App and Enjoy<<<<<<<<<<<<<<<<<<<<<
 >>>>>>>>>>>>>>>>>>>Also Comment below<<<<<<<<<<<<<<<<<<<<<



CustomListView with JSONobject ,Servlet Using Android Asynchronous Http Client | Tutorial 3

Server Side : Open Eclipse indigo and create dynamic app.

⇒Create dynamic app>>StudentApp
⇒Create JAVA class Name is DBConnection and put below data (below code is connection between database and java).

Youtube Channel :



DBConnection


 import java.sql.Connection;  
 import java.sql.DriverManager;  
 /**  
  *  
  * @author Aaru     
  */  
 public class DBConnectiion {  
     String Driver="com.mysql.jdbc.Driver";//this is mysql driver class path  
     String SQL="select Name,Address,Phone from college.Student";//this my sql query for get data from database  
     String URL="jdbc:mysql://localhost:3306";//this my sql url for database connection..  
     String USER="root"; //this is my database connection username and password  
     String PASS="root";  
 }  


Create a JAVA class name is   StudentBeam   the class is use for store multiple data in array.

StudentBeam


 /*  
  * To change this license header, choose License Headers in Project Properties.  
  * To change this template file, choose Tools | Templates  
  * and open the template in the editor.  
  */  
 /**  
  *  
  * @author Aaru  
  */  
 public class Studentbeam {  
   private String Name;  
   private String Address;  
   private String phone;  
   public String getName() {  
     return Name;  
   }  
   public void setName(String Name) {  
     this.Name = Name;  
   }  
   public String getAddress() {  
     return Address;  
   }  
   public void setAddress(String Address) {  
     this.Address = Address;  
   }  
   public String getPhone() {  
     return phone;  
   }  
   public void setPhone(String phone) {  
     this.phone = phone;  
   }  
 }  



Create a JavaServlet name is StudentServlet and create a java Class name is StudentImp
put below code in StudentImp.java



StudentImp


 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 import java.sql.Statement;  
 import java.util.ArrayList;  
 import java.util.logging.Level;  
 import java.util.logging.Logger;  
 /*  
  * To change this license header, choose License Headers in Project Properties.  
  * To change this template file, choose Tools | Templates  
  * and open the template in the editor.  
  */  
 /**  
  *  
  * @author Aaru  
  */  
 public class StudentImp {  
   DBConnectiion DB=new DBConnectiion();  
   Connection con;  
   Statement stmt;  
   ArrayList<Studentbeam>alStd=new ArrayList<>();  
   public ArrayList<Studentbeam> getData(){  
     try {  
       Class.forName(DB.Driver);  
       con=DriverManager.getConnection(DB.URL, DB.USER, DB.PASS);  
      stmt= con.createStatement();  
       ResultSet rs= stmt.executeQuery(DB.SQL);  
       while (rs.next()) {  
         Studentbeam s=new Studentbeam();  
         s.setName(rs.getString("Name"));  
         s.setAddress(rs.getString("Address"));  
         s.setPhone(rs.getString("Phone"));  
         alStd.add(s);  
         System.out.println("add data success in array");  
       }  
     } catch (ClassNotFoundException ex) {  
       Logger.getLogger(StudentImp.class.getName()).log(Level.SEVERE, null, ex);  
     } catch (SQLException ex) {  
       Logger.getLogger(StudentImp.class.getName()).log(Level.SEVERE, null, ex);  
     }  
     return alStd;  
     //Now App run success  
     //lets Connect with android app using ip address  
   }  
 }  




put below code in StudentServlet

StudentServlet


 /*  
  * To change this license header, choose License Headers in Project Properties.  
  * To change this template file, choose Tools | Templates  
  * and open the template in the editor.  
  */  
 import java.io.IOException;  
 import java.io.PrintWriter;  
 import java.util.ArrayList;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import org.json.JSONArray;  
 /**  
  *  
  * @author Aaru  
  */  
 public class StudentServlet extends HttpServlet {  
   @Override  
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
     //b'coz we use get method android side..  
     StudentImp imp=new StudentImp();  
     ArrayList<Studentbeam>alstd= imp.getData();  
     if (alstd!=null) {  
       JSONArray array=new JSONArray(alstd);  
       PrintWriter pw= resp.getWriter();  
       pw.write(array.toString());  
       pw.print(array.toString());  
       //everting is done let' run  
     }  
   }  
 }  


⇓find web.xml in project directory  and put below code)XML


 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
   <servlet>  
     <servlet-name>StudentServlet</servlet-name>  
     <servlet-class>StudentServlet</servlet-class>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>StudentServlet</servlet-name>  
     <url-pattern>/StudentServlet</url-pattern>  
   </servlet-mapping>  
 </web-app>  


Run App as Server(Apache Tomcat or Other)

Server Side Is Done click Next For android side Coding