Happy Reading ! Have a good day !

Sunday 24 May 2015

JSON Parsing in android (Full)

Posted by at 8:37:00 pm Read our previous post





API Address:
http://api.androidhive.info/contacts/

MainActivity.java contains special class: GetContact extends AsyncTask
and 3 override method:
doInBackground()
onPostExecute()
onPreExecute()

MainActivity.java:








package com.example.shoaibm.jsonparsing;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

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

import java.util.ArrayList;
import java.util.HashMap;


public class MainActivity extends ActionBarActivity {
    public  static  String url = "http://api.androidhive.info/contacts/";
    private ProgressDialog pDialogue;
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new GetContact().execute();



    }

    private class GetContact extends AsyncTask<Void, Void, Void>{



        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialogue = new ProgressDialog(MainActivity.this);
            pDialogue.setMessage("Please Wait...");
            pDialogue.setCancelable(true);
            pDialogue.show();
        }
        @Override
        protected Void doInBackground(Void... params) {

            JSONParser parser = new JSONParser();
            String text = parser.getXmlFromUrl(url);



            try{

                JSONObject jsonObject = new JSONObject(text);
                JSONArray contacts = jsonObject.getJSONArray("contacts");

                for(int i=0; i<contacts.length();i++)
                {
                    JSONObject c = contacts.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 phnObj = c.getJSONObject("phone");
                    String mobile = phnObj.getString("mobile");


                    HashMap<String, String> contact = new HashMap<String, String>();
                    contact.put("id", id);
                    contact.put("name", name);
                    contact.put("email", email);
                    contact.put("address", address);
                    contact.put("gender", gender);
                    contact.put("mobile", mobile);
                    contactList.add(contact);

                }

            }
            catch (JSONException e)
            {

            }
            return null;


        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialogue.dismiss();


            ListView lv = (ListView)findViewById(R.id.listView);
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,R.layout.list_item,
                    new String[]{"name", "email"}, new int[]{R.id.textView, R.id.textView2});
            lv.setAdapter(adapter);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String idq = contactList.get(position).get("id");
                String name = contactList.get(position).get("name");
                String email = contactList.get(position).get("email");
                String address = contactList.get(position).get("address");
                String gender = contactList.get(position).get("gender");
                String mobile = contactList.get(position).get("mobile");

                    Intent intent = new Intent(MainActivity.this, ShowDetails.class);
                    intent.putExtra("id", idq);
                    intent.putExtra("name", name );
                    intent.putExtra("email", email);
                    intent.putExtra("address", address );
                    intent.putExtra("gender", gender);
                    intent.putExtra("mobile", mobile);

                    startActivity(intent);
                }
            });

        }
    }

}


ShowDetails.Java



package com.example.shoaibm.jsonparsing;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class ShowDetails extends ActionBarActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_details);
        textView = (TextView)findViewById(R.id.textView3);

        Intent intent = getIntent();
       String id =  intent.getStringExtra("id");
        String name = intent.getStringExtra("name");
        String email = intent.getStringExtra("email");
        String address = intent.getStringExtra("address");
        String gender = intent.getStringExtra("gender");
        String mobile = intent.getStringExtra("mobile");

        textView.setText(id+"\n"+ name+"\n" +email+" \n "+address+"\n"+gender+"\n"+mobile);
    }


}



JsonParser.Java:


package com.example.shoaibm.jsonparsing;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by Shoaib M on 5/21/2015.
 */
public class JSONParser {

    public JSONParser()
    {

    }

    public String getXmlFromUrl(String url){
        String xml=null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);
        }


        catch (UnsupportedEncodingException e) {
        }
        catch (ClientProtocolException e) {
        }
        catch (IOException e) {
        }

        return xml;
    }
}


Layout/list_item.xml:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="39dp" />

</RelativeLayout>

Layout/ShowDetilsActivity.xml:




/<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="com.example.shoaibm.jsonparsing.ShowDetails">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView3"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="32dp" />
</RelativeLayout>


Manifest.xml

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





No comments:

Post a Comment

© Somewhere I Belong is powered by ULAB - designed by Shoaib Mahmud