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 Item 7 Let’s say you scroll down to view Two more elements item 6 and 7. What happens here is the last two row will be updated with the new value   item 6 and item 7..i.e handled by the adapter

Sugar ORM With Sqlite Android Part I

Sugar ORM  Android Part I:              If you have came this far in search of how to use an ORM database with your application , you are very much familiar with pain that SQLite querying concept is giving you for all basic CRUD operations with the database. Sugar ORM is  one of the solution which is available for you to carry out CRUD operation in ease, There is no need to use cursor  for reading from database, Sugar ORM speaks Object with Sqlite database. Sugar ORM consider a row of data as Object, where SQLite consider it as record. In this example I am going to show you how to create a table and add data to it using Sugar ORM. Let's get started. 1. Library Inclusion First and Foremost thing, add Sugar ORM to your project by adding the following line to your app dependencies. compile 'com.github.satyan:sugar:1.4' 2. Add Database configuration to Application Manifest: We have to inform the android sdk, that we are using SugarORM to handle CRUD