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" />

No comments:

Post a Comment