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,
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
- create an array of name, phonenumber,emailId,address.
- Assign memory for them at runtime.
- 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.
Nice linga
ReplyDeleteBorgata Hotel Casino & Spa - JTR Hub
ReplyDeleteLocated 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