Skip to main content

Writing Data Back to Json




Writing Data Back to Json Using AsyncHttpClient(library):




 


  You can download the complete Android Studio Project from here.

Gradle Dependencies:

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

    



You are about to know how to write data back to Json. In order to do that you need to know a little about the following things. we are about to create an Android application to save the user profile data and write/update it to Json.
  1. Serialization.  
  2. Gson.
  3. Android Asynchronous Http Client.  

 1. Serialization:

 Serialization is the concept of converting Java objects to byte streams and converting those byte stream back to Java objects whenever you need. The important question from you right now would be. why we use serialization. And the answer for it is. 
    you won't be updating data directly to Json. Before doing that you will be writing the data to objects and it members. so the object holds the member data. If you want to write a new set of data you will simply create a new object and write those data. Observer the following diagram you might grab an idea on how it works. 

   User Profile will be contain a list of UserProfile class members(i.e firstName,lastName,age,mobileNumber,eMail). So you can add multiple user details to userProfile array by simply calling userProfiles= new ArrayList<>().

2. Gson:

   Gson work is to convert the above writable byte stream to Json format. And before making the post Request to submit the following data with the Url. Gson have to Convert the Json data back to string. 
The following diagram explains the work of a Gson.

   

3. Android Asynchronous Http Client:

       Android Asynchronous Http client is an library like Volley, which can handle array, object and string response in a single Request. The programmer don't have to worry about the whether he will get the JsonArray , object or String as Response. you can learn about and download the dependencies from here.

Let's jump into actual Implementation. 

4.  Strings.xml:

  <string name="serverUrl">https://api.myjson.com/bins/48y0i</string>  
 <string name="postUrl">https://api.myjson.com/bins</string>  

I don't like  to create a local server in my machine and explain how you can write Json data back so I have used myjson.com, which is an online Json API , anyone can Give their own Json structure and use the same to process GET and POST call.

5. MainActivity.Java:

 
 public class MainActivity extends AppCompatActivity {  
   EditText firstname,lastname,age,mobileNumber,email;  
   Button submitDataToSerializableObject,writeDataToServer,openUrlInBrowser;  
   JSONArray userProfileArray;  
   String responseString;  
   JSONObject userProfileArrayObject,parentJsonObject;  
   int i=0;  
   ProfileData profileData;  
   UserProfiles userProfile;  
   ProgressDialog progressDialog;  
   Gson gson;  
   TextView textViewToDisplayResultUrlWhereDataIsStored;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     getAvailableDataOnPostUrl();  
     firstname=(EditText) findViewById(R.id.firstNameEditText);  
     lastname=(EditText)findViewById(R.id.lastNameEditText);  
     age=(EditText) findViewById(R.id.ageEditText);  
     mobileNumber=(EditText)findViewById(R.id.mobile_editText);  
     email=(EditText)findViewById(R.id.email_editText);  
     submitDataToSerializableObject=(Button) findViewById(R.id.submit);  
     writeDataToServer=(Button) findViewById(R.id.write_data_back_to_server);  
     progressDialog = new ProgressDialog(MainActivity.this);  
     openUrlInBrowser=(Button) findViewById(R.id.open_url_on_browser);  
     textViewToDisplayResultUrlWhereDataIsStored=(TextView) findViewById(R.id.textviewForUrl);  
     userProfileArray=new JSONArray();  
     userProfileArrayObject=new JSONObject();  
     parentJsonObject=new JSONObject();  
     submitDataToSerializableObject.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         addDataToSerializableObject();  
       }  
     });  
     writeDataToServer.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         progressDialog.setMessage("writing Data Back to server");  
         progressDialog.show();  
         try {  
           writeDataBackToserver();  
         }  
         catch (Exception e)  
         {  
           Log.v("writeBackEror",e.toString());  
         }  
       }  
     });  
     openUrlInBrowser.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v)  
       {  
         Uri uri = Uri.parse(textViewToDisplayResultUrlWhereDataIsStored.getText().toString());  
         Intent intent = new Intent(Intent.ACTION_VIEW, uri);  
         startActivity(intent);  
       }  
     });  
   }  
   private void writeDataBackToserver() {  
     AsyncHttpClient writeDataBackToserver=new AsyncHttpClient();  
     StringEntity entity=null;  
     try {  
       Gson gson = new Gson();  
       String gsonString = gson.toJson(profileData, ProfileData.class);  
       //Gson convert Json data to String and send it as StringEntity with the URL.  
       entity = new StringEntity(gsonString);  
     }  
     catch (UnsupportedEncodingException e) {  
       e.printStackTrace();  
     }  
     writeDataBackToserver.post(getApplicationContext(), getString(R.string.postUrl), entity, "application/json", new JsonHttpResponseHandler() {  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, JSONObject response) {  
         Log.v("successobject", response.toString());  
         try {  
           textViewToDisplayResultUrlWhereDataIsStored.setText(response.get("uri").toString());  
           /* In response of our successfull POST call request, we will get a URL back from  
            * "myjson.com", where the data we have sent is stored. If you are using MongoDb etc  
            *  this will be the same url which you used for POST call, which can also be used With GET Call.  
            */  
         } catch (Exception e) {  
           Log.e("error", e.toString());  
         }  
         progressDialog.dismiss();  
       }  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, JSONArray response) {  
         Log.v("successarray", response.toString());  
         progressDialog.dismiss();  
       }  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, String responseString) {  
         super.onSuccess(statusCode, headers, responseString);  
         progressDialog.dismiss();  
       }  
     });  
   }  
   private void getAvailableDataOnPostUrl()  
   {  
     /* This get Call is to say the Serializable object and Gson what are the  
      * key and value it have to match with. Like giving a structure to how the data will  
      * be written.  
      */  
     AsyncHttpClient httpClient=new AsyncHttpClient();  
     httpClient.get(getString(R.string.serverUrl), new JsonHttpResponseHandler() {  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, JSONObject response) {  
         Log.v("successjObject", response.toString());  
         try {  
           responseString = response.toString();  
           gson = new GsonBuilder().create();  
           profileData = gson.fromJson(responseString, ProfileData.class);  
           profileData.userProfiles = new ArrayList<UserProfiles>();  
           /* GET call will get the following object as response,  
           * { "userProfiles":[{}]}  
            * This will be passed to the Gson and Profile data class to set the  
            * members and values accordingly.  
            */  
         } catch (Exception e) {  
           Log.v("arrayerror", e.toString());  
           e.printStackTrace();  
         }  
       }  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, JSONArray response) {  
         Log.v("successJArray", response.toString());  
         super.onSuccess(statusCode, headers, response);  
       }  
       @Override  
       public void onSuccess(int statusCode, Header[] headers, String responseString) {  
         Log.v("successresponsestring", responseString);  
         super.onSuccess(statusCode, headers, responseString);  
       }  
       @Override  
       public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {  
         Log.e("failureJarray", errorResponse.toString());  
         super.onFailure(statusCode, headers, throwable, errorResponse);  
       }  
       @Override  
       public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {  
         Log.e("failureStringres", responseString);  
         super.onFailure(statusCode, headers, responseString, throwable);  
       }  
       @Override  
       public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {  
         Log.e("failureJObject", errorResponse.toString());  
         super.onFailure(statusCode, headers, throwable, errorResponse);  
       }  
     });  
   }  
   private void addDataToSerializableObject()  
   {  
     /* This method will add entered data to serializable objects  
      * new ArrayList<UserPorfiles> allow you to store and  
      * multiple userprofile values.  
      */  
     userProfile=new UserProfiles();  
     userProfile.firstName=firstname.getText().toString();  
     userProfile.lastName=lastname.getText().toString();  
     userProfile.age=Integer.parseInt(age.getText().toString().trim());  
     userProfile.mobileNumber=Integer.parseInt(mobileNumber.getText().toString().trim());  
     userProfile.eMail=email.getText().toString();  
     profileData.userProfiles.add(userProfile);  
     firstname.setText("");  
     lastname.setText("");  
     mobileNumber.setText("");  
     age.setText("");  
     email.setText("");  
   }  
 }  

6. profileData.java:



public class ProfileData implements Serializable {  
   public List<UserProfiles> userProfiles;  
 }  
 class UserProfiles  
 {  
   public String firstName;  
   public String lastName;  
   public int age;  
   public int mobileNumber;  
   public String eMail;  
 }  

7.ActivityMain.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:paddingLeft="@dimen/activity_horizontal_margin"  
   android:orientation="vertical"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   android:background="#4CAF50"  
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">  
   <RelativeLayout  
     android:id="@+id/firstname_layout"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
     <TextView  
       android:text="FirstName"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:textColor="@android:color/white"  
       android:layout_centerVertical="true"  
       android:layout_alignParentLeft="true"  
       android:textSize="14sp"  
       />  
     <EditText  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:hint="FirstName"  
       android:textColor="@android:color/white"  
       android:textColorHint="@android:color/white"  
       android:id="@+id/firstNameEditText"  
       android:layout_alignParentRight="true"  
       android:layout_centerVertical="true"  
       />  
   </RelativeLayout>  
   <RelativeLayout  
     android:id="@+id/lastname_layout"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
     <TextView  
       android:text="LastName"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:textColor="@android:color/white"  
       android:layout_centerVertical="true"  
       android:layout_alignParentLeft="true"  
       android:textSize="14sp"  
       />  
     <EditText  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:hint="LastName"  
       android:textColor="@android:color/white"  
       android:textColorHint="@android:color/white"  
       android:id="@+id/lastNameEditText"  
       android:layout_alignParentRight="true"  
       android:layout_centerVertical="true"  
       />  
   </RelativeLayout>  
   <RelativeLayout  
     android:id="@+id/age_layout"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
     <TextView  
       android:text="Age"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:textColor="@android:color/white"  
       android:layout_centerVertical="true"  
       android:layout_alignParentLeft="true"  
       android:textSize="14sp"  
       />  
     <EditText  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:hint="Age"  
       android:id="@+id/ageEditText"  
       android:textColor="@android:color/white"  
       android:textColorHint="@android:color/white"  
       android:layout_alignParentRight="true"  
       android:layout_centerVertical="true"  
       />  
   </RelativeLayout>  
   <RelativeLayout  
     android:id="@+id/contact_layout"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
     <TextView  
       android:text="Mobile Number"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:textColor="@android:color/white"  
       android:layout_centerVertical="true"  
       android:layout_alignParentLeft="true"  
       android:textSize="14sp"  
       />  
     <EditText  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:hint="Mobile Number"  
       android:id="@+id/mobile_editText"  
       android:textColor="@android:color/white"  
       android:textColorHint="@android:color/white"  
       android:inputType="phone"  
       android:layout_alignParentRight="true"  
       android:layout_centerVertical="true"  
       />  
   </RelativeLayout>  
   <RelativeLayout  
     android:id="@+id/email_layout"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
     <TextView  
       android:text="Email"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:textColor="@android:color/white"  
       android:layout_centerVertical="true"  
       android:layout_alignParentLeft="true"  
       android:textSize="14sp"  
       />  
     <EditText  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:hint="Email"  
       android:id="@+id/email_editText"  
       android:textColor="@android:color/white"  
       android:textColorHint="@android:color/white"  
       android:inputType="textEmailAddress"  
       android:layout_alignParentRight="true"  
       android:layout_centerVertical="true"  
       />  
   </RelativeLayout>  
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Submit data To serializable Object"  
     android:id="@+id/submit"  
     android:clickable="true"  
     android:layout_marginTop="10dp"  
     android:layout_gravity="center_horizontal"  
     />  
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="write Data Back to server"  
     android:id="@+id/write_data_back_to_server"  
     android:clickable="true"  
     android:layout_marginTop="10dp"  
     android:layout_gravity="center_horizontal"  
     />  
   <TextView  
     android:layout_marginTop="10dp"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/textviewForUrl"  
     android:textColor="@android:color/white"  
     android:textSize="15dp"  
     android:text="Url-where the data is written displayed here"  
     android:layout_gravity="center_horizontal"  
     />  
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/open_url_on_browser"  
     android:layout_gravity="center_horizontal"  
     android:textColor="@android:color/black"  
     android:text="open Url in Browser"  
     android:layout_marginTop="20dp"  
     />  
 </LinearLayout>  






8. Output:




This is how Data is written back to Json On server. Hope it helps. 

Lingaraj S.





Comments

Popular posts from this blog

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 { ...

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...

Sugar ORM SQlite Android Part 2

Code Walkthrough :       Previously you have seen how to use SugarORM with Android . In this , I will be giving you a walkthrough how the whole code works in an application, with a sample application which I have created.  you can also download the complete android studio project from here AndroidManifest.xml: This is how the sample application will look like, when the application get installed, android will create an sqlite database named codexandroid.db as mentioned in this manifest.  It will also assign the database version to be 1, if you add more table to your database you have to increement your database version number before deploying it on Google play store or for demo. android:noHistory="true"  --> This is to stop android from keeping activity in stack , so that when you press back in this application, you won't be taken back to the previously used activity.  <application android:allowBackup...