Tuesday 16 June 2015

JSON Parsing

Hello all,

In the Previous Post , we have discussed about the soap parsing and now I am sharing the code to parse the json api and showing the response in the listview

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This post explains how to parse the JSON file and extract necessary information from it.

I have made a json api using  the json-generator ,the response of the api is something like this:

{
    "contacts": [
        {
                "id": "c200",
                "name": "Kate Winslet",
                "email": "Kate@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        .
        .
  ]
}


Now let's move to parse this response.
First I have made a class which is used to connect with the server.
and I have made another class which is used to check the internet connection
I have made a class named ConnectionDetector.java to check the internet connection:

public class ConnectionDetector { private Context _context; public ConnectionDetector(Context context){ this._context = context; } public boolean isConnectingToInternet(){ ConnectivityManager connectivity = (ConnectivityManager)_context
.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } return false; } }

Now I have made another class named JSONParser.java which is used for connection with the server:


import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { private InputStream is = null; private JSONObject jObj = null; private String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); Log.e("JSON", json); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } public JSONObject getJSONFromUrl(String url) throws IllegalStateException, IOException, JSONException { // Making HTTP request // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); // try parse the string to a JSON object jObj = new JSONObject(json); // return JSON String return jObj; } }

Now let's move to the layout designing ,I am showing the response in the listview
,so I have made a list and a row which is used to design the single row of the listview.

I have made a layout named first.xml ,having the listview :

<?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"
    android:orientation="vertical" 
    android:background="#FFFFFF">

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
         >
    </ListView>

</RelativeLayout>

And another layout ,having a textview to show the single row of the above listview,
I have named it row.xml

<?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="30sp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="#000000"
        android:layout_margin="5sp"/>

</LinearLayout>

Now lets move to the main activity haivng the code for parsing,
 FirstActivity.java :

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.adapter.FirstAdapter;
import com.json.libs.ConnectionDetector;
import com.json.libs.JSONParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

public class FirstActivity extends Activity{
ListView list;
ProgressDialog dlg;
ArrayList<HashMap<String,String>> Show = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
list = (ListView)findViewById(R.id.listView1);
InItAction();
}

private void InItAction() {
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
if (cd.isConnectingToInternet()) {
new AsyncTaskLoad().execute();
}
else{
Toast.makeText(getApplicationContext(),"Interent not available!",Toast.LENGTH_LONG).show();
}
}
class AsyncTaskLoad extends AsyncTask<String,String,String>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
if (Build.VERSION.SDK_INT >= 11 ) {
  dlg = new ProgressDialog(FirstActivity.this,AlertDialog.THEME_HOLO_LIGHT );
     } else {
        dlg = new ProgressDialog(FirstActivity.this);
       }
       dlg.setMessage("Loading...");
       dlg.show();
}
@Override
protected String doInBackground(String... params) {
Show = new ArrayList<HashMap<String,String>>();
JSONParser jParser = new JSONParser();
try {
JSONObject json= jParser.getJSONFromUrl("http://www.json-generator.com/api/json/get/cdulwxdjkO?indent=2");
JSONArray jAry = json.getJSONArray("contacts");
for (int i = 0; i < jAry.length(); i++) {
JSONObject c  = jAry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address =c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String,String> map = new HashMap<String, String>();
map.put("id",id);
map.put("name",name);
map.put("email",email);
map.put("address",address);
map.put("gender",gender);
map.put("mobile",mobile);
map.put("home",home);
map.put("office",office);
Show.add(map);
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dlg.dismiss();
if (Show.size()==0) {
list.setAdapter(null);
Toast.makeText(getBaseContext(),"no contacts!!",Toast.LENGTH_LONG).show();
}
else
{
FirstAdapter adapter = new FirstAdapter(FirstActivity.this,Show);
list.setAdapter(adapter);
}
}
}
}


Now I have made an adapter which is used to set on listview 
,named as FirstAdapter.java :

import java.util.ArrayList;
import java.util.HashMap;
import com.blogdemo.R;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class FirstAdapter extends BaseAdapter{

Activity activity;
ArrayList<HashMap<String, String>> Show = new ArrayList<HashMap<String,String>>();
ViewHolder holder ;
public FirstAdapter(Activity mactivity,
ArrayList<HashMap<String, String>> show) {
this.activity = mactivity;
this.Show = show;
}

@Override
public int getCount() {
return Show.size();
}

@Override
public Object getItem(int position) {
return Show.get(position);
}

@Override
public long getItemId(int position) {
return Show.size();
}
private class ViewHolder {
public TextView txt;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mLayoutInflater = LayoutInflater.from(activity);
convertView = mLayoutInflater.inflate(R.layout.row,
null);
       holder = new ViewHolder();
holder.txt = (TextView)convertView.findViewById(R.id.textView1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt.setText("id: "+Show.get(position).get("id")+" \n"
   +"Name: "+Show.get(position).get("name")+" \n"+"Email:"+Show.get(position).get("email"));
return convertView;
}
}

Also,

Please do not forgot to add the following permission in the menifest file:

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

Following is the screen shot of the response of the used api :  






Screen shot of the response of a JSON api
 ,showing in the listview 














That's all ,this is the post for parsing the JSON API,
Please leave a comment ,if you have any query regarding to this post.
 happy coding :)

No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...