Loading ...

Parsing JSON data into android applications | CodeAsp.Net

Parsing JSON data into android applications

 /5
0 (0votes)

We need a source that will send us the data, for this we will use the following source:

http://jsonplaceholder.typicode.com/posts/1

TheJSON object the you willrecieve will be this:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

To start, we will use the above mentioned API.

Steps:

1. Create an android studio project and name it as "Json_Parse", and set the company domain as "com.json_parsing.codeasp.json_parse". Click next.

2. Now select the minimum SDK as 18(Jelly Bean 4.3) and leave all other fields as they are and click next.

3. Select the Blank Activity and click next.

4. Leave all the fields as default and click next.

5. Next, we need to add some labels.For this, open the "activity_main.xml" file from the "layout" folder under "res", and add the following code: 

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="User ID"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/userID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView"
        android:layout_marginTop="40dp"
        android:text="ID"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignTop="@+id/textView3"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="40dp"
        android:text="Title"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView5"
        android:layout_marginTop="33dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/title"
        android:layout_marginTop="40dp"
        android:text="Body"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/body"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="38dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Here, I have fixed the text of few labels as "UserID", "ID","Title","Body", and set the id's of few labels as "userID", "ID", "title","body". I will bind these with my code which will be used to display the data received from the server.

6. We are finished designing. Let us write the code for our desired output to occur. For this, open the "MainAcivity.java" file.

7. As descried in the beginning we need to set the background and add an image and display some customised text in our toast and for this, we will use our layout file "toast_message_layout" file. We need to declare them in the java file; above the "onCreate" method and below the class declaration. Add the following:

TextView userID, ID, Title, Body;

Also declare this:

Context appContext;
ProgressDialog pDialog;
static String response = null;

We will use "pDialog" while getting the data so that the screen does not freeze; and "response" that will be used to get data from the server.

8. Now, bind the "TextView" from the xml file in the "onCreate" method, as follows:

        userID = (TextView) findViewById(R.id.userID);
        ID = (TextView) findViewById(R.id.ID);
        Title = (TextView) findViewById(R.id.title);
        Body = (TextView) findViewById(R.id.body);

9. We need to create a class that will work as asynchronously to get data and then display it. This class will be used so that the screen does not freeze and the android system does not crash the application. Create the class as follows:

private class ParseData extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... arg0) {
        }

        @Override
        protected void onPostExecute(String test) {
                super.onPostExecute(test);
            }

        }
    }

10. Also needed is a method that will get a data, name that method as "makeServiceCall" which will take "String" parameter that will be the "URL" from where the data will be got, this method will return the "resopnse". Create it as follows:

 public String makeServiceCall(String url) {

        return response;

    }

11. Now we need to create a "try" "catch" block and create a Http connection that will get the data. We will use the "HttpGet" method, as follows:

try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            HttpGet httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet);


            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity, HTTP.UTF_8);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

Here, we have created a httpClient object that is used to retrive data from the "HttpClient", for which we have used "DefaultHttpCleint" class instance. "DefaultHttpClient" is the standard HttpClient and use the "SingleClientConnManager" class for the use of "Http" connections. The "HttpEntity" is a class that is used to carry the message and the headers; and the HtttpResponse is used here to get the data from the connection we have opened using the httpClient via the HttpGet method. Then, the data in the httpResponse will be saved in the httpEntity object and that will then be converted to string format and returned back.

12. In the async class, first we will add the "ProgressDialog" in the method "onPreExecute()" which will not allow the screen to freeze and will continue to get that data in the background. Add the following code to do this:

           // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please Wait");
            pDialog.setCancelable(false);
            pDialog.show();

After adding this, the method will look like:

 @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please Wait");
            pDialog.setCancelable(false);
            pDialog.show();

        }

13. Now in the doInBackground method create a "String" name it as "json_get_data", and create a try catch block, and another String as "getURL".

14. Next, we will make a call to the "makeServiceCall" method and the catch the String data returned in the "json_get_data" method and pass the data to the "onPostExecute" method. After adding this, the method will look like:

@Override
        protected String doInBackground(Void... arg0) {
            String json_get_data = "";
            try {
                String getUrl = "http://jsonplaceholder.typicode.com/posts/1";

                json_get_data = makeServiceCall(getUrl);

            } catch (Exception e) {

                e.printStackTrace();
            }
            return json_get_data;
        }

15. In the onPostExecute method get the "String" from the "doInBackground" method.

16. Dismiss the "ProgressDialog" and then create an JsonObject and the pass the String into that.

17. Next, using that object get separate string, as follows:

try {

                    JSONObject jsoncurrentUserObj = new JSONObject(json_get_data);
                    String userId = jsoncurrentUserObj.getString("userId");
                    String id = jsoncurrentUserObj.getString("id");
                    String body = jsoncurrentUserObj.getString("body");
                    String title = jsoncurrentUserObj.getString("title");
} catch (JSONException e) {
                    e.printStackTrace();
                }

18. Set all the string to the textViews, as follows:

                    userID.setText(userId);
                    ID.setText(id);
                    Body.setText(body);
                    Title.setText(title);

After adding this, the method will look like:

@Override
        protected void onPostExecute(String json_get_data) {
            super.onPostExecute(json_get_data);
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            if (json_get_data != null) {

                try {

                    JSONObject jsoncurrentUserObj = new JSONObject(json_get_data);
                    String userId = jsoncurrentUserObj.getString("userId");
                    String id = jsoncurrentUserObj.getString("id");
                    String body = jsoncurrentUserObj.getString("body");
                    String title = jsoncurrentUserObj.getString("title");
                    userID.setText(userId);
                    ID.setText(id);
                    Body.setText(body);
                    Title.setText(title);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                // unable_to_fetch.setText("Unable to fetch your case please check it online or try again.");
            }

        }

19. Now, as we need to access the Internet to get the data, we need set the permission for it, in the manifest file, as follows:

    <uses-permission android:name="android.permission.INTERNET" />

20. Finally run the application on your emulator or the device.

Application screen shots:

      

To download the project: Click Here

Comments (no comments yet)

Top Posts