X
    Categories: Beginner

Android Parsing Local Json Url || Fetching data from local URL

[et_pb_section admin_label=”section”][et_pb_row admin_label=”row”][et_pb_column type=”4_4″][et_pb_text admin_label=”Text” background_layout=”light” text_orientation=”left” use_border_color=”off” border_color=”#ffffff” border_style=”solid”]

Android app dealing with web services generally uses json links to parse the data known as json parser using with different types of libraries such as Volley Library, Retrofit and many more.

 

Parse Local Json :

Android Parsing Local Json Url will get the details from the link provided called as api, so today we will see how to Parse Local Json url locally within our app.

Sometimes when we are about to test any services we will use this type of local json url to form the complete app structure before we implement json services.

When we have to parse data to populate in a listview we send data in arraylist.

[
{
"name":"abhi","phone":9876543210},
{
"name":"ravi","phone":1234567890},
{"name":"kishore","phone":3654789120},
{"name":"vishal","phone":1234567890},
{"name":"jai","phone":5478963215}
]

for more info

 

Also we some time json is used to send a simple set of data just like user information to be displayed in profile as user name, number, age, password.

[
{
"name":"kalyan","phone":9876543210,"age":30,"email":"kalyan@email.com"}
]

 

[/et_pb_text][et_pb_video admin_label=”Video” src=”https://youtu.be/eVx8umXTL6I” image_src=”//i.ytimg.com/vi/eVx8umXTL6I/hqdefault.jpg”] [/et_pb_video][et_pb_text admin_label=”Text” background_layout=”light” text_orientation=”left” use_border_color=”off” border_color=”#ffffff” border_style=”solid”]

Create a raw json file in assets folder

Example json file

{
  "Details": [
    {
      "Name": "Rakesh",
      "Age":24
    },
    {
      "Name": "Ravi",
      "Age":22
    },
    {
      "Name": "Shyam",
      "Age":32
    },
    {
      "Name": "Vikram",
      "Age":26
    }
  ]
}

 

Then create a Pojo class also you can automatically create this class file using the json array provided the main advantage is that the time taken to create this file is reduced in terms of complex nested json array’s and efficiency in code increase

DetailsListPojo :

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class DetailsListPojo {

    @SerializedName("Details")
    @Expose
    private List<Detail> detailList = null;

    public List<Detail> getDetailList() {
        return detailList;
    }

    public void setdetailList(List<Detail> detailList) {
        this.detailList = detailList;
    }

}

 

and fetch the key values from the details list

Detail :

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Detail {

    @SerializedName("Name")
    @Expose
    private String name;
    @SerializedName("Age")
    @Expose
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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


}

 

[/et_pb_text][et_pb_text admin_label=”Text” background_layout=”light” text_orientation=”left” use_border_color=”off” border_color=”#ffffff” border_style=”solid”]

Now designing the Android Reyclerview row to Parse Local Json

activity_details_row :

Name and age of the user is shown in the list so we add two textview for the following fields as

 

<?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="15dp">

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Name"
        android:textColor="@color/black"
        android:textSize="20dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_weight="1"
        android:text="24"
        android:textSize="18dp" />

</LinearLayout>

 

Then we add recyclerview to the activity_main

activity_main :

<?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"
    tools:context="location.android.com.local_json_parsing.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/stores_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:scrollbars="vertical" />

</LinearLayout>

 

Now lets make a RecycleView Adapter

 

DetailsListAdapter :

For attaining more efficiency we can use databinding in the code

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.TextView;


import java.util.List;

import location.android.com.local_json_parsing.DetailsListPojo.Detail;

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

    private List<Detail> dataSet;
    Context context;

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView name;
        TextView age;

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

            this.name = (TextView) itemView.findViewById(R.id.name);
            this.age = (TextView) itemView.findViewById(R.id.age);
        }
    }

    public DetailsListAdapter(List<Detail> data, Context context) {
        this.dataSet = data;
        this.context = context;
    }

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


        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {


        holder.name.setText(dataSet.get(listPosition).getName());
        holder.age.setText(String.valueOf(dataSet.get(listPosition).getAge()));

    }


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

    }

}

MainActivity :

Parse the local json to fetch the user details

 public String parseJSONData() {
 String JSONString = null;
 JSONObject JSONObject = null;
 try {

 InputStream inputStream = getAssets().open("userDetail.json");

 int sizeOfJSONFile = inputStream.available();

 byte[] bytes = new byte[sizeOfJSONFile];

 inputStream.read(bytes);

 inputStream.close();

 JSONString = new String(bytes, "UTF-8");

 } catch (IOException ex) {
 ex.printStackTrace();
 return null;
 }
 return JSONString;
 }

then

 

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import location.android.com.local_json_parsing.DetailsListPojo.DetailsListPojo;

public class MainActivity extends AppCompatActivity {

    DetailsListPojo storesListProjo;
    private static RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private static RecyclerView recyclerView;

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

        recyclerView = (RecyclerView) findViewById(R.id.stores_list);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        storesListProjo = new Gson().fromJson(parseJSONData(), DetailsListPojo.class);
        adapter = new DetailsListAdapter(storesListProjo.getDetailList(), this);
        recyclerView.setAdapter(adapter);

    }

    public String parseJSONData() {
        String JSONString = null;
        JSONObject JSONObject = null;
        try {

            InputStream inputStream = getAssets().open("userDetail.json");

            int sizeOfJSONFile = inputStream.available();

            byte[] bytes = new byte[sizeOfJSONFile];

            inputStream.read(bytes);

            inputStream.close();

            JSONString = new String(bytes, "UTF-8");

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return JSONString;
    }
}

 

[/et_pb_text][et_pb_text admin_label=”Text” background_layout=”light” text_orientation=”left” use_border_color=”off” border_color=”#ffffff” border_style=”solid”]

Output :

This screen depicts how the Android Parse Local Json Url is executed

Let us know if you have any query’s on Parse Local Json tutorial in comment section below and also share our tutorial if you like for more android tutorials.

[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section]

abhishek:
Related Post

This website uses cookies.