THIS CONTENT DOWNLOAD SHORTLY

Objective

JSON is the best alternative to XML for storing data in files. It is easy to parse and access data stored in JSON format.

 

You will get Final Output:

  • login
  • contacts
  • contact-details

 

 

Step 1 Understanding JSON Response

 

1.1 What is JSON?

  • JSON is acronym of JavaScript Object Notation.
  • JSON is a lightweight data-interchange format.
  • JSON is language independent.
  • JSON is self-describing and easy to understand.

JSON uses JavaScript syntax, but the JSON format is text only, just like XML. Text can be read and used as a data format by any programming language.

 

1.2 Difference between XML / JSON?

  • XML and JSON both are the data interchange formats.
  • Both of these formats have their own advantages/disadvantages.
  • Talking about which one is better, is something related to the applications/requirements and the collaboration between client and server.
  • Selection and strength of data interchange media types, is application specific.

Below i have given a summary of each format.

 

1.2.1 XML

  • An open standard for describing data defined by the World Wide Web Consortium (W3C).
  • XML lets Web developers and designers create customized tags that offer greater flexibility in organizing and presenting information.
  • XML defines rules to mark-up a document in a way that allows the author to express semantic meaning in the mark-up.
  • XML does not necessarily restrict the author to certain tags (element) as HTML does.
  • Internet media type: application/xml.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<Payload>   
      <element>
         <FirstName>Nikunj</FirstName>
         <LastName>Popat</LastName>
         <DOB>1991-04-05</DOB>
        <Address> Ramdev Pir Chowkdi, Rajkot </Address>

         <Avatar>http://theappguruz.in/php/demojson/application/upload/users/68-niks.jpg</Avatar>         
         <Phone>
            <Home>00 000000</Home>
            <Mobile>+91 9426842981</Mobile>
            <Office>00 000000</Office>
         </Phone>
      </element>
      <element>
         <FirstName>Parimal</FirstName>
         <LastName>Gotecha</LastName>
         <DOB>1987-12-14</DOB>
         <Address> Shiv Park, Rajkot </Address>
         <Avatar>http://theappguruz.in/php/DemoJSON/application/upload/users/51-20131216_092921_1.jpg</Avatar>         
         <Phone>
            <Home>00 000000</Home>
            <Mobile>+91 0000000000</Mobile>
            <Office>00 000000</Office>
         </Phone>   
</Payload>

Here, <Playload> is parent/root element.

 

1.2.2 JSON

  • A lightweight text-based open standard designed for human-readable data interchange.
  • A text-based format for exchanging objects.
  • It is an alternative to XML that is more concise because, unlike XML, it is not a mark-up language that requires open and close tags.
  • It is derived from the object literals of JavaScript.
  • Design goals were for it to be minimal, portable, textual, and a subset of JavaScript.
  • Internet media type: application/JSON.
Challenge: Can I read data in any other format apart from XML/ JSON for mobile?
 

1.3 Type of data in JSON response

Two types of brackets you should be looking for while interpreting JSON response:

{ } The elements which directly fall under curly braces are JSON Objects.
[ ] The elements which fall under square brackets are elements of JSON Array.

Example:

{
    "Payload": [
        {
                "FirstName": "Nikunj",
                "LastName": "Popat",
                "DOB": "1991-04-05",
                "Address": "Ramdev Pir Chowkdi, Rajkot",
		 "Avatar": "http://theappguruz.in/php/DemoJSON/application/upload/users/68-NIKs.jpg"
                "Phone": {
                    "Mobile": "+91 9426842981",
                    "Home": "00 000000",
                    "Office": "00 000000"
                }
        },
        
        {
                "FirstName": "Parimal",
                "LastName": "Gotecha",
                "DOB": "1987-12-14",
                "Address": "Shiv Park, Rajkot",
                "Avatar" : "http://theappguruz.in/php/DemoJSON/application/upload/users/51-20131216_092921_1.jpg",
                "Phone": {
                    "Mobile": "+91 0000000000",
                    "Home": "00 000000",
                    "Office": "00 000000"
                }
        }
    ]
}

In the example above Payload parent JSON Object.

The Payload Object has two array elements, each for different contact details. And each of the sub-elements contains following JSON objects.

  • FirstName
  • LastName
  • DOB
  • Address
  • Avatar
  • Phone
    >> Mobile
    >> Home
    >> Office

And as you can see the Element Phone has got three JSON objects called Mobile, Home and Office. Now, since we have understood the basic structure of JSON response, let’s get started with JSON parsing.

 

Step 2 Create Model class for the JSON response

Here, I have created a ContactModel class, In ContactModel class I have taken all the variables and it’s get-set methods that are in JSON response.

package com.example.theappguruz.jsonparsingdemoandroid.model;

import java.io.Serializable;

public class ContactModel implements Serializable {

    private String firstName;
    private String lastName;
    private String DOB;
    private String avatar;

    private String address;
    private String phone;
    private String mobile;
    private String home;
    private String office;

    public String getDOB() {
        return DOB;
    }
    public void setDOB(String DOB) {
        this.DOB = DOB;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }



    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }


    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

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

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getOffice() {
        return office;
    }

    public void setOffice(String office) {
        this.office = office;
    }
}

ContactModel class implements Serializable interface because in future we will pass ContactModel class object through intent.

 

Step 3 Create constants file

Declare URL and all the other TAGs in Constans file used in JSON parsing.

package com.example.theappguruz.jsonparsingdemoandroid.constant;

public class Constants {
    public static String URL_CONTACTS = "http://theappguruz.in/php/DemoJSON/api/user/contacts";
    public static String URL_LOGIN = "http://theappguruz.in/php/DemoJSON/api/user/login";

    public static final String TAG_MESSAGE = "Message";
    public static final String TAG_USERNAME = "Username";
    public static final String TAG_PASSWORD = "Password";

    public static final String TAG_PAYLOAD = "Payload";
    public static final String TAG_FIRST_NAME = "FirstName";
    public static final String TAG_LAST_NAME = "LastName";
    public static final String TAG_DOB = "DOB";
    public static final String TAG_ADDRESS = "Address";
    public static final String TAG_AVATAR = "Avatar";
    public static final String TAG_PHONE = "Phone";
    public static final String TAG_PHONE_MOBILE = "Mobile";
    public static final String TAG_PHONE_HOME = "Home";
    public static final String TAG_PHONE_OFFICE = "Office";
    public static final int TIMEOUT_IN_MS = 90000;
}
 

Step 4 Import volley library

For getting data from API and JSON parsing we are using Volley library. Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.

>> Volley is available through the open AOSP Repository:

>> Unofficial git clone for volley:

 

4.1 Import volley library in the Android Studio project:

  1. Open Android Studio Project.
  2. Go To File >> New >> Import Module
  3. Now in the source directory select your volley library package that you had download.
  4. Click on finish and wait for complete the gradle process.
 

Step 5 Layout Files

Here, are some layout files that we have made for our project.

 

5.1 login.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/backgound_color"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="bottom"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal" >            

            <TextView
                android:id="@+id/tvLoginTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/login_title"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/app_color"
                android:textSize="@dimen/login_header" />            
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="@dimen/et_pad" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:gravity="center"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="@dimen/layout_pad" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:padding="@dimen/layout_pad" >

                    <EditText
                        android:id="@+id/etLoginUserName"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@drawable/edt_corner"
                        android:ems="10"
                        android:hint="@string/enter_username"
                        android:inputType="textEmailAddress"
                        android:padding="@dimen/et_pad"
                        android:textColorHint="@color/hint_color" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:padding="@dimen/layout_pad" >

                    <EditText
                        android:id="@+id/etLoginPassword"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@drawable/edt_corner"
                        android:ems="10"
                        android:hint="@string/enter_password"
                        android:inputType="textPassword"
                        android:padding="@dimen/et_pad"
                        android:textColorHint="@color/hint_color" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:padding="@dimen/layout_pad" >

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1" >
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="2"
                        android:gravity="center"
                        android:orientation="vertical"
                        android:padding="@dimen/layout_pad" >

                        <Button
                            android:id="@+id/btnLogin"
                            style="@style/Button_style"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:background="@drawable/btn_login"
                            android:text="@string/btn_login" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="vertical" >
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>

Our first screen will be login screen.

 

5.2 activity_main.xml file

active_main.xml file will be used to display contact list which we are fetching using API.

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <ScrollView
        android:id="@+id/scrollViewDisplay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/layoutDisplayPeople"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">


                <LinearLayout
                    android:id="@+id/parentLayout"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"></LinearLayout>


            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</LinearLayout>
 

5.3 inflate_contact.xml file.

This layout will inflate into the activity_main.xml ’s Scroll View. This listings contacts.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <com.rey.material.widget.LinearLayout
        android:id="@+id/inflateParentView"
        style="@style/FlatWaveButtonRippleStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        >

        <com.rey.material.widget.TextView

            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:layout_marginTop="15dp"
            android:layout_marginLeft="15dp"
            android:layout_weight="1"
            android:text="Name"
            android:textSize="15sp"
            android:gravity="left"

            android:textColor="@color/color_black"
            android:textStyle="bold"
            />
    </com.rey.material.widget.LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="@color/color_grey">
    </LinearLayout>
</LinearLayout>
 

5.4 contact_detail_layout.xml file

contact_detail_layout.xml is the contact detail file that shows the full contact detail.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"               >

                <ImageView
                    android:id="@+id/ivContactImage"
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_white"
                android:gravity="center">

                <TextView
                    android:id="@+id/tvContactDetailNameHeading"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="First Name"
                    android:textColor="#000000" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@color/color_grey"></LinearLayout>

                <TextView

                    android:id="@+id/tvContactDetailName"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"

                    android:text="Nikunj "
                    android:textColor="#000000" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_white"
                android:gravity="center">

                <TextView
                    android:id="@+id/tvContactDetailLastNameHeading"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="Last Name"
                    android:textColor="#000000" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@color/color_grey"></LinearLayout>

                <TextView

                    android:id="@+id/tvContactDetailLastName"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"

                    android:text="Popat"
                    android:textColor="#000000" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_white"
                android:gravity="center">

                <TextView
                    android:id="@+id/tvContactDetailDOBHeading"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="DOB"
                    android:textColor="#000000" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@color/color_grey"></LinearLayout>

                <TextView

                    android:id="@+id/tvContactDetailDOB"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"

                    android:text="1991-04-05"
                    android:textColor="#000000" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_white"
                android:gravity="center">

                <TextView
                    android:id="@+id/tvcontactDetailAddressHeading"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="Address"
                    android:textColor="#000000" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@color/color_grey"></LinearLayout>

                <TextView

                    android:id="@+id/tvcontactDetailAddress"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"

                    android:text="Shivam Park Main Road Rajkot"
                    android:textColor="#000000" />
            </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_white"
                android:gravity="center">


                <TextView

                    android:id="@+id/tvcontactDetailPhoneHeading"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"

                    android:text="Phone"
                    android:textColor="#000000" />
            </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_white"
                android:gravity="center">

                <TextView
                    android:id="@+id/tvcontactDetailMobileHeading"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="Mobile"
                    android:textColor="#000000" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@color/color_grey"></LinearLayout>

                <TextView

                    android:id="@+id/tvcontactDetailMobile"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"

                    android:text="942684291"
                    android:textColor="#000000" />
            </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_white"
                android:gravity="center">

                <TextView
                    android:id="@+id/tvcontactDetailHomeHeading"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="Home"
                    android:textColor="#000000" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@color/color_grey"></LinearLayout>

                <TextView

                    android:id="@+id/tvcontactDetailHome"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"

                    android:text="000 000 00"
                    android:textColor="#000000" />
            </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_white"
                android:gravity="center">

                <TextView
                    android:id="@+id/tvcontactDetailOfficeHeading"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="Office"
                    android:textColor="#000000" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@color/color_grey"></LinearLayout>

                <TextView

                    android:id="@+id/tvcontactDetailOffice"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="15dp"
                    android:layout_weight="1"
                    android:background="@null"
                    android:gravity="center"

                    android:text="00 000 000"
                    android:textColor="#000000" />
            </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/color_grey"></LinearLayout>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Now, let’s move towards the java file.

 

Step 6 LoginActivity.java file

Our first page of the demo is Login page. It is used for authenticate the user. To use Volley, you must add the android.permission.INTERNET permission to your AndroidManifest file. Without this, your app won't be able to connect to the network.

package com.example.theappguruz.jsonparsingdemoandroid.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.theappguruz.jsonparsingdemoandroid.R;
import com.example.theappguruz.jsonparsingdemoandroid.constant.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends Activity {
    EditText etLoginUserName;
    EditText etLoginPassword;
    Button btnLogin;
    private ProgressDialog progressDialog;

    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (progressDialog != null && progressDialog.isShowing())
                progressDialog.dismiss();

            if (msg.what == 1) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            } else if (msg.what == 2) {
                Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
            } else if (msg.what == 3) {

            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        getAllWidgets();
    }

    private void getAllWidgets() {
        btnLogin = (Button) findViewById(R.id.btnLogin);
        etLoginUserName = (EditText) findViewById(R.id.etLoginUserName);
        etLoginPassword = (EditText) findViewById(R.id.etLoginPassword);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etLoginPassword.getText().toString().equals("") || etLoginUserName.getText().toString().equals("")) {
                    Toast.makeText(getApplicationContext(), "Please Enter Username and Password Both", Toast.LENGTH_LONG).show();
                } else {
                    onLogin();
                }
            }
        });
    }

    private void onLogin() {
        progressDialog = ProgressDialog
                .show(this, "", getString(R.string.loading));
        final StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_LOGIN, new Response.Listener<String>() {
            @Override
            public void onResponse(final String response) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.get(Constants.TAG_MESSAGE).equals("Success")) {
                                handler.sendEmptyMessage(1);
                            } else {
                                handler.sendEmptyMessage(2);
                            }
                        } catch (JSONException e) {
                            handler.sendEmptyMessage(3);
                            e.printStackTrace();
                        } catch (NullPointerException e) {
                            handler.sendEmptyMessage(4);
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(Constants.TAG_USERNAME, etLoginUserName.getText().toString());
                params.put(Constants.TAG_PASSWORD, etLoginPassword.getText().toString());
                return params;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                Constants.TIMEOUT_IN_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        Volley.newRequestQueue(this).add(stringRequest);
    }
}

You need:

Username admin
Password admin

Now let’s understand important methods/responses of LoginActivity class.

>> What is Handler?

  • A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.
  • Each Handler instance is associated with a single thread and that thread's message queue.
  • When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it from that point on, it will deliver messages and runnable to that message queue and execute them as they come out of the message queue.
private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (progressDialog != null && progressDialog.isShowing())
                progressDialog.dismiss();

            if (msg.what == 1) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            } else if (msg.what == 2) {
                Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
            } else if (msg.what == 3) {

            }
            return false;
        }
});

>> To know more about Handler please refers following link:

>> onLogin(): Here, I have created a thread to complete Login Procedure after getting Username and Password.

private void onLogin() {
        progressDialog = ProgressDialog
                .show(this, "", getString(R.string.loading));
final StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_LOGIN, new Response.Listener<String>() {
            @Override
            public void onResponse(final String response) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.get(Constants.TAG_MESSAGE).equals("Success")) {
                                handler.sendEmptyMessage(1);
                            } else {
                                handler.sendEmptyMessage(2);
                            }
                        } catch (JSONException e) {
                            handler.sendEmptyMessage(3);
                            e.printStackTrace();
                        } catch (NullPointerException e) {
                            handler.sendEmptyMessage(4);
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(Constants.TAG_USERNAME, etLoginUserName.getText().toString());
                params.put(Constants.TAG_PASSWORD, etLoginPassword.getText().toString());
                return params;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                Constants.TIMEOUT_IN_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        Volley.newRequestQueue(this).add(stringRequest);
    }

>> StringRequest: A canned request for retrieving the response body at a given URL as a String.

StringRequest Class Syantax :

public StringRequest(int method,
                     String url,
                     Response.Listener <String> listener,
                     Response.ErrorListener errorListener)
method The request method to use (GET/POST)
url URL to fetch the string
listener Listener to receive the String response
errorListener Error listener, or null to ignore errors Sending a Simple Request
Volley.newRequestQueue(this).add(stringRequest);

At a high level, you use Volley by creating a RequestQueue and passing it Request objects. The RequestQueue manages worker threads for running the network operations, reading from and writing to the cache, and parsing responses. Requests do the parsing of raw responses and Volley takes care of dispatching the parsed response back to the main thread for delivery.

>> To know more about send request please refer:

 

Step 7 MainActivity.java file

This file is used to send a request to server to fetch the data from database and it will get all the records in the response and it will display all the records (response) to the user.

package com.example.theappguruz.jsonparsingdemoandroid.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.theappguruz.jsonparsingdemoandroid.constant.Constants;
import com.example.theappguruz.jsonparsingdemoandroid.model.ContactModel;
import com.example.theappguruz.jsonparsingdemoandroid.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class MainActivity extends ActionBarActivity {

    private ProgressDialog progressDialog;
    android.widget.LinearLayout parentLayout;

    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (progressDialog != null && progressDialog.isShowing())
                progressDialog.dismiss();

            if (msg.what == 1) {
                displayContactList();
            } else if (msg.what == 2) {
                Toast.makeText(getApplicationContext(),"JSON Error",Toast.LENGTH_LONG);
            } else {
                Toast.makeText(getApplicationContext(),"Null Pointer Exception",Toast.LENGTH_LONG);
            }
            return false;
        }
    });
    ArrayList<ContactModel> jsonContacts = new ArrayList<ContactModel>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        parentLayout = (LinearLayout) findViewById(R.id.parentLayout);
        callContactAPI();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void callContactAPI() {
        progressDialog = ProgressDialog
                .show(this, "", getString(R.string.loading));

        Log.d("JSON", "ContactAPI");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.URL_CONTACTS, new Response.Listener<String>() {
            @Override
            public void onResponse(final String responseString) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(responseString);
                            Log.d("JSON", "JSON");
                            if (jsonObject.has(Constants.TAG_PAYLOAD)) {
                                JSONArray contacts = jsonObject.getJSONArray(Constants.TAG_PAYLOAD);

                                for (int i = 0; i < contacts.length(); i++) {
                                    JSONObject contact = contacts.getJSONObject(i);
                                    ContactModel contactModel = new ContactModel();
                                    contactModel.setAddress(contact.getString(Constants.TAG_ADDRESS));
                                    contactModel.setFirstName(contact.getString(Constants.TAG_FIRST_NAME));
                                    contactModel.setLastName(contact.getString(Constants.TAG_LAST_NAME));
                                    contactModel.setDOB(contact.getString(Constants.TAG_DOB));

                                    contactModel.setAvatar(contact.getString(Constants.TAG_AVATAR));

                                    JSONObject phoneObject = contact.getJSONObject(Constants.TAG_PHONE);
                                    contactModel.setMobile(phoneObject.getString(Constants.TAG_PHONE_MOBILE));
                                    contactModel.setHome(phoneObject.getString(Constants.TAG_PHONE_HOME));
                                    contactModel.setOffice(phoneObject.getString(Constants.TAG_PHONE_OFFICE));

                                    jsonContacts.add(contactModel);
                                }
                            }
                            handler.sendEmptyMessage(1);
                        } catch (JSONException e) {
                            handler.sendEmptyMessage(2);
                            e.printStackTrace();
                        } catch (NullPointerException e) {
                            handler.sendEmptyMessage(3);
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                Log.d("JSON", "getParams");
                // params.put("Contacts", "Contacts");
                return params;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                Constants.TIMEOUT_IN_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        Volley.newRequestQueue(this).add(stringRequest);
    }

    private void displayContactList() {
        for (int i = 0; i < jsonContacts.size(); i++) {
            final ContactModel contactModel = jsonContacts.get(i);
            Holder holder = new Holder();
            View view = LayoutInflater.from(this).inflate(R.layout.inflate_contact, null);
            final com.rey.material.widget.LinearLayout inflateParentView = (com.rey.material.widget.LinearLayout) view.findViewById(R.id.inflateParentView);
            holder.tvName = (TextView) view.findViewById(R.id.tvName);
            view.setTag(i);
            holder.tvName.setText(contactModel.getFirstName());

            inflateParentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, ContactDetailActivity.class);
                    intent.putExtra("ContactDetail", contactModel);
                    startActivity(intent);

                }
            });
            parentLayout.addView(view);
        }
    }

    private class Holder {
        TextView tvName;
    }
}

 

 

Step 8 ContactDetailActivity.java file

This activity is called when user (Clicks on any contact) want to know all the details of the specific contact.

package com.example.theappguruz.jsonparsingdemoandroid.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.theappguruz.jsonparsingdemoandroid.R;
import com.example.theappguruz.jsonparsingdemoandroid.model.ContactModel;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;


public class ContactDetailActivity extends Activity {
    ContactModel contactDetail;
    TextView tvFirstName;
    TextView tvLastName;
    TextView tvAddress;

    TextView tvMobileNumber;
    TextView tvHomePhoneNumber;
    TextView tvOfficePhoneNumber;
    TextView tvDOB;

    private ProgressDialog progressDialog;
    ImageView ivContactImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_detail_layout);
        getAllWidgets();
        contactDetail = getContactDetail();

        setContactDetail();
    }

    private void getAllWidgets() {
        tvAddress = (TextView) findViewById(R.id.tvcontactDetailAddress);
        tvFirstName = (TextView) findViewById(R.id.tvContactDetailName);
        tvLastName = (TextView) findViewById(R.id.tvContactDetailLastName);
        tvHomePhoneNumber = (TextView) findViewById(R.id.tvcontactDetailHome);
        tvMobileNumber = (TextView) findViewById(R.id.tvcontactDetailMobile);
        tvOfficePhoneNumber = (TextView) findViewById(R.id.tvcontactDetailOffice);
        ivContactImage = (ImageView) findViewById(R.id.ivContactImage);
        tvDOB = (TextView) findViewById(R.id.tvContactDetailDOB);
    }

    private ContactModel getContactDetail() {
        ContactModel contactDetails = (ContactModel) getIntent().getSerializableExtra("ContactDetail");
        return contactDetails;
    }

    private void setContactDetail() {
        tvAddress.setText(contactDetail.getAddress());
        tvFirstName.setText(contactDetail.getFirstName());
        tvOfficePhoneNumber.setText(contactDetail.getOffice());
        tvMobileNumber.setText(contactDetail.getMobile());
        tvHomePhoneNumber.setText(contactDetail.getHome());
        tvLastName.setText(contactDetail.getLastName());
        tvDOB.setText(contactDetail.getDOB());
        Log.d("Path", contactDetail.getAvatar());
        progressDialog = ProgressDialog
                .show(this, "", getString(R.string.loading));
        Picasso.with(this).load(contactDetail.getAvatar()).resize(200, 200).into(ivContactImage, new Callback() {
            @Override
            public void onSuccess() {
                if (progressDialog != null && progressDialog.isShowing())
                    progressDialog.dismiss();
            }

            @Override
            public void onError() {

            }
        });
    }
}

I hope you enjoy this tutorial and it would be helpful to you.

Got an Idea of Android App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Android App Development Company in India.

An entrepreneur who has founded 2 flourishing software firms in 7 years, Tejas is keen to understand everything about gaming - from the business dynamics to awesome designs to gamer psychology. As the founder-CEO of a company that has released some very successful games, he knows a thing or two about gaming. He shares his knowledge through blogs and talks that he gets invited to.

face mask Belial The Demon Headgear Pocket Staff Magic