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.

JSON Android Tutorial

JSON(JavaScript Object Notation)
Before going to JSON Details, First need to observe about Serialization. So you can easily understand about JSON.
So what is Serialization?
 It is the process of Converting the data into the stream of bytes into stream of information which other System can Understand. Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.

Why I used ‘primary purpose’ in the above definition is, sometimes people use java serialization as a replacement for database. Just a placeholder where you can persist an object across sessions. This is not the primary purpose of java serialization. Sometimes, when I interview candidates for Java I hear them saying java serialization is used for storing (to preserve the state) an object and retrieving it. They use it synonymously with database. This is a wrong perception for serialization.
Different Types of Serialization:
1. NameValuePair
2. XML
3. JSON
4. SOAP Protocol
5. Serializable Classes
Name Value Pair:
              A simple class encapsulating an attribute/value pair.It is used to send small amount of data to the destination.
XML(Extensible Mark-Up Language):
         XML is an Extensible Markup Language, a metalanguage that allows users to define their own customized markup languages.

Defination of JSON:
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.
The advantage of JSON is, it is more light weight than other and parsing is more faster other than that.

JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.




Example:
Object Type JSON:
   {
    'name' : 'Tara',
    'phone' : 123456789
   };

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

In Next tutorial, we will see how JSON works in Android and how to parse json in Android.

Sunday, 17 November 2013

What are Intent Filters exactly in Android?

To inform the system which implicit intents they can handle, activities, services, and broadcast receivers can have one or more intent filters. Each filter describes a capability of the component, a set of intents that the component is willing to receive. It, in effect, filters in intents of a desired type, while filtering out unwanted intents — but only unwanted implicit intents (those that don't name a target class). An explicit intent is always delivered to its target, no matter what it contains; the filter is not consulted. But an implicit intent is delivered to a component only if it can pass through one of the component's filters. If we go through an Example, So we can understand easily.
Example:
When you use an explicit intent it's like you tell Android "open SecondActivity".
When you use an implicit intent you tell Android: "open an activity that can do these things". These things is actually the filter that you write in the manifest for SecondActivity.
As an example, if you are in FirstActivity and want to start SecondActivity:
Explicitly You Can Declare Like This:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
Implicitly You can Declare Like This:
Intent intent = new Intent();
intent.addAction("myAction");
intent.addCategory("myCategory");
startActivity(intent);
And in this case you should have in your manifest file something like:
<activity android:name="SecondActivity">
   <intent-filter>
      <action android:name="myAction"/>
      <category android:name="myCategory"/>
   </intent-filter>
</activity>