Skip to main content

Adding Json array to Serializable Class using Gson.


Why you should use Gson and Serializable Class to Handle Json Data:

Gson can be used along with Serializable class to save variables, unnecessary loops and memory  to save the data you get from Json. 

Let's Imagine you have array of contact detail and its total count is four. which is something like this.

Json Snippet:

 [
{  
     "name": "Mark",  
     "phoneNumber": "1008788666",  
     "emailId": "mark@mail.com",  
     "address": "600 Pennsylvania Avenue, Washington DC"  
   },  
   {  
     "name": "Christian",  
     "phoneNumber": "8007780066",  
     "emailId": "christian@mail.com",  
     "address": "11 Wall Street New York"  
   },  
   {  
     "name": "Benedict",  
     "phoneNumber": "4258781555",  
     "emailId": "benedict@mail.com",  
     "address": " 350 Fifth Avenue New York, NY"  
   },  
   {  
     "name": "Bob",  
     "phoneNumber": "4448784444",  
     "emailId": "bob@mail.com",  
     "address": "221 B Baker St, London, England"  
   }  
 ] 
 
so to save these data normally to a local variable,you have to do the following. which is,
  1. create an array of name, phonenumber,emailId,address.
  2. Assign memory for them at runtime. 
  3. Create a loop to store data. 


This causes lot of memory and performance issues when the record is large. Let's say 1000+. This is were Gson is handy with the help of Serializable class.

Create a Single Serializable class in the following structure and

SerializableJsonDataHolder.java:


public class SerializableJsonDataHolder implements Serializable {  
   public List<ContactDetail> contactDetailsList;  
 }  
 class ContactDetail  
 {  
   public String name;  
   public String phoneNumber;  
   public String emailId;  
   public String address;  
 }  

And pass the response that you get from Http get request to Gson , with the serializable List structure, like the following.

Code snippet:


contactDetailsTemporaryHolder = new ArrayList<ContactDetail>();  
  Type typeIndicatorForGson = new TypeToken<ArrayList<ContactDetail>>() {}.getType();  
  Gson myGson = new Gson();  
  contactDetailsTemporaryHolder = myGson.fromJson(response.toString(), typeIndicatorForGson);  
  serializableJsonDataHolder.contactDetailsList = contactDetailsTemporaryHolder; 

Important:

  • When you try to pass an array to a serializable class,don't add it's class name to myGson.fromJson("responsestring","classname");, it won't work. Actually Gson will consider this as an object reference instead of Array. 
  • So inorder to make the Gson understand that the response it have to process is Array, we have to create a Type saying what Gson class can expect. whether it's an array <studentDetail> or array <contactDetail>.
  • And then this will be passed to myGson.FromJson("responseString","Type");

By doing the above thing, you are informing Gson that, the response should be processed in the form of ArrayList with the mentioned class structure.

You can understand Clearly when you have a look at the complete workflow. Which is given below. 

1.Gradle Dependencies:

  compile 'com.loopj.android:android-async-http:1.4.9'  
   compile 'com.google.code.gson:gson:2.2.4'  

2.MainActivity.java:


public class MainActivity extends AppCompatActivity {  
   ProgressDialog myProgressDialog;  
   List<ContactDetail> contactDetailsTemporaryHolder;  
   SerializableJsonDataHolder serializableJsonDataHolder;  
   Button data1,data2,data3,data4,getJsonData;  
   TextView contactName,contactNumber,emailId,addres;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     data1=(Button)findViewById(R.id.button_fetch_first_data_from_json);  
     data2=(Button)findViewById(R.id.button_fetch_second_data_from_json);  
     data3=(Button)findViewById(R.id.button_fetch_third_data_from_json);  
     data4=(Button)findViewById(R.id.button_fetch_fourth_data_from_json);  
     contactName=(TextView) findViewById(R.id.contact_name);  
     contactNumber=(TextView)findViewById(R.id.contact_number);  
     emailId=(TextView)findViewById(R.id.email_id);  
     addres=(TextView)findViewById(R.id.address);  
     getJsonData=(Button)findViewById(R.id.getJsonData);  
     myProgressDialog=new ProgressDialog(MainActivity.this);  
     myProgressDialog.setMessage("Getting Data from Json and Adding it Serializable class");  
     serializableJsonDataHolder=new SerializableJsonDataHolder();  
     getJsonData.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         myProgressDialog.show();  
         setContactDetailsToSerializableClass();  
       }  
     });  
     data1.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         contactName.setText(serializableJsonDataHolder.contactDetailsList.get(0).name);  
         contactNumber.setText(serializableJsonDataHolder.contactDetailsList.get(0).phoneNumber);  
         emailId.setText(serializableJsonDataHolder.contactDetailsList.get(0).emailId);  
         addres.setText(serializableJsonDataHolder.contactDetailsList.get(0).address);  
       }  
     });  
     data2.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         contactName.setText(serializableJsonDataHolder.contactDetailsList.get(1).name);  
         contactNumber.setText(serializableJsonDataHolder.contactDetailsList.get(1).phoneNumber);  
         emailId.setText(serializableJsonDataHolder.contactDetailsList.get(1).emailId);  
         addres.setText(serializableJsonDataHolder.contactDetailsList.get(1).address);  
       }  
     });  
     data3.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         contactName.setText(serializableJsonDataHolder.contactDetailsList.get(2).name);  
         contactNumber.setText(serializableJsonDataHolder.contactDetailsList.get(2).phoneNumber);  
         emailId.setText(serializableJsonDataHolder.contactDetailsList.get(2).emailId);  
         addres.setText(serializableJsonDataHolder.contactDetailsList.get(2).address);  
       }  
     });  
     data4.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         contactName.setText(serializableJsonDataHolder.contactDetailsList.get(3).name);  
         contactNumber.setText(serializableJsonDataHolder.contactDetailsList.get(3).phoneNumber);  
         emailId.setText(serializableJsonDataHolder.contactDetailsList.get(3).emailId);  
         addres.setText(serializableJsonDataHolder.contactDetailsList.get(3).address);  
       }  
     });  
   }  
   private void setContactDetailsToSerializableClass() {  
     AsyncHttpClient asyncHttpClient=new AsyncHttpClient();  
     String url="http://demo5585860.mockable.io/contactDetailJson";  
     asyncHttpClient.get(MainActivity.this,url, new JsonHttpResponseHandler() {  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, JSONArray response) {  
         Log.v("success", response.toString());  
         try {  
           contactDetailsTemporaryHolder = new ArrayList<ContactDetail>();  
           Type typeIndicatorForGson = new TypeToken<ArrayList<ContactDetail>>() {}.getType();  
           Gson myGson = new Gson();  
           contactDetailsTemporaryHolder = myGson.fromJson(response.toString(), typeIndicatorForGson);  
           serializableJsonDataHolder.contactDetailsList = contactDetailsTemporaryHolder;  
           myProgressDialog.dismiss();  
         }  
         catch (Exception e)  
         {  
           myProgressDialog.dismiss();  
           Log.e("GsonError", e.toString());  
           Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();  
           e.printStackTrace();  
         }  
         }  
     } );  
   }  
 }  


2.Activity_main.xml:


<?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout 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:orientation="vertical"  
   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">  
   <Button  
     android:id="@+id/getJsonData"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:text="Get Json Array Data and Add it Serializable Object" />  
   <RelativeLayout  
     android:id="@+id/layout_containing_buttons"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content">  
     <Button  
       android:id="@+id/button_fetch_first_data_from_json"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_alignParentLeft="true"  
       android:layout_centerHorizontal="true"  
       android:text="Data 1" />  
     <Button  
       android:id="@+id/button_fetch_second_data_from_json"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_centerHorizontal="true"  
       android:layout_toRightOf="@+id/button_fetch_first_data_from_json"  
       android:text="data 2" />  
     <Button  
       android:id="@+id/button_fetch_third_data_from_json"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_centerHorizontal="true"  
       android:layout_toRightOf="@+id/button_fetch_second_data_from_json"  
       android:text="data 3" />  
     <Button  
       android:id="@+id/button_fetch_fourth_data_from_json"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_centerHorizontal="true"  
       android:layout_toRightOf="@+id/button_fetch_third_data_from_json"  
       android:text="data 4" />  
   </RelativeLayout>  
   <TextView  
     android:id="@+id/heading"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center_horizontal"  
     android:layout_marginBottom="10dp"  
     android:layout_marginTop="30dp"  
     android:text="Contact Information Retrieved From Json"  
     android:textAllCaps="true"  
     android:textColor="@color/colorPrimaryDark"  
     android:textStyle="bold" />  
   <TextView  
     android:id="@+id/contact_name"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center_horizontal"  
     android:layout_marginBottom="10dp"  
     android:layout_marginTop="10dp"  
     android:text="Name"  
     android:textAllCaps="true"  
     android:textSize="20dp"  
     android:textStyle="bold"  
     />  
   <TextView  
     android:id="@+id/contact_number"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center_horizontal"  
     android:layout_marginBottom="10dp"  
     android:layout_marginTop="10dp"  
     android:text="Phone Number"  
     android:textAllCaps="true"  
     android:textSize="20dp"  
     android:textStyle="bold"  
     />  
   <TextView  
     android:id="@+id/email_id"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center_horizontal"  
     android:layout_marginBottom="10dp"  
     android:layout_marginTop="10dp"  
     android:text="Email ID"  
     android:textSize="20dp"  
     android:textStyle="bold"  
     />  
   <TextView  
     android:id="@+id/address"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center_horizontal"  
     android:layout_marginTop="10dp"  
     android:text="Address"  
     android:textAllCaps="true"  
     android:textSize="20dp"  
     android:textStyle="bold" />  
 </LinearLayout>  













You can Download the Complete Android Studio Project from here. 

Comments

  1. Borgata Hotel Casino & Spa - JTR Hub
    Located https://jancasino.com/review/merit-casino/ in Atlantic City, Borgata www.jtmhub.com Hotel casino-roll.com Casino https://sol.edu.kg/ & novcasino Spa offers the finest in amenities and entertainment. It also provides a seasonal outdoor swimming

    ReplyDelete

Post a Comment

Popular posts from this blog

Hiding a Child item(ImageView) In ListView

Download Complete Android Studio Project by  Clicking Here . Important Things About Listview: i.                A List view Recycle it’s view. Meaning If your screen can only fit 5 items. But the total number of item   you are about to display in listview is 100 . ii.               Android won’t load these 100 items into the listview when you set your adapter. iii.             Instead it first load the first five Items on the screen and when you scroll down , it fills the new data into the listview, Which improves performance and Memory. ListView at First Load Item 1   Item 2 Item 3 Item 4 Item 5 ListView When Scrolled Item 3   Item 4 Item 5 Item 6 ...

No FindViewById

This post is going to save lot of your time from using the FindViewById. So  I found this interesting article on Medium.com  No more findviewById written by  George Mount.  and I thought why don't I write how it can be done in sample program . That would be much easier to understand isn't . So here it is. And please read the article first from Medium.com first . In this post I will demonstrate you , how to use dataBinding option in Android Studio, which will will eliminate the painful part of binding every view in xml with your Java.  Your Android Studio must be version 1.5 and Higher. 1. Add the Following lines to your app Build.gradle file : android { dataBinding . enabled = true ; } After adding this line to your app gradle file, the file should look something like this. apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.0" dataBinding.enabled = true; defaultConfig { ...