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:
- String
- Number
- JSON Object
- Array
- Boolean
- 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:
- get(String name):
- getBoolean(String name):
- getDouble(String name):
- getInt(String name):
- getJSONArray(String name):
- getJSONObject(String name):
- getLong(String name):
- getString(String name):
- length():
- keys():
- opt(String name):
- optBoolean(String name):
- optDouble(String name):
- optInt(String name):
- optJSONArray(String name):
- optJSONObject(String name):
- optLong(String name):
- 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>
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 code “activity_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.
Finally we use Volley for read human data from online database by JSON Parser.
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:
- Automatica scheduling of network request for data load from json parser.
- Multiple network connect for data loading.
- Memory response caching.
- Easy customization.
- Network error message show easily.
- Debugging tools.
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.