Android JSON Parsing

ANDROID JSON2

Android JSON Parsing

This is a post explaining the use of JSON in android application. You can GOOGLE JSON to know its definition and all other stuff related to that. So far I have seen the use of JSON in some android application but couldn’t find a good example for using it the application itself. So I made a application using JSON to fetch data into my application both locally and through network services myself.
OK.

ANDROID JSON 1

What does basically JSON means :

JSON stands for JavaScript Object Notation, is a minimal, readable format for structuring data. Its easy to read and write for us human and easy to parse for machines. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. It is used in ASP.NET, PHP, JAVA websites and android applications, iOS applications.

APPLICATION :

The application will be parsing JSON data from both server and a locally stored file itself. Do comment below what do you think about the application whether its bad or good, I appreciate your time you are spending reading this post.

First make a new android application in android studio and named it whatever you want to name it. After making it open your res > layout folder and make a new layout xml file with name js.xml [you can name it according to your wish]. This file will be used to show our data parsed from local file and the http file.
Now edit the file as below :

<LinearLayout 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:orientation="vertical"
android:background="#252525"
tools:context=".ParseXmlAndroidExample">

<TextView
android:id="@+id/lblinfo"
android:paddingTop="10px"
android:textColor="#e67e22"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:textStyle="bold"
android:text="ParallelCodes.com" />

<Button
android:id="@+id/btnparse"
android:text="Click to Parse JSON Data"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="wrap_content"></Button>

<TextView
android:paddingTop="10px"
android:textColor="#1abc9c"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:textStyle="bold"
android:text="Movies to watch : " />

<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>

</LinearLayout>

You will understand its working as its too easy to.

Make an another layout XML file and edit it as following :

jslist.xml

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#252525"
android:orientation="vertical">

<TextView
android:id="@+id/lblmoviename"
android:textColor="#e74c3c"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:text="Movie name here" />

<TextView
android:id="@+id/lblcategory"
android:textColor="#3498db"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:text="Movie category hehre" />
</LinearLayout>

This file will make our list preview.

Make a new menu folder in res folder res> menu if its not present in your project.
Now make a new menu file in it named : menu_main.xml

res > menu > menu_main.xml :

<menu 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"
tools:context=".MainActivity">
<item
android:id="@+id/otheractivity"
android:title="OTHER ACTIVITY"
android:orderInCategory="100"
app:showAsAction="always|withText" />
</menu>

To store that local JSON file to parse data make a new folder named assets in your project
[yourprojectname > app > src > main > assets] and make new file with named json.txt in it and edit it as following :

json.txt

{ "Movies" :
[
{"Movie" : "Inception" , "Category" : "Thriller"},
{"Movie" : "Interstellar", "Category" : "Sci-Fi Thriller"},
{"Movie" : "A Walk to remember", "Category" : "Romance"},
{"Movie" : "P.S. I Love You", "Category" : "Romance"},
{"Movie" : "The fault in Our Stars", "Category" : "Romance"},
{"Movie" : "The Conjuring", "Category" : "Horror"},
{"Movie" : "Hangover Part-III", "Category" : "Comedy"},
{"Movie" : "Warrior", "Category" : "Drama"},
{"Movie" : "Million Dollar Baby" , "Category" : "Drama"},
{"Movie" : "The Silence of the lambs" , "Category" : "Thriller"},
{"Movie" : "Source Code", "Category" : "Sci-fi, Thriller"},
{"Movie" : "Indigenous" , "Category" : "Suspense, Thriller"},
{"Movie" : "Friends with Benefits", "Category" : "Romance, Comedy"}
]}

Ok now the coding part. Its a long post.

CODING PART : 

Make three files in your class folder as

  1. JSONActivity.java
  2. JSONActivityLocal.java
  3. JSONParser.java

JSONActivity.java

package hitesh.androidjsonapp;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by abc on 26-Jun-15.
*/
public class JSONActivity extends ActionBarActivity {

private Context context;
private static String url = "https://parallelcodes.com/wp-content/uploads/2015/06/movies2.txt";
TextView lblinfo;
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView list;
Button btn;
List<Map<String, String>> moviedata;
ConnectivityManager cm;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.js);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
lblinfo = (TextView) findViewById(R.id.lblinfo);
lblinfo.setText("JSON from HTTP File");
list = (ListView) findViewById(R.id.list);
btn = (Button) findViewById(R.id.btnparse);
moviedata = new ArrayList<Map<String, String>>();

btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
if (activeNetworkInfo != null)
Parser();
else {
Toast.makeText(JSONActivity.this, "No Internet connectivity. Please Check your Internet Connection.", Toast.LENGTH_LONG).show();
}
}
}
);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
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();
if (id == R.id.otheractivity) {
Intent i = new Intent(JSONActivity.this, JSONActivityLocal.class);
startActivity(i);
finish();
return true;
}

return super.onOptionsItemSelected(item);
}

public void Parser() {
JSONParser jParser = new JSONParser(); // get JSON data from URL
JSONArray json = jParser.getFromURL(url);
int j = json.length();
try {

for (int i = 0; i < j; i++) {
Map<String, String> moviemap = new HashMap<String, String>();
JSONObject jsonChildNode = json.getJSONObject(i);

String movie = jsonChildNode.optString("Movie").toString();
String category = jsonChildNode.optString("Category").toString();

moviemap.put("A", movie);
moviemap.put("B", category);

moviedata.add(moviemap);
}
String[] from = {"A", "B"};
int[] views = {R.id.lblmoviename, R.id.lblcategory};
final SimpleAdapter myadapter = new SimpleAdapter(JSONActivity.this, moviedata, R.layout.jslist, from, views);
list.setAdapter(myadapter);
Toast.makeText(JSONActivity.this, "Data fetched from " + url, Toast.LENGTH_LONG).show();

} catch (JSONException e) {
Toast.makeText(JSONActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}

}
}

JSONParser.java

package hitesh.androidjsonapp;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
* Created by abc on 29-Jun-15.
*/
public class JSONParser {
InputStream inputStream;
JSONArray jsonArray;
String data;

StringBuilder sb;
HttpClient client;
HttpGet httpGet;
HttpResponse response;
StatusLine statusLine;
int statuscode;

public JSONParser() {
}

public JSONArray getFromURL(String url) {
sb = new StringBuilder();
client = new DefaultHttpClient();
httpGet = new HttpGet(url);

try {
response = client.execute(httpGet);
statusLine = response.getStatusLine();
statuscode = statusLine.getStatusCode();
if (statuscode == 200) {
HttpEntity httpentity = response.getEntity();
InputStream content = httpentity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jsonArray = new JSONArray(sb.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray;

}
}

JSONActivityLocal.java

package hitesh.androidjsonapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

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.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by abc on 26-Jun-15.
*/
public class JSONActivityLocal extends ActionBarActivity {

TextView lblinfo;
Button btn;
InputStream inputstream;
BufferedReader reader;
String m;
String movie;
String category;
String title;
ListView list;
List<Map<String, String>> moviedata;
JSONArray jsonArray;
JSONObject jsonObject;

@Override
protected void onCreate(Bundle s) {
super.onCreate(s);
setContentView(R.layout.js);

lblinfo = (TextView) findViewById(R.id.lblinfo);
lblinfo.setText("JSON from Local File");
btn = (Button) findViewById(R.id.btnparse);
list = (ListView) findViewById(R.id.list);

try {
inputstream = getResources().getAssets().open("json.txt");
reader = new BufferedReader(new InputStreamReader(inputstream));

m = reader.toString();
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
m = total.toString();
} catch (IOException ex) {
Toast.makeText(JSONActivityLocal.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show();
}

btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
moviedata = new ArrayList<Map<String, String>>();

try {
jsonObject = new JSONObject(m);
jsonArray = jsonObject.optJSONArray("Movies");
int arraylength = jsonArray.length();

for (int i = 0; i < arraylength; i++) {
Map<String, String> moviemap = new HashMap<String, String>();
JSONObject jsonChildNode = jsonArray.getJSONObject(i);

movie = jsonChildNode.optString("Movie").toString();
category = jsonChildNode.optString("Category").toString();

moviemap.put("A", movie);
moviemap.put("B", category);

moviedata.add(moviemap);
}
String[] from = {"A", "B"};
int[] views = {R.id.lblmoviename, R.id.lblcategory};
final SimpleAdapter myadapter = new SimpleAdapter(JSONActivityLocal.this, moviedata, R.layout.jslist, from, views);
list.setAdapter(myadapter);
} catch (JSONException e) {
e.printStackTrace();

}

}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
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();
if (id == R.id.otheractivity) {
Intent i = new Intent(JSONActivityLocal.this, JSONActivity.class);
startActivity(i);
finish();
return true;
}

return super.onOptionsItemSelected(item);
}
}

And lastly your AndroidManifest.xml file (The Boss) :

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hitesh.androidjsonapp" >

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".JSONActivityLocal"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name=".JSONActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"/>
</application>

</manifest>

ANDROID JSON 1

 

You can download the source code here : AndroidJSONAPP


Tags:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.