Android JSON Parsing from Web URL without Any Library

THUMB-ANDROID JSON PARSING FROM WEB URL WITHOUT ANY LIBRARY

11th October, 2022

Hi Developer!

In this tutorial you will learn how to parse JSON data from the URL. Please read previous part to learn how to parse JSON data from assets folder.

Host Your JSON File to the Web

If you have any web hosting, place your JSON file there. If you do not have one, you can host your JSON file on the Free JSON hosting providers.
http://myjson.com is one of them.

{
  "employee":
  [
    {
      "name": "Ava",
      "gender": "Female",
      "age": 26
    },
    {
      "name": "Daniel",
      "gender": "Male",
      "age": 35
    },
    {
      "name": "Emily",
      "gender": "Female",
      "age": 32
    }
  ]
}

Android JSON Parsing from Web URL without Any Library

Step 1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 2: Add Internet permission

Open AndroidManifest.xml and add the internet usage permission.

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

Step 3: Load JSON file from the Web URL

Open MainActivity and add web URL of JSON file. then create a private class inside the activity and add the code below.

private class MyJSONTask extends AsyncTask<Void, Void, String>
{
	//Web URL of the JSON file
	String jsonURL = "https://api.myjson.com/bins/14j37k";

	@Override
	protected void onPreExecute()
	{
		super.onPreExecute();
		/*if (mLoading != null)
		{
			mLoading.setVisibility(View.VISIBLE);
		}*/
	}

	@Override
	protected String doInBackground(Void... voids)
	{
		HttpURLConnection urlConnection = null;
		BufferedReader bufferedReader = null;

		try
		{
			//---Loading JSON from the Web URL---//
			URL url = new URL(jsonURL);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.connect();


			InputStream inputStream = urlConnection.getInputStream();

			bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

			StringBuffer stringBuffer = new StringBuffer();

			String line;

			while ((line = bufferedReader.readLine()) != null)
			{
				stringBuffer.append(line).append("\n");
			}
			if (stringBuffer.length() == 0)
			{
				return null;
			} else
			{
				return stringBuffer.toString();
			}
		} catch (IOException e)
		{
			return null;
		} finally
		{
			if (urlConnection != null)
			{
				urlConnection.disconnect();
			}
			if (bufferedReader != null)
			{
				try
				{
					bufferedReader.close();
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void onPostExecute(String jsonStr)
	{
		super.onPostExecute(jsonStr);

		if (jsonStr != null)
		{
			//---Parsing JSON---//
			ArrayList<Employee> employeesList = new ArrayList<>();
			try
			{
				JSONObject rootJsonObject = new JSONObject(jsonStr);

				JSONArray employeeJsonArray = rootJsonObject.getJSONArray("employee");

				for (int i = 0; i < employeeJsonArray.length(); i++)
				{
					//Create a temp employee object
					Employee aEmployee = new Employee();

					JSONObject jsonObject = employeeJsonArray.getJSONObject(i);

					//Get employee details
					aEmployee.setName(jsonObject.getString("name"));
					aEmployee.setGender(jsonObject.getString("gender"));
					aEmployee.setAge(jsonObject.getInt("age"));

					//add to list
					employeesList.add(aEmployee);
				}

				if (employeesList.size() > 0)
				{
					//Replace RecyclerView Adapter Data
					//mMyRecyclerViewAdapter.updateData(employeesList);
				}

			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}
		/*if (mLoading != null)
		{
			mLoading.setVisibility(View.GONE);
		}*/
	}
}

Step 4: Display JSON Data into RecyclerView

4.1: Add RecyclerView dependencies to the App Level Gradle.

Project ⇒ app ⇒ build.gradle

dependencies {
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
}

4.2: Add the RecyclerView to the Activity Layout.

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/myRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/myLoadingLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#33000000"
        android:clickable="true"
        android:focusable="true"
        android:orientation="vertical"
        android:gravity="center">

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Loading data. Please wait..."
            android:textColor="#FFFFFF"/>
    </LinearLayout>
</RelativeLayout>

4.3: Create a model class that represents employees details.

package com.codestringz.jsontest;

public class Employee
{
    private String name;
    private String gender;
    private int age;

    public String getName()
    {
        return name;
    }

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

    public String getGender()
    {
        return gender;
    }

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

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}

4.4: Create a layout resource file. This layout will used to display employees details in the RecyclerView.

<?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="wrap_content"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name" />

    <TextView
        android:id="@+id/textViewGender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Gender" />

    <TextView
        android:id="@+id/textViewAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Age" />
</LinearLayout>

4.5: Create a Adapter for the RecyclerView.

package com.codestringz.jsonparsingtest;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder>
{
    private ArrayList<Employee> mEmployeeList = new ArrayList<>();

    public MyRecyclerViewAdapter(ArrayList<Employee> mEmployeeList)
    {
        this.mEmployeeList = mEmployeeList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        View employeeRow = LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_row, parent, false);

        MyViewHolder myViewHolder = new MyViewHolder(employeeRow);

        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position)
    {
        String name = "Name: " + mEmployeeList.get(position).getName();
        holder.nameTextView.setText(name);

        String gender = "Gender: " + mEmployeeList.get(position).getGender();
        holder.genderTextView.setText(gender);

        String ageStr = "Age: " + mEmployeeList.get(position).getAge();
        holder.ageTextView.setText(ageStr);
    }

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

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

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

    public void updateData(ArrayList<Employee> pEmployeesList)
    {
        if (pEmployeesList.size() > 0)
        {
            mEmployeeList.clear();
            mEmployeeList.addAll(pEmployeesList);
            notifyDataSetChanged();
        }
    }

    public class MyViewHolder extends RecyclerView.ViewHolder
    {
        private TextView nameTextView;
        private TextView genderTextView;
        private TextView ageTextView;

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

            nameTextView = itemView.findViewById(R.id.nameTextView);
            genderTextView = itemView.findViewById(R.id.genderTextView);
            ageTextView = itemView.findViewById(R.id.ageTextView);
        }
    }
}

4.6: Now modify the Activity. Load JSON Data from the assets folder. Create an object of the RecyclerView Adapter and set it to the RecyclerView.

IMG-JSON-Data-Parsing-in-Android
JSON Data Parsing in Android
package com.codestringz.jsonparsingtest;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends AppCompatActivity
{
    private MyRecyclerViewAdapter mMyRecyclerViewAdapter;
    private ViewGroup mLoading;

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

        setUIRef();

        new MyJSONTask().execute();
    }

    private void setUIRef()
    {
        mLoading = findViewById(R.id.myLoadingLayout);

        RecyclerView recyclerView = findViewById(R.id.myRecyclerView);

        ArrayList<Employee> employees = new ArrayList<>();

        mMyRecyclerViewAdapter = new MyRecyclerViewAdapter(employees);

        recyclerView.setAdapter(mMyRecyclerViewAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
    }

    private class MyJSONTask extends AsyncTask<Void, Void, String>
    {
        //Web URL of the JSON file
        String jsonURL = "https://api.myjson.com/bins/14j37k";

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            if (mLoading != null)
            {
                mLoading.setVisibility(View.VISIBLE);
            }
        }

        @Override
        protected String doInBackground(Void... voids)
        {
            HttpURLConnection urlConnection = null;
            BufferedReader bufferedReader = null;

            try
            {
                //---Loading JSON from the Web URL---//
                URL url = new URL(jsonURL);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();


                InputStream inputStream = urlConnection.getInputStream();

                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                StringBuffer stringBuffer = new StringBuffer();

                String line;

                while ((line = bufferedReader.readLine()) != null)
                {
                    stringBuffer.append(line).append("\n");
                }
                if (stringBuffer.length() == 0)
                {
                    return null;
                } else
                {
                    return stringBuffer.toString();
                }
            } catch (IOException e)
            {
                return null;
            } finally
            {
                if (urlConnection != null)
                {
                    urlConnection.disconnect();
                }
                if (bufferedReader != null)
                {
                    try
                    {
                        bufferedReader.close();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        protected void onPostExecute(String jsonStr)
        {
            super.onPostExecute(jsonStr);

            if (jsonStr != null)
            {
                //---Parsing JSON---//
                ArrayList<Employee> employeesList = new ArrayList<>();
                try
                {
                    JSONObject rootJsonObject = new JSONObject(jsonStr);

                    JSONArray employeeJsonArray = rootJsonObject.getJSONArray("employee");

                    for (int i = 0; i < employeeJsonArray.length(); i++)
                    {
                        //Create a temp employee object
                        Employee aEmployee = new Employee();

                        JSONObject jsonObject = employeeJsonArray.getJSONObject(i);

                        //Get employee details
                        aEmployee.setName(jsonObject.getString("name"));
                        aEmployee.setGender(jsonObject.getString("gender"));
                        aEmployee.setAge(jsonObject.getInt("age"));

                        //add to list
                        employeesList.add(aEmployee);
                    }

                    if (employeesList.size() > 0)
                    {
                        //Replace RecyclerView Adapter Data
                        mMyRecyclerViewAdapter.updateData(employeesList);
                    }

                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
            if (mLoading != null)
            {
                mLoading.setVisibility(View.GONE);
            }
        }
    }
}
Display JSON Data In the RecyclerView
Display JSON Data in the RecyclerView

Happy coding!

Leave a Reply