Android JSON object Parser using volley

JSON Means ” JavaScript Object Notation”. JSON object is structured human readable and easy to parse. It is a best way to read online data from server.

JSON Parsing Data Type:

  1. String
  2. Number
  3. JSON Object
  4. Array
  5. Boolean
  6. null

JSON Parsing Data Type Details

JSON Parsing In Android:

http://onlinetech24.com/test/json_object.php

Objects({}):

curly bracket ({}) represent JSONObject. A JSONObject represent the some type of data like Strings, Booleans, Integers, Longs, Doubles, null. JSONObject is infinities.

JSONObjet Parsing methods:

  1. get(String name):
  2. getBoolean(String name):
  3. getDouble(String name):
  4. getInt(String name):
  5. getJSONArray(String name):
  6. getJSONObject(String name):
  7. getLong(String name):
  8. getString(String name):
  9. length():
  10. keys():
  11. opt(String name):
  12. optBoolean(String name):
  13. optDouble(String name):
  14. optInt(String name):
  15. optJSONArray(String name):
  16. optJSONObject(String name):
  17. optLong(String name):
  18. optString(String name):

Example of JSON Parsing In Android Studio:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.api.sm.allapi">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".Controller"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".JSON_Object_Read">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

java class for android

Create a class in android project “BitmapCache”

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader;

/**
* Created by sm on 11/09/2018.
*/

public class BitmapCache extends LruCache<String, Bitmap> implements
       ImageLoader.ImageCache {

   public static int getDefaultLruCacheSize() {
       final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
       final int cacheSize = maxMemory / 8;
       return cacheSize;
   }

   public BitmapCache() {
       this(getDefaultLruCacheSize());
   }

   public BitmapCache(int sizeInKiloBytes) {
       super(sizeInKiloBytes);
   }

   @Override
   protected int sizeOf(String key, Bitmap value) {
       return value.getRowBytes() * value.getHeight() / 1024;
   }

   @Override
   public Bitmap getBitmap(String url) {
       return get(url);
   }

   @Override
   public void putBitmap(String url, Bitmap bitmap) {
       put(url, bitmap);
   }
}

Create a class in android project “Controller” for load data and image form online by volley lib.

import android.app.Application;
import android.text.TextUtils;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
/**
* Created by sm on 11/09/2018.
*/
public class Controller extends Application {
   public static final String TAG = Controller.class.getSimpleName();
   private RequestQueue queue;
   private com.android.volley.toolbox.ImageLoader ImageLoader;
   private static Controller controller;

   @Override
   public void onCreate() {
       super.onCreate();
       controller = this;
   }

   public static synchronized Controller getPermission() {
       return controller;
   }

   public RequestQueue getRequestQueue() {
       if (queue == null) {
           queue = Volley.newRequestQueue(getApplicationContext());
       }
       return queue;
   }

   public com.android.volley.toolbox.ImageLoader getImageLoader() {
       getRequestQueue();
       if (ImageLoader == null) {
           ImageLoader = new ImageLoader(this.queue,
                   new BitmapCache());
       }
           return this.ImageLoader;
   }


   public  void addToRequestQueues(Request req, String tag) {
       // default tag if tag is empty
       req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
       req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
       getRequestQueue().add(req);
   }

   public  void addToRequestQueue(Request req) {
       req.setTag(TAG);
       req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
       getRequestQueue().add(req);
   }

   public void cancelPendingRequests(Object tag) {
       if (queue != null) {
           queue.cancelAll(tag);
       }
   }

}

Type this code in your project main class:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

/**
* Created by sm on 11/09/2018.
*/

public class JSON_Object_Read extends AppCompatActivity {
   TextView s_stock_quantity, s_price, s_total_sale, s_customer_commission, s_agent_commission;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_json__object__read);
       setTitle("JSON Object");

      // ------------------------- Text View --------------------------
       s_stock_quantity = (TextView) findViewById(R.id.stock_quantity);
       s_price = (TextView) findViewById(R.id.price);
       s_total_sale = (TextView) findViewById(R.id.total_sale);
       s_customer_commission = (TextView) findViewById(R.id.customer_commission);
       s_agent_commission = (TextView) findViewById(R.id.agent_commission);


       final String url = "http://onlinetech24.com/test/json_object.php";
       JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
               new Response.Listener() {
                   @Override
                   public void onResponse(JSONObject response) {
                       try {
                           //----------first object-----------------------
                           JSONObject data = response.getJSONObject("store");
                           String stock_quantity = data.getString("stock_quantity");
                           String price = data.getString("price");
                               s_price.setText("Total Price: "+price+" $");

                           //---------- second object-----------------------
                           JSONObject total  = response.getJSONObject("total");
                           String total_sale = total.getString("total_sale");
                               s_total_sale.setText("Total Sale: "+total_sale+" $"); //----- Set Text from Json Objcet
                           String customer_commission = total.getString("customer_commission");
                               s_customer_commission.setText("Agent Commission: "+customer_commission+" $"); //----- Set Text from Json Objcet
                           String agent_commission = total.getString("agent_commission");
                               s_agent_commission.setText("Customer Commission: "+agent_commission+" $"); //----- Set Text from Json Objcet
                               s_stock_quantity.setText("Stock Quantity: "+stock_quantity); //----- Set Text from Json Objcet

                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
                   }
               }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                   Toast.makeText(getApplication(),"Your Netwark Connection Problem", Toast.LENGTH_LONG).show();
               } else if (error instanceof AuthFailureError) {
                   Toast.makeText(getApplication(),"Failure to Connection Server", Toast.LENGTH_LONG).show();
               } else if (error instanceof ServerError) {
                   Toast.makeText(getApplication(),"Server Problem", Toast.LENGTH_LONG).show();
               } else if (error instanceof NetworkError) {
                   Toast.makeText(getApplication(),"Network Problem", Toast.LENGTH_LONG).show();
               } else if (error instanceof ParseError) {
                   Toast.makeText(getApplication(),"Parse Problem", Toast.LENGTH_LONG).show();
               }
           }
       }){ @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
           Map<String, String> params = new HashMap<String, String>();
           params.put("Accept", "application/json");
         //  params.put("Authorization", access_token); //--- if use access token
           return params;
       }
       };
       req.setRetryPolicy(
               new DefaultRetryPolicy(
                       500000,
                       DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                       DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
               )
       );
       Controller.getPermission().addToRequestQueue(req);


   }
}

XML Layout:
Main activity XML codeactivity_json__object__read”

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".JSON_Object_Read">

   <LinearLayout
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:gravity="center"
       android:orientation="vertical">

       <LinearLayout
           android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:orientation="vertical">

           <LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:gravity="center"
               android:orientation="vertical">

               <LinearLayout
                   android:layout_width="match_parent"
                   android:layout_height="wrap_content"
                   android:orientation="vertical"
                   android:padding="2dp">

                   <LinearLayout
                       android:layout_width="match_parent"
                       android:layout_height="match_parent"
                       android:layout_margin="10dp"
                       android:background="#d7d7d7"
                       android:orientation="vertical"
                       android:padding="7dp">

                       <TextView
                           android:id="@+id/stock_quantity"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           android:layout_margin="5dp"
                           android:textColor="#404040"
                           android:textSize="15sp"
                           android:textStyle="normal" />

                       <TextView
                           android:id="@+id/price"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           android:layout_margin="5dp"
                           android:textColor="#404040"
                           android:textSize="15sp"
                           android:textStyle="normal" />
                   </LinearLayout>

                   <LinearLayout
                       android:layout_width="match_parent"
                       android:layout_height="match_parent"
                       android:layout_margin="10dp"
                       android:background="#d7d7d7"
                       android:orientation="vertical"
                       android:padding="7dp">

                       <TextView
                           android:id="@+id/total_sale"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           android:layout_margin="5dp"
                           android:textColor="#404040"
                           android:textSize="15sp"
                           android:textStyle="normal" />


                   </LinearLayout>

                   <LinearLayout
                       android:layout_width="match_parent"
                       android:layout_height="match_parent"
                       android:layout_margin="10dp"
                       android:background="#d7d7d7"
                       android:orientation="vertical"
                       android:padding="7dp">

                       <TextView
                           android:id="@+id/customer_commission"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           android:layout_margin="5dp"
                           android:textColor="#404040"
                           android:textSize="15sp"
                           android:textStyle="normal" />

                       <TextView
                           android:id="@+id/agent_commission"
                           android:layout_width="wrap_content"
                           android:layout_height="wrap_content"
                           android:layout_margin="5dp"
                           android:textColor="#404040"
                           android:textSize="15sp"
                           android:textStyle="normal" />
                   </LinearLayout>
               </LinearLayout>
           </LinearLayout>
       </LinearLayout>
   </LinearLayout>
</android.support.constraint.ConstraintLayout>


Android XML” design for

json object

data  view.

xml design

Finally we use Volley for read human data from online database by JSON Parser.

volley lib

 

compile ‘com.android.volley:volley:1.1.1’

Why use volley lib?

 

Volley is an HTTP lib for making network android apps easily. Volley is faster from another online lib JSON Object. It has available source in online.

 

Volley use benefits:

  1. Automatica scheduling of network request for data load from json parser.
  2. Multiple network connect for data loading.
  3. Memory response caching.
  4. Easy customization.
  5. Network error message show easily.
  6. Debugging tools.

More details volley lib

We know that maximum “android app developer” use volley lib for JSON Object read. And it is google system for android mobile phone.

If you want to need another android source code please contact with me and need any static or dynamic android project like “office project”, “informative apps”,”personal information apps” other apps as your wish.

 

Leave a Reply

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