Android Volley Example:
Download Complete Android studio Project from here.
You can host Your own Json data(REST,SOAP) online for free from here.
Why Volley:
Usually networks
calls(GET, POST) are made using Apache HTTP
Client either inside AsynchTask or Thread. Even before making the Request, one
have to write numerous lines of code to open connection to the Targeting HTTP.
Which is a burden for programmers.
So What Volley
does is, it removes this particular burden. By default, Every Volley request is
Asynchronous, so there is no need to Create AsyncTask for
Volley Network Calls.
RequestQueue:
Volley allows you to make Multiple Network
calls in parallel, you can also say to volley in which order the request call
have to be made using RequestQueue ordering.
Volley
also allows Image Caching.
About this Tutorial:
In this
tutorial we are going to get the contact information which is in Json format
hosted from Mockable.io. and store the
information inside local array variables(name, phonenumber,email,id).
Later
display the array Values on button click.
Json:
The things you
need to know about Json is
[ - This represent an Jsonarray.
{- This represent an Jsonobject.
A json File may start with Array i.e [ or Object .i.e {, so
your first request call have to be JsonArrayRequest or JsonObjectRequest.
Example 1:
[
{
“name”:”android”
}
]
so Here your Volley network call
should start with JsonArrayRequest.
Example 2:
{
[
“name”:”android”
]
}
For the Second one your Volley
Network call should start with
JsonObjectRequest.
In this tutorial we will use
JsonArrayRequest to create Volley Network call and in response to our call, we
will get the following Json Information as response which is then processed to
get information.
[ { "name": "Mark", "phone number": "1008788666", "emailid": "leonardo@mail.com", "address": "600 Pennsylvania Avenue, Washington DC" }, { "name": "Christian", "phone number": "8007780066", "emailid": "leonardo@mail.com", "address": "11 Wall Street New York" }, { "name": "Benedict", "phone number": "4258781555", "emailid": "leonardo@mail.com", "address": " 350 Fifth Avenue New York, NY" }, { "name": "Bob", "phone number": "4448784444", "emailid": "leonardo@mail.com", "address": "221 B Baker St, London, England" } ]
1. build.gradle:
If you are using Android Studio add the following line as your dependencies inside app gradle folder , if eclipse download the Volley Libaray and add it to your Project.
dependencies {
compile 'com.mcxiaoke.volley:library:1.0.17'
}
2. AndriodManifest.xml:
Specify the Following Permission for the application.
<uses-permission android:name="android.permission.INTERNET"/>
3. activity_main.java:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:id="@+id/getJsonData" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Get Json Data From MockableIo" /> <RelativeLayout android:id="@+id/layout_containing_buttons" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/button_fetch_first_data_from_json" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerHorizontal="true" android:text="Data 1" /> <Button android:id="@+id/button_fetch_second_data_from_json" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_toRightOf="@+id/button_fetch_first_data_from_json" android:text="data 2" /> <Button android:id="@+id/button_fetch_third_data_from_json" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_toRightOf="@+id/button_fetch_second_data_from_json" android:text="data 3" /> <Button android:id="@+id/button_fetch_fourth_data_from_json" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_toRightOf="@+id/button_fetch_third_data_from_json" android:text="data 4" /> </RelativeLayout> <TextView android:id="@+id/heading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginBottom="10dp" android:layout_marginTop="30dp" android:text="Contact Information Retrieved From Json" android:textAllCaps="true" android:textColor="@color/colorPrimaryDark" android:textStyle="bold" /> <TextView android:id="@+id/contact_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:text="Name" android:textAllCaps="true" android:textSize="20dp" android:textStyle="bold" /> <TextView android:id="@+id/contact_number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:text="Phone Number" android:textAllCaps="true" android:textSize="20dp" android:textStyle="bold" /> <TextView android:id="@+id/email_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:text="Email ID" android:textAllCaps="true" android:textSize="20dp" android:textStyle="bold" /> <TextView android:id="@+id/address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp" android:text="Address" android:textAllCaps="true" android:textSize="20dp" android:textStyle="bold" /> </LinearLayout>
4. MainActivity.java:
public class MainActivity extends AppCompatActivity { RequestQueue codexJsonExampleRequestQueue; Button data1,data2,data3,data4,getJsonData; TextView contactName,contactNumber,emailId,addres; JsonArrayRequest jsonArrayRequest; ProgressDialog myProgressDialog; String[] name,phoneNumber,email,address; int arraySizeOfJsonContact; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); data1=(Button)findViewById(R.id.button_fetch_first_data_from_json); data2=(Button)findViewById(R.id.button_fetch_second_data_from_json); data3=(Button)findViewById(R.id.button_fetch_third_data_from_json); data4=(Button)findViewById(R.id.button_fetch_fourth_data_from_json); getJsonData=(Button)findViewById(R.id.getJsonData); contactName=(TextView) findViewById(R.id.contact_name); contactNumber=(TextView)findViewById(R.id.contact_number); emailId=(TextView)findViewById(R.id.email_id); addres=(TextView)findViewById(R.id.address); Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); /*DiskBasedCache provides a *one-file-per-response cache with an in-memory index, * and BasicNetwork provides a network transport based on your preferred HTTP client. * */ Network network = new BasicNetwork(new HurlStack()); /*BasicNetwork is Volley's default network implementation. A BasicNetwork * must be initialized with the HTTP client your app is using to connect to the network. * Typically this is an HttpURLConnection. */ codexJsonExampleRequestQueue=new RequestQueue(cache,network); //Started Representing the Request queue with cache and Network. codexJsonExampleRequestQueue.start(); /*Start the queue, as discussed,network call can be queued and Executed in order, *here we are simply starting it don't have more than one call. */ myProgressDialog=new ProgressDialog(this); getJsonData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myProgressDialog.setMessage("Getting Json Data From Mockable.IO"); myProgressDialog.show(); makeJsonArrayRequest(); } }); data1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { contactName.setText(name[0]); contactNumber.setText(phoneNumber[0]); emailId.setText(email[0]); addres.setText(address[0]); } }); data2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { contactName.setText(name[1]); contactNumber.setText(phoneNumber[1]); emailId.setText(email[1]); addres.setText(address[1]); } }); data3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { contactName.setText(name[2]); contactNumber.setText(phoneNumber[2]); emailId.setText(email[2]); addres.setText(address[2]); } }); data4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { contactName.setText(name[3]); contactNumber.setText(phoneNumber[3]); emailId.setText(email[3]); addres.setText(address[3]); } }); } public void makeJsonArrayRequest() { jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "http://demo5585860.mockable.io/contactdetails", new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_SHORT).show(); arraySizeOfJsonContact=response.length(); //response.length of will return the number of Jsonobject inside the JsonArrray; name=new String[arraySizeOfJsonContact]; phoneNumber=new String[arraySizeOfJsonContact]; email=new String[arraySizeOfJsonContact]; address=new String[arraySizeOfJsonContact]; //allocating Array size for name,phonenumber,email,address. for(int i=0;i<arraySizeOfJsonContact;i++) { try { JSONObject object=response.getJSONObject(i); /*Getting the Object 0,1,2,3 inside JsonArray *{ * "name":"mark" * } * so when .getJsonObject(0),we will mark object , * we can get all the values inside it. * .getJsonObject(1) will give you chrisitian object etc. *i.e.mark,chrisitian,Benedict,Bob contact detail */ name[i]=object.getString("name"); /* * using the Object.getString("Name parameter mentioned in Json") * which is Name */ phoneNumber[i]=object.getString("phone number"); email[i]=object.getString("emailid"); address[i]=object.getString("address"); //so every data is stored into the array. } catch (JSONException e) { } } /*The above for loop will run until all the object is * */ myProgressDialog.dismiss(); codexJsonExampleRequestQueue.stop(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); myProgressDialog.dismiss(); Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show(); } }); codexJsonExampleRequestQueue.add(jsonArrayRequest); } }
This how Volley Network call is made and it response is handled.
Comments
Post a Comment