Thursday, 19 December 2013

JSON Parsing Android Beginners

Android JSON Parsing Example 

JSON Parsing in Android
(Without using Asynctask)

JSON is an easy way to parse and access data stored in JSON format. In this tutorial you can see how to parse JSON in android. Before going to program, let’s see JSON format type. JSON format is two types:
      1.    Object Type
      2.    Array Type.
     An Example:  
Object Type JSON:
   {
    'name' : 'Tara',
    'phone' : 123456789
   };

Array Type JSON:
  [
      {
         ‘name' : 'Tara',
         'phone' : 123456789
      },
      {
         ‘name' : 'Tara',
         'phone' : 123456789
      },
        .
        .
        .
    ];

In this tutorial, I am taking an example of following JSON which will give you list of News and each “NewsLines” have different Head-Lines and Date-Lines. You can get this JSON by accessing  http://mfeeds.timesofindia.indiatimes.com/Feeds/jsonfeed?newsid=3947071&format=simplejson 


If you observe carefully, you can see { and ]. The main difference between these two is object and array. Curly bracket { represents JSONObject and Square bracket [ represents JSONArray.


Now we will create Parser class. This parser class is used to execute the JSON link and get the JSON data and returns JSON Object.
public class Parser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    public JSONObject getJSONData(String url){
            try{
                        DefaultHttpClient client = new DefaultHttpClient();
                        HttpPost post = new HttpPost(url);
                        HttpResponse response = client.execute(post);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();
            }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
            try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
            try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return jObj;
    }
}

After creating Parser class, You need to know how you can use it in your MainActivity class. In NewsLines, there are multiple strings i.e HeadLine and DateLine. So you need to define these in your class.
    private static final String NEWS = "NewsML";
       private static final String NEWS_LINE = "NewsLines";
       private static final String HEAD_LINE = "HeadLine";
       private static final String DATE_LINE = "DateLine";
Now it’s main thing How I can get the data. Here I will use Parser class and provide the specific url. Depending upon JSON object, you will get the length of json array and write the code like this.
    Parser parser = new Parser();
        JSONObject json = parser.getJSONData(url);
            news = json.getJSONArray(NEWS);
            for(int i=0;i<news.length();i++){
                        JSONObject object = news.getJSONObject(i);
                        JSONObject newsline = object.getJSONObject(NEWS_LINE);
                        String headLine = newsline.getString(HEAD_LINE);
                        String dateLine = newsline.getString(DATE_LINE);
                 }
After getting all the data showing in list view. So MainActivity class is like this:
public class MainActivity extends ListActivity {

private static String url = "http://mfeeds.timesofindia.indiatimes.com/Feeds/jsonfeed?newsid=3947071&amp;amp;format=simplejson";
    private static final String NEWS = "NewsML";
    private static final String NEWS_LINE = "NewsLines";
    private static final String HEAD_LINE = "HeadLine";
    private static final String DATE_LINE = "DateLine";
    JSONArray news = null;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                       
                      ArrayList<HashMap<String, String>> newsList =
                      new ArrayList<HashMap<String, String>>();
        Parser parser = new Parser();
        JSONObject json = parser.getJSONData(url);
        try{
            news = json.getJSONArray(NEWS);
            for(int i=0;i<news.length();i++){
                        JSONObject object = news.getJSONObject(i);
                        JSONObject newsline = object.getJSONObject(NEWS_LINE);
                        String headLine = newsline.getString(HEAD_LINE);
                        String dateLine = newsline.getString(DATE_LINE);
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(HEAD_LINE, headLine);
                        map.put(DATE_LINE, dateLine);
                        newsList.add(map);
            }
        }catch(JSONException e){
            e.printStackTrace();
        }
      
 ListAdapter adapter = new SimpleAdapter(this, newsList,
                                            R.layout.listview_item,
                                            new String[] { HEAD_LINE, DATE_LINE },
                                            new int[] {R.id.tv_headLine, R.id.tv_dateLine });

        setListAdapter(adapter);
            }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android1:id="@android:id/list"
        android1:layout_width="match_parent"
        android1:layout_height="wrap_content" >
    </ListView>
        

</LinearLayout> 

listview_item.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:background="#DEC397"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_headLine"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HeadLine"
        android:textColor="#DE5084"
        android:textSize="18sp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/tv_dateLine"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5BC990"
        android:textSize="14sp"
        android:text="DateTime"
        android:textAppearance="?android:attr/textAppearanceMedium" />


</LinearLayout>


In your manifest file, don’t forget to mansion internet connection permission.
<uses-permission android:name="android.permission.INTERNET" />

You Will Get Out Put Like This:

Here We are directly getting data on Main UI Thread, So there is a possibility to getting NetworkOnMainThread exception. 

You can get exception like this, when you directly accessing data on Main UI thread:
 So it's better parsing data using asynctask. 
In Next tutorial I explained how JSON parsing happening using Threading mechanism.

7 comments:

  1. Android Tutorial for Beginners learns android programming and how to develop android mobile phone and ipad applications starting from environment setup.

    ReplyDelete
  2. why we need to declare static variable in parser class, can i declare it normal or local variable instead.

    ReplyDelete
  3. i am facing an error Error:cannot find symbol method setListAdapter(ListAdapter)

    ReplyDelete