Make a project using JSON Parsing or REST API from scratch on Android Studio JAVA.

Hey, guys...

In this blog, we will see how to parse JSON data from the REST API. For this, we need JSON data that come from the server. If you have the REST API, then it's ok if not then follow the tutorial.

JSON Parsing in Android Studio using Volley and Picasso

If you don't have the RSET API then go to the Reqres.in to use the dummy JSON data.  Here you can get every request like GET, POST, PUT, DELETE etc. We will fetch one user data from the URL using the GET method.

We will use the Volley to give the HTTP request and Picasso to show the images from the server.

REST API from  Reqres

Reqres single user GET method - https://reqres.in/api/users/2

Resposne

{
    "data": {
        "id"2,
        "email""janet.weaver@reqres.in",
        "first_name""Janet",
        "last_name""Weaver",
        "avatar""https://s3.amazonaws.com
/uifaces/faces/twitter/josephstein/128.jpg"
    },
    "ad": {
        "company""StatusCode Weekly",
        "url""http://statuscode.org/",
        "text""A weekly newsletter focusing on 
software development, infrastructure
, the server, performance, and the
 stack end of things."
    }
}

If you have API testing software like POSTMAN then you will get the response as the above JSON data.  We are going to build an android app that will show this data.

What we will build or Output?


Android Design


We will build the above app follow steps to build the above app.

Step. 1

Create a project, name your project. Choose java



Step. 2

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

Add the above internet permission for our project in the AndroidManifest.xml file.


Step. 3

Add the dependencies of Volley, Picasso and also the design support library or material library.

// Volley to make network request HTTP
implementation 'com.android.volley:volley:1.1.0'
// Use Picasso to fetch images from network server
implementation "com.squareup.picasso:picasso:2.5.2"
// Import design support library or material library
implementation 'com.google.android.material:material:1.0.0'


Then sync the project.

Step. 4

Create the activity_main.xml file to make the design where we will plot data from the server.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"android:layout_height="400dp"
android:layout_margin="5dp"xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="3dp"app:cardElevation="3dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:gravity="center" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetch JSON data from Reqres Server using GET Method"
android:textSize="19dp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="20dp"
/>
<ImageView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:id="@+id/image"
android:src="@mipmap/ic_launcher"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
android:text="Title"
android:textSize="20sp"
android:gravity="center"
android:layout_marginTop="30dp"
android:textColor="#000"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/email"
android:text="Email"
android:layout_marginTop="10dp"
android:textSize="18sp"
android:gravity="center"
android:textColor="#000"/>
</LinearLayout>
</androidx.cardview.widget.CardView>

Step. 5

Create the MainActivity.java.

package com.example.jsonparsing;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
// Declare elements
TextView name, email;
ImageView profile_pic;
// Use Progress Bar to load the data
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize all elements
name = findViewById(R.id.name);
email = findViewById(R.id.email);
profile_pic = findViewById(R.id.image);
// Initialize all Progress Dialog
progressDialog = new ProgressDialog(this);
// Declare method to retrieve data to make the onCreate method clean
getProfileData();
// Set message to progress bar
progressDialog.setMessage("Getting Data...");
// Set cancelable to progress bar on ouside click on screen we disabled here
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
// Here we show the Progress Dialog
progressDialog.show();
}
// Initialize the method
private void getProfileData() {
// Use the url of the server, we used here is reqres
String url = "https://reqres.in/api/users/2";
// Make a string request, by passing the method, url and we will get the response
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
// Get the whole object
JSONObject jsonObject = new JSONObject(response);
// Get the the data object inside the whole object
JSONObject innerObject = jsonObject.getJSONObject("data");
// Get all objects inside the data objects
String fetch_email = innerObject.getString("email");
String fetch_first_name = innerObject.getString("first_name");
String fetch_last_name = innerObject.getString("last_name");
String fetch_profile_pic_url = innerObject.getString("avatar");
// Set the values to our component
email.setText(fetch_email);
// Concatenate first name and last name
name.setText(fetch_first_name+" "+fetch_last_name);
// Load the image URL from the server using picasso: place holder
// used for show the default image
Picasso.with(getApplicationContext()).load(fetch_profile_pic_url)
.placeholder(R.drawable.ic_launcher_background)
.error(R.drawable.ic_launcher_background)
.into(profile_pic);
progressDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
progressDialog.hide();
}
}
// If some error will get then here we can watch
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(MainActivity.this, "Error :"+error.toString(),
Toast.LENGTH_SHORT).show();
progressDialog.hide();
}
}) {
// This is used to pass parameters using post method by using
//the params object we will put the datas
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return super.getParams();
}
};
// If some problem will occur then here it will retry the request again
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Follow the avobe steps that are written in the MainActivity.java to understand the codings. In overally we are initialised the component objects by findings it ID's. 
Then we created a method called getProfileData() where we did all the coding stuffs. 
We made a request to the Reqres URL then the server will give response back. Then we are just parsing the JSON data and showing on the app.  Try it yourself if you are getting problems then COMMNET below box.
Now its time to make close of this blog thank you for reading this blog, Next blog I will start blogging on "HOW TO MAKE API USING NODEJS ?" it will make your REST API development so easier. THANK YOU
Post a Comment (0)
Previous Post Next Post