https://choudhary780.blogspot.com/2017/05/json-parsing-with-retrofit-in-android.html
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" />
Comments
Post a Comment