Friday 5 May 2017

How to Implement Google Place API  in Android Studio.

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project.

compile 'com.google.android.gms:play-services:8.4.0'

Create Xml file in project.
Open => app => res => layout - activity_main.xml.

<?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:gravity="center"
    android:orientation="vertical"
    android:padding="24dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/icons"
        android:elevation="2dp"
        android:orientation="vertical"
        android:padding="8dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_from"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/edtFrom"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:editable="false"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:hint="From" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_to"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp">

            <EditText
                android:id="@+id/edtTo"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:editable="false"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:hint="To" />
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

    <Button
        android:id="@+id/find"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Find Now"
        android:textColor="@color/icons" />
</LinearLayout>



Create the Java file in project.
Open app => main => src =
FragmentFind.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.conn.findroute.R;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;


public class FragmentFind extends Fragment {

    Button mFind;
    EditText mFrom, mTo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bus, container, false);

        init(view);
        eventListener();

        return view;
    }

    /*
    * Initialize UI elements
    * */
    void init(View v) {


        mFind = (Button) v.findViewById(R.id.find);
        mFrom = (EditText) v.findViewById(R.id.edtFrom);
        mTo = (EditText) v.findViewById(R.id.edtTo);
    }

    /*
    * Click event handler
    * */
    private void eventListener() {


        mFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Snackbar.make(v, "Coming Soon", Snackbar.LENGTH_LONG).show();
                Intent in = new Intent(getActivity(), RouteListActivity.class);
                startActivity(in);
            }
        });

        mFrom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent =
                            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                    .build(getActivity());
                    startActivityForResult(intent, 1);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO: Handle the error.
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO: Handle the error.
                }
            }
        });

        mTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent =
                            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                    .build(getActivity());
                    startActivityForResult(intent, 2);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO: Handle the error.
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO: Handle the error.
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == getActivity().RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(getActivity(), data);
                Log.i("FIND", "Place: " + place.getName());
                mFrom.setText(place.getName());
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(getActivity(), data);
                // TODO: Handle the error.
                Log.i("MAP", status.getStatusMessage());

            } else if (resultCode == getActivity().RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
        if (requestCode == 2) {
            if (resultCode == getActivity().RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(getActivity(), data);
                Log.i("FIND", "Place: " + place.getName());
                mTo.setText(place.getName());
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(getActivity(), data);
                // TODO: Handle the error.
                Log.i("MAP", status.getStatusMessage());

            } else if (resultCode == getActivity().RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
    }
}


Add Internet permission in your manifest.

<uses-permission android:name="android.permission.INTERNET" />
 <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="key"/>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true"/>

Wednesday 3 May 2017

 JSON Parsing in array with Retrofit in Android Studio.

[
    {
        "Id":"101",
        "Name":"Arun",
        "Marks":"112"
    },
  
    {
        "Id":"102",
        "Name":"Kamal",
        "Marks":"116"
    },
   
]


Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.


First we need to add Library to our project.

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.google.code.gson:gson:1.7.2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp:okhttp:2.4.0'




Create Xml file in project.
Open => app => res => layout - activity_main.xml.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txtIdOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp" />

    <TextView
        android:id="@+id/txtIdTwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="300dp" />

    <TextView
        android:id="@+id/txtNameOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="120dp" />

    <TextView
        android:id="@+id/txtNameTwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="270dp" />

    <TextView
        android:id="@+id/txtMarkOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="240dp" />

    <TextView
        android:id="@+id/txtMarkTwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="90dp" />

</RelativeLayout>



Create the Java file in project.
Open app => main => src = MainActivity.java



import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import java.util.List;

import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends AppCompatActivity {

    String url = "http://www.androidtutorialpoint.com/";
    TextView idOneTextView, nameOneTextView, markOneTextView;
    TextView idTwoTextView, nameTwoTextView, markTwoTextView;

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


        idOneTextView = (TextView) findViewById(R.id.txtIdOne);
        nameOneTextView = (TextView) findViewById(R.id.txtNameOne);
        markOneTextView = (TextView) findViewById(R.id.txtMarkOne);

        idTwoTextView = (TextView) findViewById(R.id.txtIdTwo);
        nameTwoTextView = (TextView) findViewById(R.id.txtNameTwo);
        markTwoTextView = (TextView) findViewById(R.id.txtMarkTwo);

        //Getting the Data here....
        getRetrofitArray();


    }

    void getRetrofitArray() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);

        Call<List<Student>> call = service.getStudentDetails();

        call.enqueue(new Callback<List<Student>>() {
            @Override
            public void onResponse(Response<List<Student>> response, Retrofit retrofit) {

                try {

                    List<Student> StudentData = response.body();

                    for (int i = 0; i < StudentData.size(); i++) {

                        if (i == 0) {
                            idOneTextView.setText("Id  :  " + StudentData.get(i).getStudentId());
                            nameOneTextView.setText("Name  :  " + StudentData.get(i).getStudentName());
                            markOneTextView.setText("Marks  : " + StudentData.get(i).getStudentMarks());
                        } else if (i == 1) {
                            idTwoTextView.setText("Id  :  " + StudentData.get(i).getStudentId());
                            nameTwoTextView.setText("Name  :  " + StudentData.get(i).getStudentName());
                            markTwoTextView.setText("Marks  : " + StudentData.get(i).getStudentMarks());
                        }
                    }


                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("onFailure", t.toString());
            }
        });
    }


}


Create the Java file in project.
Open app => main => src = RetrofitArrayAPI.java


import java.util.List;
import retrofit.Call;
import retrofit.http.GET;

/**
 * Created by Saify on 5/3/2017.
 **/

public interface RetrofitArrayAPI {

    /*
     * Retrofit get annotation with our URL
     * And our method that will return us details of student.
    */
    @GET("api/RetrofitAndroidArrayResponse")
    Call<List<Student>> getStudentDetails();

}


Create the Java file in project.
Open app => main => src = Student.java


/**
 * Created by Saify on 5/3/2017.
 **/

public class Student {
    //Variables that are in our json
    private int StudentId;
    private String StudentName;
    private String StudentMarks;

    //Getters and setters
    public int getStudentId() {
        return StudentId;
    }

    public void setStudentId(int bookId) {
        this.StudentId = StudentId;
    }

    public String getStudentName() {
        return StudentName;
    }

    public void setStudentName(String name) {
        this.StudentName = StudentName;
    }

    public String getStudentMarks() {
        return StudentMarks;
    }

    public void setStudentMarks(String price) {
        this.StudentMarks = StudentMarks;
    }
}


Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
JSON Parsing with Retrofit in Android Studio.

Json Format:- http://api.androidhive.info/contacts/
{
    "contacts": [
        {
                "id": "c200",
                "name": "Ravi Tamada",
                "email": "ravi@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        }
        ]
}


Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project.
  compile 'com.google.code.gson:gson:2.6.2'
  compile 'com.squareup.retrofit2:retrofit:2.1.0'
  compile 'com.squareup.retrofit2:converter-gson:2.1.0'
  compile 'com.android.support:recyclerview-v7:25.1.0'
  compile 'com.jakewharton:butterknife:8.4.0'
  compile 'com.squareup.okhttp3:logging-interceptor:3.4.2'
  compile 'com.google.dagger:dagger:2.4'
  compile 'com.squareup.okhttp3:okhttp:3.5.0'


Create Xml file in project. 
Open => app => res => layout - activity_main.xml.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="co.apidemos.activity.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerView"
        android:scrollbars="vertical"
        ></android.support.v7.widget.RecyclerView>
    <TextView
        android:id="@+id/emptyTextView"
        android:layout_width="wrap_content"
        android:text="@string/empty_string"
        android:layout_centerInParent="true"
        android:textSize="30sp"
        android:visibility="gone"
        android:layout_height="wrap_content" />
</RelativeLayout>



Create Xml file in project. 
Open => app => res => layout - list_item.xml.


package co.apidemos.adapter;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/userLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fff"
    android:orientation="vertical">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="12dp">

    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_vertical_margin"
        android:text="" />

    <TextView
        android:id="@+id/txtAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_vertical_margin"
        android:text="" />

    <TextView
        android:id="@+id/txtEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_vertical_margin"
        android:text=" " />

    <TextView
    android:id="@+id/txtGender"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/activity_vertical_margin"
    android:text="" />



</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="6dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mobile: "
            />

        <TextView
            android:id="@+id/txtPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_vertical_margin"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="6dp">

        <TextView
            android:id="@+id/textHome"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home: "/>

        <TextView
            android:id="@+id/txtHome"
            style="@style/textviewBadge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="6dp">

        <TextView
            android:id="@+id/textOffice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="office: "/>

        <TextView
            android:id="@+id/txtOffice"
            style="@style/textviewBadge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginTop="8dp"
        android:background="#ccc"></View>
</LinearLayout>



Create the Java file in project.
Open app => main => src = MainActivity.java



import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import co.apidemos.BaseActivity;
import co.apidemos.R;
import co.apidemos.adapter.CustomAdapter;
import co.apidemos.model.flow.ObjectData;
import co.apidemos.model.flow.UserData;
import co.apidemos.rest.APIClient;
import co.apidemos.rest.EndPoints;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Saify on 5/3/2017.
 **/

public class MainActivity extends BaseActivity {

    @BindView(R.id.emptyTextView)
    TextView emptyTextView;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    List<UserData> myDataSource = new ArrayList<>();
    RecyclerView.Adapter myAdater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setTitle(getApplicationContext().getResources().getString(R.string.stackoverflow));
        creatingLayouts();
        ButterKnife.bind(this);

        loadUsers();
    }

    private void loadUsers() {
        EndPoints apiService = APIClient.getStackOverFLowClient().create(EndPoints.class);
        Call<ObjectData> call = apiService.getUsers("");
        showProgressDialog();
        call.enqueue(new Callback<ObjectData>() {
            @Override
            public void onResponse(Call<ObjectData> call, Response<ObjectData> response) {

                List<UserData> users = response.body().getUsers();

                myDataSource.clear();
                myDataSource.addAll(response.body().getUsers());
                myAdater.notifyDataSetChanged();
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<ObjectData> call, Throwable t) {
                t.printStackTrace();
                emptyTextView.setText(t.toString());

            }
        });
    }

    private void creatingLayouts() {
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        myAdater = new CustomAdapter(getApplicationContext(), myDataSource, R.layout.list_item);
        recyclerView.setAdapter(myAdater);
    }

}



Create the Java file in project.

Open app => main => src = CustomerAdapter.java


import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import co.apidemos.R;
import co.apidemos.model.flow.UserData;

/**
 * Created by Saify on 5/3/2017.
 **/


public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.UserViewHolder> {
    private List<UserData> users;
    private Context mcontext;
    private int rowLayout;


    // constructor
    public CustomAdapter(Context mcontext, List<UserData> users, int rowLayout) {
        this.setMcontext(mcontext);
        this.setUsers(users);
        this.setRowLayout(rowLayout);
    }

    public Context getMcontext() {
        return mcontext;
    }

    public void setMcontext(Context mcontext) {
        this.mcontext = mcontext;
    }

    public List<UserData> getUsers() {
        return users;
    }

    public void setUsers(List<UserData> users) {
        this.users = users;
    }

    public int getRowLayout() {
        return rowLayout;
    }

    public void setRowLayout(int rowLayout) {
        this.rowLayout = rowLayout;
    }

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(rowLayout, parent, false);
        return new UserViewHolder(view);
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, final int position) {
        holder.userName.setText("NAME: "+users.get(position).getUserName());
        holder.userName.setTypeface(Typeface.DEFAULT_BOLD);
        holder.userAddess.setText("ADDRESS: " + users.get(position).getAddress());
        holder.userEmail.setText("EMAIL:  " + users.get(position).getEmail());
        holder.userGender.setText("Gender: "+users.get(position).getGender());


        Iterator<Map.Entry<String, String>> iterator=users.get(position).getPhone().entrySet().iterator();

        Map.Entry<String, String> pair=iterator.next();
        holder.phone.setText(pair.getKey()+ " : ");
        holder.phoneTextView.setText(pair.getValue());

        pair=iterator.next();
        holder.home.setText(pair.getKey()+ " : ");
        holder.homeTextView.setText(pair.getValue());

        pair=iterator.next();
        holder.office.setText(pair.getKey()+ " : ");
        holder.officeTextView.setText(pair.getValue());



        holder.usersLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mcontext, " " + users.get(position).getUserName(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return users.size();
    }


    public static class UserViewHolder extends RecyclerView.ViewHolder {

        LinearLayout usersLinearLayout;
        TextView userName;
        TextView userAddess;
        TextView userEmail;
        TextView userGender;
        TextView phoneTextView;
        TextView phone;
        TextView homeTextView;
        TextView home;
        TextView officeTextView;
        TextView office;


        public UserViewHolder(View itemView) {
            super(itemView);

            usersLinearLayout = (LinearLayout) itemView.findViewById(R.id.userLayout);
            userName = (TextView) itemView.findViewById(R.id.txtName);
            userAddess = (TextView) itemView.findViewById(R.id.txtAddress);
            userEmail = (TextView) itemView.findViewById(R.id.txtEmail);
            userGender = (TextView) itemView.findViewById(R.id.txtGender);
            phoneTextView = (TextView) itemView.findViewById(R.id.txtPhone);
            phone = (TextView) itemView.findViewById(R.id.textPhone);
            homeTextView = (TextView) itemView.findViewById(R.id.txtHome);
            home = (TextView) itemView.findViewById(R.id.textHome);
            officeTextView = (TextView) itemView.findViewById(R.id.txtOffice);
            office = (TextView) itemView.findViewById(R.id.textOffice);

        }
    }
}



//*****In this java file declaring the array list with array name********//


Create the Java file in project.
Open app => main => src = ObjectData.java

import com.google.gson.annotations.SerializedName;
import java.util.List;

/**
 * Created by Saify on 5/3/2017.
 **/

public class ObjectData {
    @SerializedName("contacts")
    private List<UserData> users;

    public  void setUsers(List<UserData> users){this.users=users;}
    public List<UserData> getUsers(){ return users;}
}



//*****set the parameter******//


Create the Java file in project.
Open app => main => src = UserData.java


import com.google.gson.annotations.SerializedName;

import java.util.HashMap;


/**
 * Created by Saify on 5/3/2017.
 **/

public class UserData {

    @SerializedName("address")
    private String address;
    @SerializedName("name")
    private String userName;

    @SerializedName("gender")
    private  String gender;

    @SerializedName("email")
    private String email;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }



    @SerializedName("phone")
    private HashMap<String, String> phone= new HashMap<>();

    public HashMap<String, String> getPhone() {
        return phone;
    }

    public void setPhone(HashMap<String, String> phone) {
        this.phone = phone;
    }

}


//********Set the base url and end point url*****//


Create the Java file in project.
Open app => main => src = APIClient.java


import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Saify on 5/3/2017.
 **/

public class APIClient {

    public static  final  String BASE_URL="http://api.androidhive.info";
    public static Retrofit retrofit=null;
   

    public static  Retrofit getStackOverFLowClient(){
        if(retrofit == null){
            retrofit=new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return  retrofit;
    }
}



Create the Java file in project.
Open app => main => src = EndPoint.java


import co.apidemos.model.flow.ObjectData;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Created by Saify on 5/3/2017.
 **/


public interface EndPoints {
    //get the user of stackoverflow
    @GET("/contacts/")
    Call<ObjectData> getUsers(@Query("") String sort);

}



//********Progres Dialog Class******//


Create the Java file in project.
Open app => main => src = BaseActivity.java


import android.app.ProgressDialog;
import android.support.annotation.VisibleForTesting;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by Saify on 5/3/2017.
 **/


public class BaseActivity extends AppCompatActivity {

    @VisibleForTesting
    public ProgressDialog mProgressDialog;

    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        hideProgressDialog();
    }

}



Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />


Tuesday 2 May 2017

Swipe to Refresh ListView(SwipeRefreshLayout) in Android Studio.

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project.
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

Create Xml file in project.  
Open => app => res => layout - activity_main.xml.

<?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:padding="16dp">


    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swiperefreshlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Swipe To Refresh"
            android:textSize="18dp" />

    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>




Create the Java file in project.

Open app => main => src = MainActivity.java

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {

    SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        refresh();
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefreshlayout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

    }

    private void refresh() {
        //Getting then data through json volley...
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://api.androidhive.info/contacts/",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //swipeRefreshLayout.setRefreshing(false);
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }
}


Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />


May this code help you. Thanks!!!!!!