Android Json Parsing Using Google Gson Part 3


In the previous part of the Json series , we seen the complete basics of json.In this part we are going to actually parse a sample Json Object Using Google GSON.The Json will be not  passed as a String within the code itself instead we will call the json object through  external URL through HTTP call.


Step 1:
Here is our Json Code that we are going to parse Using Gson in Android:

   "Os_version":[ {    "title":"Android 4.3 Jelly Bean (API level 18)"
      },
      { 
         "title":"Android 4.4 KitKat (API level 19)"
      },
      { 
         "title":"Android 5.0 Lollipop (API level 21)"
      }
   ],
   "author":"Venkatesh Pillai",
   "price":"Open Source",
   "subject":"Last Android Os release"
}



Step 2: 
The next step is to download the Gson jar file.

Step 3:
Right-click the project's top most folder and select PROPERTIES ->JAVA BUILD PATH and select the libraries tab.

 Click the Add JARs button and select the Gson jar we added to the /libs folder 


Step 4:
We need to create one model class Beansubject.java and BeanOs_version.java and annotate field names  with the SerializedName annotation. When we add serialized name to field must match with key name from JSON

Beansubject.java

import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class BeanSubject {

@SerializedName("subject")
    private String subject; 
@SerializedName("price")   
private String price;    
@SerializedName("auther")    
private String auther;    
@SerializedName("Os_version")    
private ArrayList<BeanTopic> beanTopics;

    public BeanSubject(ArrayList<BeanTopic> beanOs_version, String subject, String price, String auther)
{        this.beanOs_version = beanOs_version;      
this.subject = subject;        
this.price = price;        
this.auther = author;    

}

public String getSubject() { 
return subject;   
}    
public void setSubject(String subject) { 
this.subject = subject;    
}   
public String getPrice() { 
return price;   
}    
public void setPrice(String price) {  
this.price = price;    
}    
public String getAuthor() {  
return auther;    
}    
public void setAuthor(String auther) {
this.auther = auther;    
}    
public ArrayList<BeanOs_version> getBeanOs_version() { 
return beanOs_version;    
}    
public void setBeanOs_version(ArrayList<BeanOs_version> beanOs_version) {
this.beanOs_version = beanOs_version;    
}

}


Step 5:

     BeanOs_version.java

import com.google.gson.annotations.SerializedName;
public class BeanOs_version {

    @SerializedName("title") 
private String title;

    public BeanTopic(String title)
{   
this.title = title;    
}

    public String getTitle() {
return title;    
}   
public void setTitle(String title) 
{        
this.title = title;    
}
}

Step 6:
Here come the important task of creating HTTP request to the url to fetch the required data through Json. 
Create API.java class to perform an HTTP request and retrieve the resource as a stream.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class API 
{                
private static Reader reader=null;                
public static Reader getData(String SERVER_URL) 
{        
                        try {                                              
DefaultHttpClient httpClient = new DefaultHttpClient();                                                
HttpPost httpPost = new HttpPost(SERVER_URL);                                                
HttpResponse response = httpClient.execute(httpPost);                                                
StatusLine statusLine = response.getStatusLine();                                                
if (statusLine.getStatusCode() == 200) {                                                                HttpEntity entity = response.getEntity();                                                                InputStream content = entity.getContent();                                                                
reader = new InputStreamReader(content);                                                
} else {  
}                               
} catch (ClientProtocolException e) {                                           
e.printStackTrace();                                
} catch (IllegalStateException e) {                                             
e.printStackTrace();                                
} catch (IOException e) {                                                e.printStackTrace();                     
}                              
return reader;                
}
}



Step 7:
Now change the code in MainActivity.java Activity class and 
create GSON instance get data in required way that can be shown in your activity_main.xml layout file .
We will use Asyn Task Since the required details need to be fetched in background.Its not the good way to fetch data in tha UI thread. The doInBackground() method will help to work in background. 

Main Activity.java

new AsyncTask<Void,Void,Void>(){

@Override

protected void onPreExecute() {

super.onPreExecute();

progressDialog=new ProgressDialog(MyActivity.this);

progressDialog.setCancelable(false);

progressDialog.setMessage("Loading...");

progressDialog.show();

} @Override



protected Void doInBackground(Void... voids) {

Reader reader=API.getData("....url....");

beanSubject = new GsonBuilder().create().fromJson(reader, BeanSubject.class);



//Printing in Log File

Log.e("Subject: ", beanSubject.getSubject()+"");

Log.e("Auther: ", beanSubject.getAuthor()+"");

Log.e("Price: ", beanSubject.getPrice()+"");

Os_versionArrayList=beanSubject.getBeanOs_version();




Os_versionList=new StringBuffer();

for(BeanOs_version Os_version: Os_versionArrayList){

Log.e("topic title: ",Os_version.getTitle()+"");

Os_versionList.append("* "+Os_version.getTitle()+"\n");

} return null;

} @Override



protected void onPostExecute(Void aVoid) {

super.onPostExecute(aVoid);

progressDialog.dismiss();

txtSubject.setText("Subject: "+beanSubject.getSubject());

txtPrice.setText("price: "+beanSubject.getPrice());

txtAuthor.setText("Auther: "+beanSubject.getAuthor());

txtOs_versionList.setText("Topics: "+"\n"+Os_versionList);

}

}.execute();

Step 8:

Run the application to see the result.





Thats it .We are able to fetch the data from the URL using HTTP request through GSON in android app

Happy Coding!Happy Development.

Android Parsing Json tutorial part -2


Parsing a JsonArray in Android

In the previous part of the Json series , we seen the complete basics of json.In this part we are going to actually parse a sample Json Array.The Json will be passed aa a String within the code itself instead of caaling the external URL through HTTP call.




Lets get started.



The sample json we created for todays project[Footballmania]

{
"FIFA World cup 2015":[

    "Team_Code":"BRA",
           "Team_Name":"BRAZIL",
           "GOAL":"2"
}, 
        {           
           "Team_Code":"GER" 
           "Team_Name":"GERMANY"
           "GOAL":"1"
}

};


The difference between [ and { - (Square brackets and Curly brackets) has been completely explained in the last post of Json.so take a look at that before you proceed.

If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.


Creating New Android Project[FootballMania]

1. Create a new project in Eclipse from File ->New -> Android Application Project. I had left my main activity name as MainActivity.java and gave the package name as com.example.androidgreeve.simplejson

2.Since we are not making any HTTP calls in this part of tutorial,we will make no changes to the Manifest.xml file.


Manifest.XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidgreeve.simplejson"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidgreeve.simplejson.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Creating the Layout 

3.Now will create the required Front End for the todays project in activity_main.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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:background="@drawable/bg">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="29dp"
        android:text="Androidgreeve"
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:textColor="#fff"
        android:textStyle="bold"
        android:textSize="30sp"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="23dp"
        android:text="FIFA -Final Scoreline"
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:textColor="#fff"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="54dp"
        android:text="Code"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#fff" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="60dp"
        android:text="Team"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#fff"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView4"
        android:layout_alignBottom="@+id/textView4"
        android:layout_centerHorizontal="true"
        android:text="Score"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#fff" />


</RelativeLayout>

Parsing the Json data.

//passing json Array as string.
4.String strJson="{ \"FIFA World cup 2015\" " +
        ":[{\"Team_Code\":\"BRA\"," +
        "\"Team_Name\":\"BRAZIL\"," +
        "\"GOAL\":\"2\"}," +
        "" +
        "{\"Team_Code\":\"GER\"," +
        "\"Team_Name\":\"GERMANY\"," +
        "\"GOAL\":\"1\"}] }";
           
                // Create the root JSONObject from the JSON string.
            JSONObject  jsonRootObject = new JSONObject(strJson);

            //Get the instance of JSONArray that contains JSONObjects
                  JSONArray jsonArray = jsonRootObject.optJSONArray("FIFA World cup 2015");
                   
                //Iterate the jsonArray and print the info of JSONObjects
                  for(int i=0; i < jsonArray.length(); i++){
                   
                     JSONObject jsonObject = jsonArray.getJSONObject(i);
                         
                     String Team_Code = jsonObject.optString("Team_Code").toString();
                     String Team_Name = jsonObject.optString("Team_Name").toString();
                     int GOAL = Integer.parseInt(jsonObject.optString("GOAL").toString());
                      

Complete Code of Mainactivity.java

6. The complete code of the Main_activity
package com.example.androidgreeve.simplejson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TextView T_name= (TextView)findViewById(R.id.textView3);
        TextView T_Code= (TextView)findViewById(R.id.textView4);
        TextView T_goal=(TextView)findViewById(R.id.textView5);
        
        
        String strJson="{ \"FIFA World cup 2015\" " +
        ":[{\"Team_Code\":\"BRA\"," +
        "\"Team_Name\":\"BRAZIL\"," +
        "\"GOAL\":\"2\"}," +
        "" +
        "{\"Team_Code\":\"GER\"," +
        "\"Team_Name\":\"GERMANY\"," +
        "\"GOAL\":\"1\"}] }";   
              
               try {
             
                     // Create the root JSONObject from the JSON string.
              JSONObject  jsonRootObject = new JSONObject(strJson);

              //Get the instance of JSONArray that contains JSONObjects
                    JSONArray jsonArray = jsonRootObject.optJSONArray("FIFA World cup 2015");
                    String name="",code="";
                    String goal="";
                    //Iterate the jsonArray and print the info of JSONObjects
                    for(int i=0; i < jsonArray.length(); i++){
                   
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                         
                        String Team_Code = jsonObject.optString("Team_Code").toString();
                        String Team_Name = jsonObject.optString("Team_Name").toString();
                        int GOAL = Integer.parseInt(jsonObject.optString("GOAL").toString());
                         
                        name+=Team_Name+"  ";
                        code+=Team_Code+"\n";
                        goal+=GOAL+"\n";
                        //Setting data to XML
                        T_name.setText(name);
                        T_Code.setText(code+"\n");
                        T_goal.setText(goal+"\n");
                        
                      }
            
                    
                   //output.setText(data);
         
                } catch (JSONException e) {e.printStackTrace();}

    }
      
}
    

Whats Next?

7.No worries, this was the simplest method to parse data.In the next tutorial we will parse Json URl anfd fetch data from it.
Dont miss any thing Just subscribe and Share it.  

Happy developing!Happy Coding.

Android Json Parsing basics tutorial

Step by Step guide to learn Json and parsing it in android.  

JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server. 

In this tutorial we are going to learn how to parse JSON in android.But Before that we need to get the basics of Json correctly understood so that it could become easy to implement.

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML.
Json_Basic_tutorial androidgreeve

You can see the difference between an XML and Json in the below code.


Simple Example :

Json Version of It.

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

This XML syntax also defines an employees object with 3 employee records:
The XML version of it.

<employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>

Android provides four different classes to manipulate JSON data. 

These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.

The following table will help to understand in detail about it.




JSON Syntax Rules

JSON syntax is a subset of the JavaScript object notation syntax:
  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays
JSON data is written as name/value pairs.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

"firstName":"John"


JSON Values

JSON values can be:
  • A number (integer or floating point)
  • A string (in double quotes)
  • A Boolean (true or false)
  • An array (in square brackets)
  • An object (in curly braces)
  • null

Lets see some Sample JsonArray String 

JSONArray String is like this

[{
"internalName": "blaaa",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
},
{
"internalName": "blooo",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}]


An example of JSONObject Is like this
{
"internalName": "domin91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,



You can find the difference in the braces of the JSonArray and JsonObject.

Why Json?Why not XML? Difference?Advantages  all this question answer can be found below.


Advantages of JSON
  • Smaller message size
  • More structural information in the document
    • Can easily distinguish between the number 1 and the string "1" as numbers, strings (and Booleans) are represented differently in JSON.
    • Can easily distinguish between single items and collections of size one (using JSON arrays).
  • Easier to represent a null value
  • Easily consumed by JavaScript
Advantages of XML
  • Namespaces allow for sharing of standard structures
  • Better representation for inheritance
  • Standard ways of expressing the structure of the document: XML schema, DTD, etc
  • Parsing standards: DOM, SAX, StAX
  • Standards for querying: XQuery and XPath
  • Standards for transforming a document: XSLT
Draw
  • Human Readable
  • Easy to parse
You can find lots of tools to convert from XMl to Json and viceversa.

Here we end the basics of Json.In the next tutorial we will how to actually parse json in Android app , and it advantages.

If any doubts feel free to ask in the comment below.Any suggestion to be added you are welcomed.

How to apply Material Design to your app

Changes HDDMigration to be made from Holo to Material.

The Android 5.0 SDK was released(if you want know step by step guide to installing it) last Friday, featuring new UI widgets and material design, our visual language focused on good design. To enable you to bring your latest designs to older Android platforms we have expanded our support libraries, including a major update to AppCompat, as well as new RecyclerViewCardView and Palette libraries.
In this post we'll take a look at what’s new in AppCompat and how you can use it to support material design in your apps.

We will go Step by Step to make changes for Material Design:

From ActionbarCompact to AppCompactv21

AppCompat (aka ActionBarCompat) started out as a backport of the Android 4.0 ActionBar API for devices running on Gingerbread, providing a common API layer on top of the backported implementation and the framework implementation. AppCompat v21 delivers an API and feature-set that is up-to-date with Android 5.0.

Three things to lookout or there might be three situations we need to consider.

Setting up the things first to migrate to appcompact v21:

Migrating from holo to material.

If you have followed the guidelines correctly then you don't require to change lots of thing in your app for migration.

A)Open the values Folder that contains the Themes.xml file and change accordingly.
values/themes.xml:
<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
    <!-- Set AppCompats actionBarStyle -->
    <item name="actionBarStyle">@style/MyActionBarStyle</item>

    <!-- Set AppCompat’s color theming attrs -->
    <item name=”colorPrimary”>@color/my_awesome_red</item>
    <item name=”colorPrimaryDark”>@color/my_awesome_darker_red</item>
    
    <!-- The rest of your attributes -->
</style>

Note:
B)If you are using gradle , add appcompat as a dependency in your build.gradle file:
just paste the below code in dependency
dependencies {
    compile "com.android.support:appcompat-v7:21.0.+"
}
 C) Now you can remove all other actionbar styles.

2)Apply themes using new color palette attributes:
Checkout the new colors added in Android 5.0 Lollipop


D)Copy the code the themes,xml in values folder.
<!-- colorAccent is used as the default value for colorControlActivated,
         which is used to tint widgets -->
    <item name=”colorAccent”>@color/accent</item>

    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight, and colorSwitchThumbNormal. -->


In the next post we will look at how to create a Actionbar from scratch using the latest Material Design.

We would ask you to try this things and comments if you face with some problems,
Please like and share with other dev who are willings to try this out too!

Happy developing!Happy Coding!