JSON in Android @AndroidMonk

WiseL Teach
WiseLTeach
Published in
4 min readJan 2, 2017

This tutorial is mainly designed for beginners in android. JSON in android is a very common and easy topic to learn.

Prerequisite: Learning JSON in 2 mins@AndroidMonk

In this tutorial we will create and android app and one JSON file. We will extract the information from the JSON file and show that in our android app.

JSON file contains the list of movies. GitHub link for file: here

Download this file of create a similar file using any text editor.

Starting Steps

  • Create new android project. New -> New Project -> Name this project as “JSON Parsing” -> Next -> Next-> Next-> Finish.
  • Create an assets folder in project. Right Click on ‘app’ in ‘Android’ Project Panel (as shown below). New-> Folder-> Assets Folder-> Finish.
  • Copy the moviesData.json file from your computer and paste it inside assets folder.

Working with UI

We will show the data inside a listview and a textview.

  • XML code for main_activity.xml
<?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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<!--It will show author details-->
<TextView
android:id="@+id/tvAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="22sp"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:layout_margin="16dp"
android:padding="16dp"
android:background="@color/colorPrimary"
/>

<!--It will contain the details of movies-->
<ListView
android:id="@+id/lvMovies"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tvAuthor"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
/>

</RelativeLayout>
  • Create new xml file named item_movies.xml inside layout folder which will define the layout of each movie row.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
>

<!--It will display movie name-->
<TextView
android:id="@+id/tvMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorPrimary"
android:textSize="22sp"
android:textStyle="bold"
/>

<!--It will display year-->
<TextView
android:id="@+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorAccent"
android:textSize="18sp"
android:textStyle="bold"
/>

<!--It will display rating-->
<TextView
android:id="@+id/tvRating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#424242"
android:textSize="18sp"
android:textStyle="bold"
/>

</LinearLayout>

Writing Java Code

Code for MainActivity.java

package com.wiselteach.jsonparsing;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

TextView tvAuthorDetails;
ListView lvMovies;

// This array list will be used to store movies data temporarily and then pass that to listview.
ArrayList<HashMap<String, String>> moviesArrayList = new ArrayList<>();

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

tvAuthorDetails = (TextView) findViewById(R.id.tvAuthor);
lvMovies = (ListView) findViewById(R.id.lvMovies);

String fileData = ReadFromFile("moviesData.json");

ConvertStringToJSON(fileData);

}

public String ReadFromFile(String fileName) {
//Creating objects
StringBuilder returnString = new StringBuilder();
InputStream inputStream = null;
InputStreamReader inputSteamReader = null;
BufferedReader reader = null;
try {
inputStream = this.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
inputSteamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputSteamReader);
String line = "";
while ((line = reader.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
//Error Handling
try {
if (inputSteamReader != null)
inputSteamReader.close();
if (inputStream != null)
inputStream.close();
if (reader != null)
reader.close();
} catch (Exception e2) {
e2.getMessage();
}
}

//Return the output in string format
return returnString.toString();
}

private void ConvertStringToJSON(String fileData) {
//NOTE: For '{' we use JSON Object and for '[' we use JSON Array

try {
JSONObject completeData = new JSONObject(fileData);
JSONObject moviesData = completeData.getJSONObject("movieData");
JSONObject authorData = completeData.getJSONObject("authorData");

//Using authorData Object to identify values from keys.
String authorName = authorData.getString("name");
String company = authorData.getString("company");
String website = authorData.getString("website");
tvAuthorDetails.setText(authorName + "\n" + company + "\n" +website);

//Using movieData Object and setting data in list.
JSONArray moviesList = moviesData.getJSONArray("moviesList");

//Running loop for each array item
for(int i = 0; i<moviesList.length(); i++){
//Fetching data for each movie from object
JSONObject currentMovieData = moviesList.getJSONObject(i);

String name = currentMovieData.getString("movieName");
String year = currentMovieData.getString("year");
String rating = currentMovieData.getString("rating");

HashMap<String,String> movies = new HashMap<>();
movies.put("name", name);
movies.put("year",year);
movies.put("rating",rating);

moviesArrayList.add(movies);
}

//Now we have completely read the json file
//we will use the array list to display data in listview

ListAdapter adapter = new SimpleAdapter(
MainActivity.this, // Context of the activity
moviesArrayList, // ArrayList containing data
R.layout.item_movies, // Layout which we will use to display data
new String[]{"name", "year", "rating"}, // Keys of hashmap to get values
new int[]{R.id.tvMovie, R.id.tvYear, R.id.tvRating} // Set values to textview accordingly.
);

lvMovies.setAdapter(adapter);

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

}

Output

Now you can easily us JSON parsing and listview anywhere in android.

Do add suggestions in comments section.

#AndroidMonk

#WiseLTeach

#WiseL

--

--

WiseL Teach
WiseLTeach

Personalized digital learning solutions that provides assistance to students and teachers.