Wednesday, July 24, 2013

JSON Parser Example(Reading data from JSON and displaying in custom ListView)

Create a folder name raw, in res folder of your project.
inside the raw folder create a file address.json and paste the following code....


res->raw->address.json
-----------------------------
{
    "contacts": [
        {
                "id": "k001",
                "name": "Kundan Kumar",
                "email": "kk@gmail.com",
                "address": "Bangalore - karnataka",
                "gender" : "male",
                "phone": "8123561470"
        },
        {
                 "id": "S001",
                "name": "Sangam Kumar",
                "email": "ss@gmail.com",
                "address": "India",
                "gender" : "male",
                "phone": "08123565560"
               
        }
   
  ]
}


activity_main.xml
---------------------
<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"
 
    tools:context=".MainActivity"
    android:background="@drawable/bg">

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#990000"
        android:dividerHeight="1dip"
        android:paddingTop="5dip">
    </ListView>

</LinearLayout>


image_view.xml
-------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="19dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/phoneView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nameView"
        android:layout_below="@+id/nameView"
        android:text="Phone" />

    <TextView
        android:id="@+id/nameView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/imageView1"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>


MainActivity.java
---------------------
package com.kundan.jsonexample;

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

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

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;

public class MainActivity extends Activity {
ListView lv;
String jsonstr=null;
String[] nameID;
String[] phoneID;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.listView1);
try {
InputStream in=getResources().openRawResource(R.raw.address);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=br.readLine())!=null){
sb.append(line+"\n");
}
jsonstr=sb.toString();
Log.d(this.toString(), jsonstr);
//System.out.println(jsonstr);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
JSONObject jobj=new JSONObject(jsonstr);
//System.out.println(jobj);
JSONArray jarray=jobj.getJSONArray("contacts");
//System.out.println(jarray);
//JSONObject jobj1=jarray.getJSONObject(0);
//System.out.println(jobj1);
nameID=new String[jarray.length()];
phoneID=new String[jarray.length()];
JSONObject jobject=null;
for(int i=0;i<=jarray.length();i++){
jobject=jarray.getJSONObject(i);
//System.out.println(jobject.getString("name"));
//System.out.println(jobject.getString("phone"));
nameID[i]=jobject.getString("name");
phoneID[i]=jobject.getString("phone");
}
} catch (Exception e) {
 Log.e("JSON Parser", "Error parsing data " + e.toString());
}
lv.setAdapter(new MyImageAdapter(this,nameID,phoneID));
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "clicked:"+nameID[position], Toast.LENGTH_SHORT).show();
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

MyImageAdapter.java
-------------------------
package com.kundan.jsonexample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

public class MyImageAdapter extends BaseAdapter {
String[] nameID;
String[] phoneID;
Context context;
public MyImageAdapter(Context context, String[] nameID,String[] phoneID) {
this.context=context;
this.nameID=nameID;
this.phoneID=phoneID;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return nameID.length;
}

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.image_view, parent,false);
TextView name=(TextView) rowView.findViewById(R.id.nameView);
TextView phone=(TextView) rowView.findViewById(R.id.phoneView);
ImageView iv=(ImageView) rowView.findViewById(R.id.imageView1);
name.setText(nameID[position]);
phone.setText(phoneID[position]);
String str1=nameID[position];
if(str1.startsWith("Kundan Kumar")){
iv.setImageResource(R.drawable.fb);
}
if(str1.startsWith("Sangam Kumar")){
iv.setImageResource(R.drawable.tw);
}
return rowView;
}

}





No comments:

Post a Comment