Android Retrofit Tutorial | Get,Post Request With RecyclerView,ListView

android retrofit post request with parameters, android retrofit get request with parameters

Android Retrofit tutorial is the leading topic of this post. This post covers below examples,

1. Android Retrofit GET Request With Parameters Multiple QueryMap

2. Android Retrofit Post Request With Parameters

3. Android Retrofit ListView Tutorial Example

4. Android Retrofit Parse JSON Display RecyclerView Retrofit

1. Android Retrofit GET Request With Parameters Multiple QueryMap

Notice on Android Retrofit GET Request With Parameters example.

You will learn how to pass parameters in URL in retrofit GET requests to a remote servers.

Server will reply us the JSON data in string format. We will pass retrofit multiple and dynamic query parameters along with the URL.

Watch GET retrofit Parameters With Hashmap

Step 1. Required Basic Tasks

Make a new project in android studio. Select Empty activity as the default template.

We need to make two basic work.

First of all, add the following line in AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />

Now in your build.gradle(Module: app) file, write the below lines

 implementation 'com.squareup.retrofit2:retrofit:2.5.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'

First line will enable us to use the retrofit classes to make http call.

Second one will fetch the scalar library. This library will convert the JSON response in string format.

Step 2. Interface For URL

Let us make required interface. For this, create a new Java class and name it as GetInterface.java

GetInterface.java should have the following source code

import java.util.Map;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;

public interface GetInterface {

    String JSONGETURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";

    @GET("loginGETrequest.php")
    Call<String> getUserLogin( @QueryMap Map<String, String> options);
}

First line is the string variable called JSONGETURL. This variable includes the URL which we need to fire.

@GET(“loginGETrequest.php”) is telling the compiler to make GET request to loginGETrequest.php file.

We will call getUserLogin() method to make the http call. It has hashmap (QueryMap) in it’s first parameter.

This hashmap includes the parameters which we need to pass with the URL.

Step 3. Showcase activity

Server will give us information like name, hobby, username, password etc information when we successfully get logged in.

In this activity we will show two information like name and hobby in text views.

So make a new activity and give it a name like NameActivity.java and activity_name.xml

Code block for activity_name.xml is as the below

<?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="#ec0d45"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvusername"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:text="hello"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvpassword"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"/>


</LinearLayout>

As already mentioned, this file includes two text views.

Now in NameActivity.java file, write the following code lines

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

public class NameActivity extends AppCompatActivity {

    private TextView tvName, tvPass;

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

        tvName = findViewById(R.id.tvusername);
        tvPass = findViewById(R.id.tvpassword);

        tvName.setText(MainActivity.firstName);
        tvPass.setText(MainActivity.hobby);

    }
}

For writing name and hobby in the text views, I am using two variables which are defined in the Main Activity.

Access specifier for these variables are public static, so we can use them here in name activity.

Step 4. Final Attack

Now last thing is to write two main files : activity_main.xml and MainActivity.java

Code structure for activity_main.xml file is looking like the following

<?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="#ec0d45"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="35sp"
        android:text="DemoNuts - Retrofit GET request with parameters"
        android:textColor="#fff"
        android:layout_marginBottom="20dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etusername"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etpassword"
        android:inputType="textPassword"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Login"
        android:textSize="29sp"
        android:background="#0bbc37"
        android:textColor="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"/>

</LinearLayout>

Several UI widgets are there in the above file. One text view, two edit texts and one button.

Text view have stationary text which you can replace with company name or logo.

One edit text will get the value of username and other one will get password from the user.

When the user clicks the button, retrofit will hit the GET call to the URL.

In the MainActivity.java , write down the below source code

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

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

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private EditText etUname, etPass;
    private Button btn;
    public static String firstName, hobby;

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

        etUname = findViewById(R.id.etusername);
        etPass = findViewById(R.id.etpassword);
        btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });

    }

    private void loginUser() {

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(GetInterface.JSONGETURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        GetInterface api = retrofit.create(GetInterface.class);

        Map<String, String> mapdata = new HashMap<>();
        mapdata.put("username", username);
        mapdata.put("password", password);

        Call<String> call = api.getUserLogin(mapdata);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        parseLoginData(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });

    }

    public void parseLoginData(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    firstName = dataobj.getString("name");
                    hobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,NameActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

Care about Main

Above class includes the important logic so let us understand it carefully.

First of all, see the below code snippet

 private EditText etUname, etPass;
    private Button btn;
    public static String firstName, hobby;

First line is making the objects of Edit text class. Second is giving the button element.

Last line is creating two public static string variables. We have already seen their usages in the previous step.

Consider following code

  btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });

When the user clicks the button, compiler will execute above code.

It will simply call the loginUser() method.

Source code block for  loginUser() method is as the below

 private void loginUser() {

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(GetInterface.JSONGETURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        GetInterface api = retrofit.create(GetInterface.class);

        Map<String, String> mapdata = new HashMap<>();
        mapdata.put("username", username);
        mapdata.put("password", password);

        Call<String> call = api.getUserLogin(mapdata);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        parseLoginData(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });

    }

In this method, we will create two string variables first. (username and password )

These variables will get their values from two edit texts.

After this, compiler will create the object of the Retrofit class.

Here, .baseUrl(GetInterface.JSONGETURL) method will providing URL to the Retrofit object.

Now we are creating a hashmap. Here, you need to write parameters which we want to pass along with the URL.

In this login service, we are passing two parameters : username and password, so that , we will create two key value pair for hashmap.

You can add any number of parameters in this hashmap so it is working as dynamic json request.

Then we will create the object of Call<string> class.Here, we are providing this hashmap (parameters) to the URL.

Finally, call.enqueue() will fire the http call. When the server sends the response, compiler will call onResponse() method.

In this method, compiler will first convert the response in string format. Then it will call the parseLoginData() method.

parseLoginData() method holds the following code block

 public void parseLoginData(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    firstName = dataobj.getString("name");
                    hobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,NameActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

This methods takes the JSON response in string format as a parameter.

Now inside this method, compiler will first parse the json object. Then it will check the “status” field’s value. If it is true then it will parse one json array using “data” field from the response

After this, it will create one for loop and will fetch the value of name and hobby.

It will store these values into the public static string variables.





2. Android Retrofit Post Request With Parameters

Android Retrofit Post Request With Parameters JSON Example welcomes you.

You will learn to make http call using retrofit post request with parameters in this tutorial.

Several server calls like log in, registration, near by place etc. request need to have parameter with the URL.

For example, you want to fire login web service than you need to pass username and password along with the URL.

So here I will show you how to do this with retrofit POST request in android application.

Watch the Retrofit POST

Load the following video to see final outcome of this video.

PHP File

We are using the below php file ( simplelogin.php ) in this tutorial.

<?php

   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
//including the database connection file
       include_once("config.php");
       
        $username = $_POST['username'];
 	$password = $_POST['password'];
 	
	 if( $username == '' || $password == '' ){
	        echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
	 }else{
	 	$query= "SELECT * FROM registerDemo WHERE username='$username' AND password='$password'";
	        $result= mysqli_query($con, $query);
		 
	        if(mysqli_num_rows($result) > 0){  
	         $query= "SELECT * FROM registerDemo WHERE username='$username' AND password='$password'";
	                     $result= mysqli_query($con, $query);
		             $emparray = array();
	                     if(mysqli_num_rows($result) > 0){  
	                     while ($row = mysqli_fetch_assoc($result)) {
                                     $emparray[] = $row;
                                   }
	                     }
	           echo json_encode(array( "status" => "true","message" => "Login successfully!", "data" => $emparray) );
	        }else{ 
	        	echo json_encode(array( "status" => "false","message" => "Invalid username or password!") );
	        }
	         mysqli_close($con);
	 }
	} else{
			echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
	}
?>

Step 1. Initial Works

Our first first task is to make a new project in android studio with empty activity.

After this, in the AndroidManifest.xml file, add the following line.

<uses-permission android:name="android.permission.INTERNET" />

Above line is the internet permission. We need this permission to use the internet of the android device.

Now in your build.gradle(Module: app) file, write the following line

 implementation 'com.squareup.retrofit2:retrofit:2.5.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'

First line will fetch the classes of the retrofit 2 library.

Second will enable us to use the scalar library in our project.

Step 2. Retrofit Interface

For using retrofit, we need to make one Interface.

Make a new JAVA file and give it a name like PostInterface.java

Source code for PostInterface.java is looking like below file

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface PostInterface {

    String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";
    @FormUrlEncoded
    @POST("simplelogin.php")
    Call<String>  getUserLogin(
            @Field("username") String uname,
            @Field("password") String password
    );
}

first line is defining a string variable. This variable includes the URL for login.

Consider @POST(“simplelogin.php”). Here, @POST is saying that retrofit will make POST request.

Inside getUserLogin() method, there are two string parameters which we need to pass with the web service URL.

Step 3. Showing Credentials

Prepare a new activity called “Hobby Activity.”

System will create two files : activity_hobby.xml and HobbyActivity.java

Source code for activity_hobby.xml should look like the below

<?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="#edd712"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvusername"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:text="hello"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvpassword"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"/>


</LinearLayout>

This file includes two text views. One will hold the value of user name or first name.

Second text view will get the value of hobby in string format.

Now in HobbyActivity.java file, you should add the following source code

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

public class HobbyActivity extends AppCompatActivity {

    private TextView tvName, tvPass;

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

        tvName = findViewById(R.id.tvusername);
        tvPass = findViewById(R.id.tvpassword);

        tvName.setText(MainActivity.firstName);
        tvPass.setText(MainActivity.hobby);

    }
}

As we have added two text views in activity_hobby.xml , here we will get them using their ID.

Both these text views will get their values from two public string variables defined in the Main activity.

Step 4. Final and Main thoughts

Time to write two main files of this example : activity_main.xml and MainActivity.java

In your activity_main.xml file, add the below code snippet

<?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="#ec0d45"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="45sp"
        android:text="DemoNuts"
        android:textColor="#fff"
        android:layout_marginBottom="20dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etusername"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etpassword"
        android:inputType="textPassword"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Login"
        android:textSize="29sp"
        android:background="#0bbc37"
        android:textColor="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"/>

</LinearLayout>

Above file have One text view, two edit texts and one button.

text view is just saying the company name.

I have added one edit text is for username and other one is for password.

When the user clicks the button, system will make the http call.

Now code structure for MainActivity.java is looking like the below

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private EditText etUname, etPass;
    private Button btn;
    public static String firstName, hobby;

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

        etUname = findViewById(R.id.etusername);
        etPass = findViewById(R.id.etpassword);
        btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });

    }

    private void loginUser() {

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(PostInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        PostInterface api = retrofit.create(PostInterface.class);

        Call<String> call = api.getUserLogin(username,password);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        parseLoginData(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });

    }

    public void parseLoginData(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    firstName = dataobj.getString("name");
                    hobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,HobbyActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

Taking above code seriously

Let us see words of main activity in deep.

Consider the following code block

 private EditText etUname, etPass;
 private Button btn;
 public static String firstName, hobby;

First line is making an object of edit text and second one is of Button.

Third line making two public static string variables. We have used these variables in hobby activity.

Now read the below code block

  btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });

When the user clicks the button, compiler will execute the above code.

It will simply call the loginUser() method.

Following is the coding lines for  loginUser() method.

private void loginUser() {

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(PostInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        PostInterface api = retrofit.create(PostInterface.class);

        Call<String> call = api.getUserLogin(username,password);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        parseLoginData(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });

    }

First two lines will declare the two string variables.

First one will get the string value from etUname edittext. It is the username entered by the user.

Second line will give the password of the user to the string variable from another edit text.

After this, compiler will create the object of the Retrofit class.

Here, .baseUrl(PostInterface.JSONURL) line is telling retrofit about the URL.

After this, compiler will create the object of the PostInterface and Call<String> classes.

Now, api.getUserLogin() method will get username and password as a parameter.

At this point, system have made the http call to the remote server. When the compiler get the response, it will call the onResponse() method.

Inside this onResponse() method, we will get the response in string format.

After this, compiler will call parseLoginData() method.

Following is the main source code for parseLoginData() method.

 public void parseLoginData(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    firstName = dataobj.getString("name");
                    hobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,HobbyActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

First of all, compiler will check the value of “status” field of the JSON response. If this value is “true” then it will parse a json array.

Compiler will parse the Json array using the “data” field from the string json response.

Now it will go through one for loop. Inside for loop, it will get the value of “name” and “hobby.”

It will store these values into public string variables called “firstName” and “hobby.”

After this, system will open the Hobby Activity.





3. Android Retrofit ListView Tutorial Example

You are reading about Android Retrofit ListView Tutorial Example Parse JSON Step By Step.

Retrofit android tutorial will guide you to parse JSON data from the remote web server and then display this data in the ListView.

We will fetch/retrieve JSON data from MySQL database (server) using retrofit and will make custom listview with image and text.

In this tutorial, we will fetch the information like player name, city, country and image URL in JSON format with retrofit library.

Retrofit library makes our task easy to do http calls to the web service to retrieve the JSON data.

It also handles the cache of data in the proper manner.

Then a listview will showcase this information in a perfect format.

Last Look Of Retrofit ListView

Let us reach our goal step by step.

Step 1. Permission and Gradle lines

Open up your android studio and make a new fresh project with empty activity as a default activity.

When we want to get data from server, we need to use internet of the android device.

For this need, we will write one line in AndroidManifest.xml file. Below line will enable our app to use internet.

 <uses-permission android:name="android.permission.INTERNET"/>

After this, let us add some lines in the build.gradle(Module:app) file as per the below

 implementation 'com.squareup.retrofit2:retrofit:2.5.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
 implementation 'com.squareup.picasso:picasso:2.71828'

First line will add the required classes to use retrofit library in our project.

Second line will enable us to use the coding lines of the scalar library.

By default, retrofit will not give us the JSON response in a string format. Scalar helps us to convert the JSON data into the string format.

Last line is for picasso library. This library will help us to load the images from URL and to maintain the image cache.

Step 2. Making Our Interface

Prepare a new JAVA class and give it a name MyInterface.java

Write down the below source code in MyInterface.java

import retrofit2.Call;
import retrofit2.http.GET;

public interface MyInterface {

    String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";

    @GET("json_parsing.php")
    Call<String> getString();
}

A string variable JSONURL contains the URL from which we will get our JSON data.

@GET annotation holds the name of the php file.

getString() function has the return type as a call back in the string format.

Step 3. Model class for ListView

Now make a new java class named ModelListView.java

Source code for ModelListView.java is looking like the following

  private String name, country, city, imgURL;

    public String getImgURL(){
        return imgURL;
    }

    public void setImgURL(String imgURL){
        this.imgURL = imgURL;
    }

    public String getName() {
        return name;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

Types of information we are getting from JSON is like name, city, country etc.

Above class includes getter ans setter information for all the types of the information.

These methods will help us to maintain data between the listview and the adapter class.

Step 4. Special layout file

Create a new layout resource file named retro_lv.xml and write the below code snippet in this 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">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:scaleType="fitXY"
        android:id="@+id/iv"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_marginTop="5dp"
            android:layout_weight="1"
            android:id="@+id/name"
            android:text="ddd"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/country"
            android:text="ddd"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/city"
            android:text="ddd"/>

    </LinearLayout>



</LinearLayout>

This file have one image view and three text views.

We will fetch image from the URL in this image view.

Textviews will hold the information like name, country, city etc.

Step 5. Retro Adapter

Time to make an adapter class for the listview.

Prepare a new class and named it as RetroAdapter.java

Following is the code structure for RetroAdapter.java class

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;

public class RetroAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<ModelListView> dataModelArrayList;

    public RetroAdapter(Context context, ArrayList<ModelListView> dataModelArrayList) {

        this.context = context;
        this.dataModelArrayList = dataModelArrayList;
    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }
    @Override
    public int getItemViewType(int position) {

        return position;
    }

    @Override
    public int getCount() {
        return dataModelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return dataModelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.retro_lv, null, true);

            holder.iv = (ImageView) convertView.findViewById(R.id.iv);
            holder.tvname = (TextView) convertView.findViewById(R.id.name);
            holder.tvcountry = (TextView) convertView.findViewById(R.id.country);
            holder.tvcity = (TextView) convertView.findViewById(R.id.city);

            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }

        Picasso.get().load(dataModelArrayList.get(position).getImgURL()).into(holder.iv);
        holder.tvname.setText("Name: "+dataModelArrayList.get(position).getName());
        holder.tvcountry.setText("Country: "+dataModelArrayList.get(position).getCountry());
        holder.tvcity.setText("City: "+dataModelArrayList.get(position).getCity());

        return convertView;
    }

    private class ViewHolder {

        protected TextView tvname, tvcountry, tvcity;
        protected ImageView iv;
    }

}

Look at the constructor in the above adapter class. It has two parameters.

First parameters will get context while other one will get the arraylist with the objects of the ModelListView class.

getView() method contain the necessary coding lines to fill the information.

Following lines are populating the row of the listview.

 Picasso.get().load(dataModelArrayList.get(position).getImgURL()).into(holder.iv);
        holder.tvname.setText("Name: "+dataModelArrayList.get(position).getName());
        holder.tvcountry.setText("Country: "+dataModelArrayList.get(position).getCountry());
        holder.tvcity.setText("City: "+dataModelArrayList.get(position).getCity());

First line line will load the image from the URL using picasso library.

Other three lines will fill the name, country and city respectively.

Step 6. Main Modifications

Now just need to change the main files.

First of all, add the below code snippet in the activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="26sp"
        android:text="Below ListView is populated from RETROFIT JSON Data"
        android:textColor="#000"
        />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lv"
        android:layout_marginTop="10dp"/>


</LinearLayout>

Above file holds one text view and one listview.

Text view is static and it is saying that below listview have data which is parsed with retrofit.

Now in the MainActivity.java file, you should write the following coding lines

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private RetroAdapter retroAdapter;

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

        listView = findViewById(R.id.lv);

        getJSONResponse();

    }

    private void getJSONResponse(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        MyInterface api = retrofit.create(MyInterface.class);

        Call<String> call = api.getString();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        writeListView(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private void writeListView(String response){

        try {
            //getting the whole json object from the response
            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

                ArrayList<ModelListView> modelListViewArrayList = new ArrayList<>();
                JSONArray dataArray  = obj.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    ModelListView modelListView = new ModelListView();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    modelListView.setImgURL(dataobj.getString("imgURL"));
                    modelListView.setName(dataobj.getString("name"));
                    modelListView.setCountry(dataobj.getString("country"));
                    modelListView.setCity(dataobj.getString("city"));

                    modelListViewArrayList.add(modelListView);

                }

                retroAdapter = new RetroAdapter(this, modelListViewArrayList);
                listView.setAdapter(retroAdapter);

            }else {
                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

Deep Into Main Activity

Let us check what will main activity code actually do in this app.

First of all in onCreate() method, compiler will call getJSONResponse() method.

Source code for getJSONResponse() method is as the below

  private void getJSONResponse(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        MyInterface api = retrofit.create(MyInterface.class);

        Call<String> call = api.getString();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        writeListView(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

Here, compiler will create the object of the Retrofit class. During this process, it will bind the URL using .baseUrl() method.

Then compiler will create the object of the MyInterface class which we have created in Step 2.

An object of the Call<String> will use call.enqueue() to make the http call.

When system gives the final JSON response then compiler will call onResponse() method.

Inside the onResponse() method, we will get the JSON response in the string format.

Then call to writeListView() method will be taken place.

Code for writeListView() method is as the following

 private void writeListView(String response){

        try {
            //getting the whole json object from the response
            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

                ArrayList<ModelListView> modelListViewArrayList = new ArrayList<>();
                JSONArray dataArray  = obj.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    ModelListView modelListView = new ModelListView();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    modelListView.setImgURL(dataobj.getString("imgURL"));
                    modelListView.setName(dataobj.getString("name"));
                    modelListView.setCountry(dataobj.getString("country"));
                    modelListView.setCity(dataobj.getString("city"));

                    modelListViewArrayList.add(modelListView);

                }

                retroAdapter = new RetroAdapter(this, modelListViewArrayList);
                listView.setAdapter(retroAdapter);

            }else {
                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

Let us first check the JSON data which we get from the server.

{
    "status": "true",
    "message": "Data fetched successfully!",
    "data": [
        {
            "id": "1",
            "name": "Roger Federer",
            "country": "Switzerland",
            "city": "Basel"
        },
        {
            "id": "2",
            "name": "Rafael Nadal",
            "country": "Spain",
            "city": "Madrid"
        },
        {
            "id": "3",
            "name": "Novak Djokovic",
            "country": "Serbia",
            "city": "Monaco"
        },
        {
            "id": "4",
            "name": "Andy Murray",
            "country": "United Kingdom",
            "city": "London"
        },
        {
            "id": "5",
            "name": "Maria Sharapova",
            "country": "Russia",
            "city": "Moscow"
        },
        {
            "id": "6",
            "name": "Caroline Wozniacki",
            "country": "Denmark",
            "city": "Odense"
        },
        {
            "id": "7",
            "name": "Eugenie Bouchard",
            "country": "Canada",
            "city": " Montreal"
        },
        {
            "id": "8",
            "name": "Ana Ivanovic",
            "country": "Serbia",
            "city": "Belgrade"
        }
    ]
}

Now understand the writeListView() method and also check the JSON data simultaneously.

Here, compiler will first get the json array from the field “data

Then it will run one for loop. In the every iteration of the for loop, compiler will fetch the information and will set it in the object of the ModelListView class.

After the completion of the for loop, compiler will set the arraylist to the second parameter of the RetroAdapter.

Finally, adapter is set to the listview and whooom, our example is finish!!





4. Android Retrofit Parse JSON Display RecyclerView Retrofit

This post is about Android RecyclerView Retrofit Tutorial With Example.

Android JSON parsing and display with recyclerview using retrofit is today’s topic.

In this tutorial, we will retrieve JSON data from MySQL database and then we will set this data in Recycler View.

Retrofit library is useful to make http calls seamlessly and it also saves time.

If we make http call with android’s in built classes then this task can be a little tricky.

Following is Output

Step 1. Gradle and Permission Tasks

Create a new project in the android studio. Select Empty activity during the process of making a new project.

Now in the AndroidManifest.xml file, add the following line

<uses-permission android:name="android.permission.INTERNET" />

Above line will enable our app to use the internet so that we can fetch JSON data from web server or MySQL database.

Now we need to use five different libraries in this project.

Write down the following coding lines in build.gradle(Module: app) file

 implementation 'com.squareup.retrofit2:retrofit:2.5.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
 implementation 'com.squareup.picasso:picasso:2.71828'
 implementation 'com.android.support:recyclerview-v7:27.1.1'
 implementation 'com.android.support:cardview-v7:27.1.1'

First coding line will fetch the required classes to use the retrofit library.

Second line will enable us to use the scalars library. This library will help us to convert the JSON response into the string format.

Third one will allow us to use Picasso library which will load the images from the URL for us.

Fourth line is for recycler view.

And last one is for card view because recycler view and card view are not added to the default UI widgets (like text view, edittext, list view etc.) in the android system.

Step 2. Required Interface

Create a new JAVA class. Give it a name like RecyclerInterface.java and add the following source code in it

import retrofit2.Call;
import retrofit2.http.GET;

public interface RecyclerInterface {

    String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";

    @GET("json_parsing.php")
    Call<String> getString();
}

A string variable JSONURL holds the URL of the json file in the string format.

Name of the PHP file is not included in the string variable but it is present in the @GET annotation.

Then a method is defined as the getString() which has the return type as Call<String>.

Step 3. Model For Retrofit

Make a new JAVA class and call it as ModelRecycler.java

Source code for ModelRecycler.java class is as the following

public class ModelRecycler {

    private String name, country, city, imgURL;

    public String getImgURL(){
        return imgURL;
    }

    public void setImgURL(String imgURL){
        this.imgURL = imgURL;
    }

    public String getName() {
        return name;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

Our JSON data has certain types of information such as player’s name, country, city and URL of the image.

Model class have getter and setter methods for all these information types.

Such type of model class helps us to maintain proper data structure while interacting with the RecyclerView.

Step 4. Layout File for RecyclerView

Create a new layout file under res->layout directory.

Name of this file should be retro_item.xml

Source code for this file is as per the below

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

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        app:cardCornerRadius="5dp">

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

            <ImageView
                android:id="@+id/iv"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:scaleType="fitXY" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="100dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_marginTop="5dp"
                    android:layout_weight="1"
                    android:text="ddd"
                    android:textColor="#000"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/country"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:text="ddd"
                    android:textColor="#000"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/city"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:text="ddd"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

I have written one image view and three text views in this file.

Picasso will fetch will image in this image view while text views will hold the information like country, name and city.

All the rows of the recyclerview will get their look and feel from this layout file.

Step 5. Adapter For Retrofit RecyclerView

Time to write the adapter file to populate our recycler view.

Create a new JAVA class and set it’s name as RetrofitAdapter.java

Following is the code structure for RetrofitAdapter.java  class

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;

public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    private ArrayList<ModelRecycler> dataModelArrayList;

    public RetrofitAdapter(Context ctx, ArrayList<ModelRecycler> dataModelArrayList){

        inflater = LayoutInflater.from(ctx);
        this.dataModelArrayList = dataModelArrayList;
    }

    @Override
    public RetrofitAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.retro_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(RetrofitAdapter.MyViewHolder holder, int position) {

        Picasso.get().load(dataModelArrayList.get(position).getImgURL()).into(holder.iv);
        holder.name.setText(dataModelArrayList.get(position).getName());
        holder.country.setText(dataModelArrayList.get(position).getCountry());
        holder.city.setText(dataModelArrayList.get(position).getCity());
    }

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

    class MyViewHolder extends RecyclerView.ViewHolder{

        TextView country, name, city;
        ImageView iv;

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

            country = (TextView) itemView.findViewById(R.id.country);
            name = (TextView) itemView.findViewById(R.id.name);
            city = (TextView) itemView.findViewById(R.id.city);
            iv = (ImageView) itemView.findViewById(R.id.iv);
        }

    }
}

First of all, look at the second parameter of the constructor. It has arraylist with the objects of the ModelRecycler class.

This arraylist will work as the data source in this adapter.

Now read the onBindViewHolder() method. Compiler will fill the information using this method.

First line inside onBindViewHolder() method will load the image from URL using Picasso library.

Second, third and fourth lines will set the information like name, country and city respectively in the text views.

Step 6. Main Activity files

At last but not least, we need to change the writings for main files.

In your activity_main.xml file, add the below code lines

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:background="#15e6e6"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Below RecyclerView is populated from Retrofit JSON Data"
        android:textColor="#fff"
        android:textStyle="bold"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginTop="15dp"/>

</LinearLayout>

One text view and a recycler view is present in the main layout file.

Text view has constant value and it is saying like “Recyclerview has JSON data which is fetched with retrofit.”

Now in the MainActivity.java file, you should add the following code snippet

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private RetrofitAdapter retrofitAdapter;
    private RecyclerView recyclerView;

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

        recyclerView = findViewById(R.id.recycler);

        fetchJSON();

    }

    private void fetchJSON(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RecyclerInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        RecyclerInterface api = retrofit.create(RecyclerInterface.class);

        Call<String> call = api.getString();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        writeRecycler(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private void writeRecycler(String response){

        try {
            //getting the whole json object from the response
            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

                ArrayList<ModelRecycler> modelRecyclerArrayList = new ArrayList<>();
                JSONArray dataArray  = obj.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    ModelRecycler modelRecycler = new ModelRecycler();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    modelRecycler.setImgURL(dataobj.getString("imgURL"));
                    modelRecycler.setName(dataobj.getString("name"));
                    modelRecycler.setCountry(dataobj.getString("country"));
                    modelRecycler.setCity(dataobj.getString("city"));

                    modelRecyclerArrayList.add(modelRecycler);

                }

                retrofitAdapter = new RetrofitAdapter(this,modelRecyclerArrayList);
                recyclerView.setAdapter(retrofitAdapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

            }else {
                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


}

Main Activity Roots

Inside onCreate() method, compiler will call fetchJSON() method.

Coding lines for fetchJSON() method is as the following

 private void fetchJSON(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RecyclerInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        RecyclerInterface api = retrofit.create(RecyclerInterface.class);

        Call<String> call = api.getString();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        writeRecycler(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

First task is to create the object of the Retrofit class. Here, .baseUrl() contains the URL to which we will make the http call.

Then compiler will create the object of the RecyclerInterface class which we have made during the step 2.

After that, compiler will make the call object and using it, it will execute the .enqueue() method.

Until now, retrofit have make the http call to the URL. When server gives the response, compiler will call onResponse() method.

Here we will get our JSON response in string format. Then compiler will call writeRecycler() method.

Before we read writeRecycler() method, let us first check the JSON STRUCTURE

{
    "status": "true",
    "message": "Data fetched successfully!",
    "data": [
        {
            "id": "1",
            "name": "Roger Federer",
            "country": "Switzerland",
            "city": "Basel"
        },
        {
            "id": "2",
            "name": "Rafael Nadal",
            "country": "Spain",
            "city": "Madrid"
        },
        {
            "id": "3",
            "name": "Novak Djokovic",
            "country": "Serbia",
            "city": "Monaco"
        },
        {
            "id": "4",
            "name": "Andy Murray",
            "country": "United Kingdom",
            "city": "London"
        },
        {
            "id": "5",
            "name": "Maria Sharapova",
            "country": "Russia",
            "city": "Moscow"
        },
        {
            "id": "6",
            "name": "Caroline Wozniacki",
            "country": "Denmark",
            "city": "Odense"
        },
        {
            "id": "7",
            "name": "Eugenie Bouchard",
            "country": "Canada",
            "city": " Montreal"
        },
        {
            "id": "8",
            "name": "Ana Ivanovic",
            "country": "Serbia",
            "city": "Belgrade"
        }
    ]
}

Now following is the code for writeRecycler() method

 private void writeRecycler(String response){

        try {
            //getting the whole json object from the response
            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

                ArrayList<ModelRecycler> modelRecyclerArrayList = new ArrayList<>();
                JSONArray dataArray  = obj.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    ModelRecycler modelRecycler = new ModelRecycler();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    modelRecycler.setImgURL(dataobj.getString("imgURL"));
                    modelRecycler.setName(dataobj.getString("name"));
                    modelRecycler.setCountry(dataobj.getString("country"));
                    modelRecycler.setCity(dataobj.getString("city"));

                    modelRecyclerArrayList.add(modelRecycler);

                }

                retrofitAdapter = new RetrofitAdapter(this,modelRecyclerArrayList);
                recyclerView.setAdapter(retrofitAdapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

            }else {
                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

First of all, compiler will check the status field from JSON. If it has value as true then it will parse one JSONArray.

Field named “data” holds the json array and compiler will parse it in object of the ArrayList<ModelRecycler>.

Then compiler will run one for loop.

During the every iteration of for loop, system set the information using various setter methods of the ModelRecycler class.

After the completion of the for loop, compiler create the object of the RetrofitAdapter class and will bind it with the recycler view.