Android JSON Parsing Using okHttp Example with New Material Design Library

Android JSON Parsing Using okHttp Example with New Material Design Library

Hello to everyone, Today I am posting about JSON Parsing in Android using okHttp Library.

HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

I found many documentation to understand okHttp but I want to share my example which i have created as Demo.

Prerequisites: 

1. What is JSON?

2. Android Studio Basics

Example:

Create New Project in Android Studio android follow the instructions.

Permissions in AndroidManifest.xml

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

Add following gradle dependency in build.gradle:

compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'com.squareup.okhttp:okhttp:2.0.0'

JSON Parser File (Copy Class and Paste in Your src Folder):

/**  
  * @author Pratik Butani  
  */  
 public class JSONParser {  
   /********  
    * URLS  
    *******/  
   private static final String MAIN_URL = "http://pratikbutani.x10.mx/json_data.json";  
   /**  
    * TAGs Defined Here...  
    */  
   public static final String TAG = "TAG";  
   /**  
    * Key to Send  
    */  
   private static final String KEY_USER_ID = "user_id";  
   /**  
    * Response  
    */  
   private static Response response;  
   /**  
    * Get Table Booking Charge  
    *  
    * @return JSON Object  
    */  
   public static JSONObject getDataFromWeb() {  
     try {  
       OkHttpClient client = new OkHttpClient();  
       Request request = new Request.Builder()  
           .url(MAIN_URL)  
           .build();  
       response = client.newCall(request).execute();  
       return new JSONObject(response.body().string());  
     } catch (@NonNull IOException | JSONException e) {  
       Log.e(TAG, "" + e.getLocalizedMessage());  
     }  
     return null;  
   }  
 }

Layout File: activity_main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/parentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/stat_sys_download" />

</android.support.design.widget.CoordinatorLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<String> list;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();
        /**
         * Binding that List to Adapter
         */
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(findViewById(R.id.parentLayout), list.get(position), Snackbar.LENGTH_LONG).show();
            }
        });

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(@NonNull View view) {

                /**
                 * Just to know onClick and Printing Hello Toast in Center.
                 */
                Toast toast = Toast.makeText(getApplicationContext(), "Hello in Center", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                
                /**
                 * Checking Internet Connection
                 */
                if (InternetConnection.checkConnection(getApplicationContext())) {
                    new GetDataTask().execute();
                } else {
                    Snackbar.make(view, "Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }

    /**
     * Creating Get Data Task for Getting Data From Web
     */
    class GetDataTask extends AsyncTask<Void, Void, Void> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            /**
             * Progress Dialog for User Interaction
             */
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setTitle("Hey Wait Please...");
            dialog.setMessage("I am getting your JSON");
            dialog.show();
        }

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {

            /**
             * Getting JSON Object from Web Using okHttp
             */
            JSONObject jsonObject = JSONParser.getDataFromWeb();

            try {
                /**
                 * Check Whether Its NULL???
                 */
                if (jsonObject != null) {
                    
                    /**
                     * Check Length...
                     */
                    if (jsonObject.length() > 0) {
                        
                        /**
                         * Getting Array named "contacts" From MAIN Json Object
                         */
                        JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);

                        /**
                         * Check Length of Array...
                         */
                        int lenArray = array.length();
                        if (lenArray > 0) {
                            for (int jIndex = 0; jIndex < lenArray; jIndex++) {
                                
                                /**
                                 * Getting Inner Object from contacts array...
                                 * and
                                 * From that We will get Name of that Contact
                                 *
                                 */
                                JSONObject innerObject = array.getJSONObject(jIndex);
                                String name = innerObject.getString(Keys.KEY_NAME);

                                /**
                                 * Getting Object from Object "phone"
                                 */
                                JSONObject phoneObject = innerObject.getJSONObject(Keys.KEY_PHONE);
                                String phone = phoneObject.getString(Keys.KEY_MOBILE);

                                /**
                                 * Adding name and phone concatenation in List...
                                 */
                                list.add(name + " - " + phone);
                            }
                        }
                    }
                } else {

                }
            } catch (JSONException je) {
                Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.dismiss();
            /**
             * Checking if List size if more than zero then
             * Update ListView
             */
            if (list.size() > 0) {
                adapter.notifyDataSetChanged();
            } else {
                Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
            }
        }
    }
}

Output:

Android JSON Parsing Using okHttp Example with New Material Design Library

Android JSON Parsing Using okHttp Example with New Material Design Library

Download Demo from GitHub: JSON Parsing using okHttp

Hope You will enjoy with Android JSON Parsing with okHttp and basic of Android Design Library.

Any question, Any query, Any suggestion Always Welcome. Do comment.

Thank you.

Page Views (10406)

13582 Total Views 2 Views Today
Support with Your Share:

About pratikbutani

Enthusiastic Android Application Developer, Speaker at Google Developer Group - Rajkot, All time Learner of new things, Googler, Eager to Help IT Peoples. Master of all, Jack of ONE.

Comment Your Suggestion or Appreciation:

Loading Facebook Comments ...

One Comment

  1. Pingback: Android Tutorial - JSON Parsing using Retrofit - Part 1 - Pratik Butani - AndroidButs

Leave a Reply

Your email address will not be published. Required fields are marked *