Monday, April 28, 2014

Simple JSON parsing

Example to parse data from a simple JSON fromat
From the URL : "http://yourwebsite.com/getCities";
{  //JSON Object
"list":[ //JSON Array
{"name":"Hyderabad"},
{"name":"Mumbai"},
{"name":"Delhi"} 
//JSON Array
//JSON Object

Now check the following code,
1.ListActivty
2.ParserClass
3.ServiceHandlerClass
4.Pojo Class
And List, Row XML layouts

package com.example.testapp;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.parsing.Parsing;
import com.parsing.Pojo;

public class ListActivity extends Activity {
ListView list;
MyAdapter mAdapter = new MyAdapter();
LoadData load = new LoadData();

ArrayList<Pojo> listObj;
//JsonParsing parser = new JsonParsing();
Parsing parser = new Parsing();

String mUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
list = (ListView) findViewById(R.id.listView);

mUrl = "http://urdomain.com/getCitiesService";

// { "list":[{"name":"Hyderabad"},{"name":"Mumbai"},{"name":"Delhi"} ] }

load.execute();

}

class LoadData extends AsyncTask<Void, Void, Void> {

ProgressDialog dialog;

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(ListActivity.this, "Getting Data...",
"Plz Wait....");
dialog.setCancelable(true);
dialog.show();
}

@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
listObj = parser.getList(mUrl);
return null;
}

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (listObj != null && listObj.size() != 0) {
// Log.e("MyLog", movielistArray.toString());
list.setAdapter(mAdapter);
}
dialog.dismiss();
}
}

class MyAdapter extends BaseAdapter {

TextView name;

public int getCount() {
// TODO Auto-generated method stub
return listObj.size();
}

public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
LayoutInflater inf = (LayoutInflater) getSystemService(ListActivity.LAYOUT_INFLATER_SERVICE);

v = inf.inflate(R.layout.row, null);
name = (TextView) v.findViewById(R.id.name);
name.setText(listObj.get(position).getName());
return v;
}

}
}

// PARSING CLASS

package com.parsing;

import java.util.ArrayList;

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

import android.util.Log;

public class Parsing {

private static final String TAG = "SearchResultsParser";

Pojo data_pojo;
ArrayList<Pojo> dataArray1 = new ArrayList<Pojo>();

// method to parse the given JSON object by taking the url of the JSON as
// argument
public ArrayList<Pojo> getList(String url) {

url = url.replace(" ", "%20");

try {

ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

Log.d("Response: ", "> " + jsonStr);

if (jsonStr != null) {

JSONObject json = new JSONObject(jsonStr);

JSONArray array1 = json.getJSONArray("list");

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

JSONObject jsonObject1 = null;
try {
jsonObject1 = array1.getJSONObject(i);
data_pojo = new Pojo(jsonObject1.getString("name"));
dataArray1.add(data_pojo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Log.d("array size>>>>>>>>>>>", "Date"
+ dataArray1.get(0).getName());
Log.d("array size>>>>>>>>>>>", dataArray1.size() + "");

}
} catch (Exception e) {
Log.d(TAG, e.toString());
}

return dataArray1;

}
}

//POJO CLASS
package com.parsing;

public class Pojo {

private String name;

public String getName() {
return name;
}

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

public Pojo(String name) {
this.name = name;
}
}

// SERVICE HANDLER Class

package com.parsing;
import java.io.IOException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class ServiceHandler {
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;
    public ServiceHandler() {
    }
    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }
    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
             
            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }
                httpResponse = httpClient.execute(httpPost);
            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);
                httpResponse = httpClient.execute(httpGet);
            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
         
        return response;
    }
}

//List XML Layout

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

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

</LinearLayout>


// row XML layout

<?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="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="row name"
        android:textSize="18sp"
        android:textColor="#ff1100" />

</LinearLayout>

//ManifestFILE
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testapp.ListActivity"
            android:label="@string/title" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

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

</manifest>