How to Parse JSON in Android Example

How to Parse JSON in Android Example

In this android code snippet tutorial, we are going to learn how to parse JSON in android application development.

JSON stands for JavaScript Object Notation and is use for data interchange between android application and a server.

A more detailed definition was taken from JSON website – “JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999”.

Android provides different classes that can be used to manipulate JSON. The classes are as follow:-JSONArray, JSONObject, JSONStringer and JSONTokenizer.

To further understand how a typical JSON object or Array can look like, the code pasted below shows a detailed information about JSON object.

{
"African_Music" :
[
{
"song_name":"Hero",
"song_id":"1990",
"artist_name":"Enrique"
},
{
"song_name":"African Queen",
"song_id":"2004",
"artist_name":"Tuface"
},
{
"song_name":"Ifunanyi",
"song_id":"2012",
"artist_name":"PSquare"
}
]
}

Important thing to note from the above JSON is the use of “{}” and “[]”. The curly bracket is used to represent an object in JSON while the square bracket is used to represent an array.

There are many other important method that is available to access and manipulate JSON object. The list is shown below

getString(String name) – This method just Returns the value but in the form of Object type

getBoolean(String name) – This method returns the boolean value specified by the key

getDouble(String name) – This method returns the double value specified by the key

getInt(String name) – This method returns the integer value specified by the key

getLong(String name) – This method returns the long value specified by the key

length() – This method returns the number of name/value mappings in this object

names() – This method returns an array containing the string names in this object.

In order to parse JSON object from a server source, we are going to need internet access for this file.

It is important to note that when you are working with internet or accessing data from a remote source in android, you will need to add internet permission in your android manifest file.

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

We are going to use android API for HTTP request to request for the JSON. Once we get the Json file as an InputStream, we will convert it to a string. The string object will be pass as a parameter to an instance of JsonObject class.

We will use an AsyncTask class to make make server calls in a background Thread. This is important so that will not end up blocking the main UI Thread.

The data that will be obtained from a remote Json file will be used to populated a ListView with the help of a custom Adapter.

Before we start, the first thing I will do is to list the environment and tools I used in this android code snippet but feel free to use whatever environment or tools you are familiar with.

Windows 7

Android Studio

Samsung Galaxy Fame Lite

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: ParseJsonInAndroid

Package: com.inducesmile.parsejsoninandroid

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

Once you are done with creating your project, make sure you change the package name if you did not use the same package.

Main Layout

We will start by adding an ListView in our activity_main.xml layout file. If you are using Eclipse or Android Studio, you can switch to the design view and drag and drop this View inside your layout file.

You can also copy and paste the following code below into this file if you don’t want to do it yourself.

<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentStart="true" />

</RelativeLayout>

Since we will make use of a custom adapter to bind the Json data to a ListView, we will create a custom adapter that takes a List object as one of its parameters. The List object will wrap objects of ItemObject class which contains all the elements of Json Array.

The code for the custom adapter is shown below

package inducesmile.com.parsejsoninandroid;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;

public class CustomAdapter extends BaseAdapter {

private LayoutInflater lInflater;
private List<ItemObject> listStorage;
public CustomAdapter(Context context, List<ItemObject> customizedListView) {
lInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
}

@Override

public int getCount() {

return listStorage.size();

}

@Override

public Object getItem(int position) {

return position;

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder listViewHolder;

if(convertView == null){

listViewHolder = new ViewHolder();

convertView = lInflater.inflate(R.layout.list, parent, false);

listViewHolder.songName = (TextView)convertView.findViewById(R.id.textView);

listViewHolder.songYear = (TextView)convertView.findViewById(R.id.textView2);

listViewHolder.songAuthor = (TextView)convertView.findViewById(R.id.textView3);

convertView.setTag(listViewHolder);

}else{

listViewHolder = (ViewHolder)convertView.getTag();

}

listViewHolder.songName.setText("Song Name: " + listStorage.get(position).getSongName());

listViewHolder.songYear.setText("Song Year: " + listStorage.get(position).getSongYear());

listViewHolder.songAuthor.setText("Song Author: " + listStorage.get(position).getSongAuthor());

return convertView;

}
static class ViewHolder{

TextView songName;

TextView songYear;

TextView songAuthor;
}
}

As you can seen, the List class uses an ItemObject as its value type. We are going to create this object with three different attributes, get and set methods for these attributes. The code is shown below.

package inducesmile.com.parsejsoninandroid;

public class ItemObject {

private String songName;
private String songYear;
private String songAuthor;

public ItemObject(String songName, String songYear, String songAuthor) {
this.songName = songName;
this.songYear = songYear;
this.songAuthor = songAuthor;
}

public String getSongName() {
return songName;
}

public void setSongName(String songName) {
this.songName = songName;
}

public String getSongYear() {
return songYear;
}

public void setSongYear(String songYear) {
this.songYear = songYear;
}

public String getSongAuthor() {
return songAuthor;
}

public void setSongAuthor(String songAuthor) {
this.songAuthor = songAuthor;
}
}

When we created the custom adapter, we inflated a layout. The layout is a custom layout that is used to design the interface of each item of the ListView component. In our case, we added three TextViews to hold song name, song year and song author. The code snippet is as shown below.

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:textSize="18dp"
android:textColor="#df4510"
android:id="@+id/textView" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView2"
android:textColor="#000"
android:layout_below="@+id/textView"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"
android:layout_marginTop="20dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView3"
android:textColor="#000"
android:layout_marginRight="10dp"
android:layout_alignTop="@+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

</RelativeLayout>

We have added internet permission in our manifest file. The complete code is shown below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="inducesmile.com.parsejsoninandroid" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

 MainActivity.java

In the MainActivity.java file, we will obtain an instance of the ListView. To make a request to our remote server, create an AsyncTask class. The doInBackground method of the class is where are server request and response codes live. The returned response is then pass to the onPostExecute method.

In this method, the ListView object setAdapter method takes an instance of our created custom adapter. The whole code is shown below

package inducesmile.com.parsejsoninandroid;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
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.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {

private ListView songList;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

songList = (ListView)findViewById(R.id.listView);

AsynDataClass jsonAsync = new AsynDataClass();

jsonAsync.execute("");

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

}
return super.onOptionsItemSelected(item);

}

private class AsynDataClass extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {

// TODO Auto-generated method stub

HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

HttpPost httpPost = new HttpPost("http://toscanyacademy.com/blog/download/content.json");

String jsonResult = "";

try {

HttpResponse response = httpClient.execute(httpPost);

jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

System.out.println("Returned Json object " + jsonResult.toString());

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return jsonResult;

}

@Override

protected void onPreExecute() {

// TODO Auto-generated method stub

super.onPreExecute();

}

@Override
protected void onPostExecute(String result) {

super.onPostExecute(result);

System.out.println("Resulted Value: " + result);

List<ItemObject> parsedObject = returnParsedJsonObject(result);

CustomAdapter jsonCustomAdapter = new CustomAdapter(MainActivity.this, parsedObject);

songList.setAdapter(jsonCustomAdapter);

}

private StringBuilder inputStreamToString(InputStream is) {

String rLine = "";

StringBuilder answer = new StringBuilder();

BufferedReader br = new BufferedReader(new InputStreamReader(is));

try {

while ((rLine = br.readLine()) != null) {

answer.append(rLine);

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return answer;

}

}

private List<ItemObject> returnParsedJsonObject(String result){

List<ItemObject> jsonObject = new ArrayList<ItemObject>();

JSONObject resultObject = null;

JSONArray jsonArray = null;

ItemObject newItemObject = null;

try {

resultObject = new JSONObject(result);

System.out.println("Testing the water " + resultObject.toString());

jsonArray = resultObject.optJSONArray("African_Music");

} catch (JSONException e) {

e.printStackTrace();

}

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

JSONObject jsonChildNode = null;

try {

jsonChildNode = jsonArray.getJSONObject(i);

String songName = jsonChildNode.getString("song_name");

String songYear = jsonChildNode.getString("song_id");

String songAuthor = jsonChildNode.getString("artist_name");

newItemObject = new ItemObject(songName, songYear, songAuthor);

jsonObject.add(newItemObject);

} catch (JSONException e) {

e.printStackTrace();

}

}

return jsonObject;

}

}

Save the file and run your project. If everything works for you, this image will appear on your test device.

jsonparse

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published.

OTHER INTERESTING POSTS:

No Responses

Add a Comment