Thursday, 7 January 2016

JSON Parsing Android

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.ParseException;
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 NewsHandelar {

public static String ResponceStr;
public static final int GET = 1;
public static final int POST = 2;


public NewsHandelar()
{

}
public String MakeSystemCall(String url, int Method) {

return this.MakeSystemCall(url, Method, null);
}
private String MakeSystemCall(String url, int method, List<NameValuePair> param) {

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 (param != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(param));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (param != null) {
                    String paramString = URLEncodedUtils
                            .format(param, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            ResponceStr = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
       
        return ResponceStr;

    }
}







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

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

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends ListActivity {

ProgressDialog pDialog;
public static final String Url="http://mfeeds.timesofindia.indiatimes.com/Feeds/jsonfeed?newsid=3947071&amp;amp;format=simplejson";
public static String NewsMl="NewsML";
public static String HEAD_LINES="HeadLine";
public static String DATE_LINE="DateLine";
JSONArray NEWSML;
ArrayList<HashMap<String, String>> NewsShow;
ListView li;


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

NewsShow=new ArrayList<HashMap<String,String>>();
li=getListView();
new GetAllNews().execute();
}

public class GetAllNews extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected Void doInBackground(Void... params) {

NewsHandelar NH=new NewsHandelar();
// Log.i("All Details", "In DoinBackground");
String JsonStr=NH.MakeSystemCall(Url, NewsHandelar.GET);
if(JsonStr!=null)
{
try {
JSONObject jsonObject=new JSONObject(JsonStr);
//Log.i("All Details", String.valueOf(jsonObject));
NEWSML=jsonObject.getJSONArray(NewsMl);
for(int i=0;i<NEWSML.length();i++)
{
JSONObject NewsLines=NEWSML.getJSONObject(i);
//Log.i("All Details", String.valueOf(NewsLines));
JSONObject FinalNews=NewsLines.getJSONObject("NewsLines");
//Log.i("All Details", String.valueOf(FinalNews));
String Header=FinalNews.getString(HEAD_LINES);
String Footer=FinalNews.getString(DATE_LINE);
Log.i("Header and Footer", Header + Footer);
HashMap<String, String> Newslist=new HashMap<String, String>();
Newslist.put(HEAD_LINES, Header);
Newslist.put(DATE_LINE, Footer);
NewsShow.add(Newslist);

Log.i("All Details", String.valueOf(NewsShow));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(pDialog.isShowing())
pDialog.dismiss();
ListAdapter Adapter=new SimpleAdapter(MainActivity.this, NewsShow, R.layout.news_row, new String[]{HEAD_LINES, DATE_LINE}, new int[]{R.id.textView1, R.id.textView2});
setListAdapter(Adapter);
}
}

}




news_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="match_parent"
    android:orientation="vertical" >
<TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" 
        android:text="Text1"/>
 
    <!--Date Info -->
    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="#acacac"
        android:text="Text2" />

</LinearLayout>



activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView 
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
 

   
</LinearLayout>


No comments:

Post a Comment