Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android JSON Parsing Tutorial

JSON Parsing in Android

JSON(JavaScript Object Notation), is a language independent data format that uses human-readable text to transmit data objects consisting of key-value pairs.

In this tutorial we will explain the structure of JSON response and how to parse the response in order to get required Information. To explain the concept we would be using two sample JSON responses we have created and placed at below links.

http://androidtutorialpoint.com/api/MobileJSONArray.json
http://androidtutorialpoint.com/api/MobileJSONObject.json

These links consist of sample JSON Responses for JSON Array and JSON Object respectively. Before starting to build app let’s dig a bit into the structure of a JSON response.

Consider following JSON Response :

[
        {
            "rom":"32GB",
            "screenSize":"5.5 inch",
            "backCamera":"21MP",
            "companyName":"Motorola",
            "name":"Moto X Play",
            "frontCamera":"5MP",
            "battery":"3630mAH",
            "operatingSystem":"Android 5.1",
            "processor":"1.8GHz",
            "url":"http://www.androidtutorialpoint.com/api/motorola_moto_x_play",
            "ram":"2GB"
        },
        {
            "rom":"8GB",
            "screenSize":"4 inch",
            "backCamera":"5MP",
            "companyName":"Samsung",
            "name":"Galaxy S Duos 3",
            "frontCamera":"0.3MP",
            "battery":"1500mAH",
            "operatingSystem":"Android 4.4",
            "processor":"1.2GHz",
            "url":"http://www.androidtutorialpoint.com/api/samsung_galaxy_s_dous_3",
            "ram":"512MB"},{"rom":"64GB",
            "screenSize":"4.7 inch",
            "backCamera":"12MP",
            "companyName":"Apple",
            "name":"Iphone 6S",
            "frontCamera":"5MP",
            "battery":"1715mAH",
            "operatingSystem":"iOS 9",
            "processor":"1.84GHz",
            "url":"http://www.androidtutorialpoint.com/api/apple_iphone_6s",
            "ram":"2GB"
        },
        {
            "rom":"16GB",
            "screenSize":"5.2 inch",
            "backCamera":"12.3MP",
            "companyName":"LG",
            "name":"Nexus 5X",
            "frontCamera":"5MP",
            "battery":"1500mAH",
            "operatingSystem":"Android 6",
            "processor":"1.8GHz",
            "url":"http://www.androidtutorialpoint.com/api/lg_nexus_5x",
            "ram":"2GB"
        }
            ]

As apparent from above a JSON Response can have the following elements.

  1. JSON Array([): In a JSON file , square bracket ([) represents a JSON array.
  2. JSON Objects({): In a JSON file, curly bracket ({) represents a JSON object.
  3. Key: A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object.
  4. Value: Each key has a value that could be string , integer or double etc.

Android provides the following classes to manipulate a JSON response :
JSONObject ,JSONArray, JSONStringer and JSONTokener. We will be talking about org.json.JSONObject and org.json.JSONArray in this tutorial.
To parse a JSON response first identify the fields in the JSON response that you are interested in. For example. In the JSON given above in the link, we will be using all the fields. We have to write our parse function accordingly.

Let’s go step by step to make a sample JSON parsing app. We will demonstrate how to parse a JSON Object and a JSON Array. In this app, we will retrieve the details of Mobile Phones from the JSON String provided at given URL and then display them as a list, on Clicking each individual Mobile, details of the mobile will be displayed.



Pre-requisites:

  1. Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
  2. A real time android device (Smartphone or Tablet) configured with Android Studio. .

Creating new project

  1. Open Android Studio and create a new project “JSONParser” and company domain application.example.com (We have used our company domain i.e androidtutorialpoint.com. Similarly you can use yours).
  2. Click Next and choose Min SDK, we have kept the default value. Again Click Next and Choose Blank Activity .
  3. Name the Activity JSONParseActivity and click next.
  4. Leave all other things as default and Click Finish.

A new project will be created and gradle will resolve all the dependencies.
Next create a mobile class. Mobile class represents the model of a mobile I.e it contains all the fields and methods (getter and setter) required by a Mobile. So create a new Java class Mobile.java and put following code in it.

Mobile.java

package com.androidtutorialpoint.jsonparser;
import java.io.Serializable;

public class Mobile implements Serializable{
    private String mName;
    private String mCompanyName;
    private String mOperatingSystem;
    private String mProcessor;
    private String mRam;
    private String mRom;
    private String mFrontCamera;
    private String mBackCamera;
    private String mScreenSize;
    private String mBattery;
    private String mUrl;
    public String getName() {
        return mName;
    }
    public void setName(String mName) {
        this.mName = mName;
    }
    public String getCompanyName() {
        return mCompanyName;
    }
    public void setCompanyName(String mCompanyName) {
        this.mCompanyName = mCompanyName;
    }
    public String getOperatingSystem() {
        return mOperatingSystem;
    }
    public void setOperatingSystem(String mOperatingSystem) {
        this.mOperatingSystem = mOperatingSystem;
    }
    public String getProcessor() {
        return mProcessor;
    }
    public void setProcessor(String mProcessor) {
        this.mProcessor = mProcessor;
    }
    public String getRam() {
        return mRam;
    }
    public void setRam(String mRam) {
        this.mRam = mRam;
    }
    public String getRom() {
        return mRom;
    }
    public void setRom(String mRom) {
        this.mRom = mRom;
    }
    public String getFrontCamera() {
        return mFrontCamera;
    }
    public void setFrontCamera(String mFrontCamera) {
        this.mFrontCamera = mFrontCamera;
    }
    public String getBackCamera() {
        return mBackCamera;
    }
    public void setBackCamera(String mBackCamera) {
        this.mBackCamera = mBackCamera;
    }
    public String getScreenSize() {
        return mScreenSize;
    }
    public void setScreenSize(String mScreenSize) {
        this.mScreenSize = mScreenSize;
    }
    public String getBattery() {
        return mBattery;
    }
    public void setBattery(String mBattery) {
        this.mBattery = mBattery;
    }
    public String getUrl() {
        return mUrl;
    }
    public void setUrl(String mUrl) {
        this.mUrl = mUrl;
    }
}

We are implementing Serializable interface as we will be passing Mobile object from one Activity to other.
Next create two function parseFeed() and parseArrayFeed() to parse the JSONObject and JSONArray respectively. While parsing the JSON response we might get an org.json.JSONException so we will write the parsing logic in a try/catch block.
parseFeed() takes JSONObject as a parameter and sets all the attribute of the mobile object.

JSONParser.java

package com.androidtutorialpoint.jsonparser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

public class JSONParser {
   public static ArrayList mMobiles = new ArrayList();
    public static Mobile parseFeed(JSONObject obj) {

        try {
                Mobile mobile = new Mobile();
                mobile.setName(obj.getString("name"));
                mobile.setCompanyName(obj.getString("companyName"));
                mobile.setOperatingSystem(obj.getString("operatingSystem"));
                mobile.setProcessor(obj.getString("processor"));
                mobile.setBackCamera(obj.getString("backCamera"));
                mobile.setFrontCamera(obj.getString("frontCamera"));
                mobile.setRam(obj.getString("ram"));
                mobile.setRom(obj.getString("rom"));
                mobile.setScreenSize(obj.getString("screenSize"));
                mobile.setUrl(obj.getString("url"));
                mobile.setBattery(obj.getString("battery"));
                return mobile;
            } catch (JSONException e1) {
            e1.printStackTrace();
            return null;
        }
    }

parseArrayFeed() takes JSONArray as a parameter and returns an ArrayList of Mobile.

JSONParser.java

public static ArrayList parseArrayFeed(JSONArray arr) {
        JSONObject obj=null;
        Mobile mobile = null;
        mMobiles.clear();
        try {

            for(int i = 0;i

Open AndroidManifest.xml and put the following code, always remember to change the package name according to your company domain. We have added the android.permission.INTERNET since we will be requesting JSON Data over Network.

AndroidManifest.xml

We create an activity JSONParseActivity which consist of two Buttons to decide whether to decode a JSONObject or a JSONArray as shown.


Put following code in JSONParseActivity:

JSONParseActivity.java

package com.androidtutorialpoint.jsonparser;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class JSONParseActivity extends AppCompatActivity {

    private Button button_getJSONObject;
    private Button button_getJSONArray;
    private final String EXTRA_JSON_OBJECT_INDEX = "com.androidtutorialpoint.jsonparser";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jsonparse);
        button_getJSONObject = (Button) findViewById(R.id.button_jsonobject);
        button_getJSONArray = (Button) findViewById(R.id.button_jsonarray);


        button_getJSONObject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplication(), ParseJSONObject.class);
                i.putExtra(EXTRA_JSON_OBJECT_INDEX, 0);
                startActivity(i);

            }
        });

        button_getJSONArray.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplication(), ParseJSONArray.class);
                startActivity(i);
            }
        });
    }
}

In above activity we have defined setOnClickListener for the two buttons and we are calling ParseJSONObject.java and ParseJSONArray.java on clicking them respectively.Following is Layout file for JSONParseActivity:

activity_jsonparse.xml


    

Let’s first talk about ParseJSONObject.java. This activity shows the details of the mobile retrieved from the MobileJSONObject URL and shows all the specs of the mobile along with the image. Create a Java Class ParseJSONObject.java and paste the following code.

ParseJSONObject.java

package com.androidtutorialpoint.jsonparser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

public class ParseJSONObject extends AppCompatActivity {

    private static final String TAG ="ParseJSONObject";
    private final String EXTRA_JSON_OBJECT_INDEX = "com.androidtutorialpoint.jsonparser";

    private Mobile mMobile;
    private TextView nameTextView;
    private TextView companyNameTextView;
    private TextView operatingSystemTextView;
    private TextView processorTextView;
    private TextView ramTextView;
    private TextView romTextView;
    private TextView frontCameraTextView;
    private TextView backCameraTextView;
    private TextView screenSizeTextView;
    private TextView batteryTextView;
    private ImageView photoImageView;
    private String photoUrl;

    String url = "http://androidtutorialpoint.com/api/MobileJSONObject.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parsejsonobject);

        nameTextView =(TextView)findViewById(R.id.edit_text_name);
        companyNameTextView =(TextView)findViewById(R.id.edit_text_company_name);
        operatingSystemTextView =(TextView)findViewById(R.id.edit_text_operating_system);
        processorTextView = (TextView)findViewById(R.id.edit_text_processor);
        ramTextView = (TextView)findViewById(R.id.edit_text_ram);
        romTextView = (TextView)findViewById(R.id.edit_text_rom);
        frontCameraTextView = (TextView)findViewById(R.id.edit_text_front_camera);
        backCameraTextView = (TextView)findViewById(R.id.edit_text_back_camera);
        screenSizeTextView = (TextView)findViewById(R.id.edit_text_screen_size);
        batteryTextView = (TextView)findViewById(R.id.edit_text_battery);
        photoImageView = (ImageView)findViewById(R.id.image_view_mobile_picture);



        final   ProgressDialog pDialog = new ProgressDialog(ParseJSONObject.this);
                pDialog.setMessage("Loading...");
                pDialog.show();

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,url, null,new Response.Listener() {

                            @Override
                            public void onResponse(JSONObject response) {

                                mMobile = JSONParser.parseFeed(response);


                                nameTextView.setText("Name :" + mMobile.getName());
                                companyNameTextView.setText("Company :" + mMobile.getCompanyName());
                                operatingSystemTextView.setText(" OS :" + mMobile.getOperatingSystem());
                                processorTextView.setText("Processor :" + mMobile.getProcessor());
                                ramTextView.setText("RAM :"+mMobile.getRam());
                                romTextView.setText("Memory :"+mMobile.getRom());
                                frontCameraTextView.setText("Front Camera :"+mMobile.getFrontCamera());
                                backCameraTextView.setText("Rear Camera :"+mMobile.getBackCamera());
                                screenSizeTextView.setText("Screen Size :"+mMobile.getScreenSize());
                                batteryTextView.setText("Battery :"+mMobile.getBattery());
                                photoUrl = (mMobile.getUrl());

                                ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(getApplicationContext()),
                                        new LruBitmapCache());

                                // If you are using normal ImageView
                                imageLoader.get(photoUrl, new ImageLoader.ImageListener() {

                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        Log.e(TAG, "Image Load Error: " + error.getMessage());
                                    }

                                    @Override
                                    public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                                        if (response.getBitmap() != null) {
                                            // load image into imageview
                                            photoImageView.setImageBitmap(response.getBitmap());
                                            pDialog.hide();

                                        }
                                    }
                                });


                                Log.d(TAG, response.toString());
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        // hide the progress dialog
                        pDialog.hide();
                    }
                });

                   // Adding request to request queue
           Volley.newRequestQueue(getApplicationContext()).add(jsonObjReq);
        }
    }

The code is very simple.

  1. We are referencing the layout elements in the OnCreate() method.
  2. Then, We are submitting a network request using Volley Library to get the JSON response from the URL. To know more about how to use Volley Library, refer to the following tutorial => Android Volley Tutorial
  3. On getting the response from the network request we are calling the JSON Parser and then setting the values for the TextView and ImageView widget.

The Layout for the above activity is as follows:

activity_parsejsonobject.xml

Layout is also pretty simple we have LinearLayout enclosed within a ScrollView to allow scrolling.We have an ImageView and some TextView‘s as a child of the LinearLayout to show info about Mobile.
Next create a Java class ParseJSONArray to host a Fragment that will list the mobile phones from JSON Array URL. Put following code in it:

ParseJSONArray.java

package com.androidtutorialpoint.jsonparser;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public class ParseJSONArray extends AppCompatActivity {
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parsejsonarray);
        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
        if (fragment == null) {
            fragment = new ListMobiles();
            fm.beginTransaction()
                    .add(R.id.fragmentContainer, fragment)
                    .commit();
        }
    }
}

Create a layout resource file for ParseJsonArray activity. It consists of just a FrameLayout that will act as a container for the Fragment

activity_parsejsonarray.xml

Create a Java class ListMobiles that will display the list of mobiles.

ListMobiles.java

package com.androidtutorialpoint.jsonparser;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import java.util.ArrayList;

public class ListMobiles extends ListFragment {

    private final String TAG = "ListMobiles";
    private ArrayList  mMobileList;
    String url = "http://androidtutorialpoint.com/api/MobileJSONArray.json";
    private final String EXTRA_JSON_OBJECT = "mobileObject";

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        final   ProgressDialog pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...");
        pDialog.show();

        JsonArrayRequest jsonArrayReq = new JsonArrayRequest(url,
                new Response.Listener() {
                    @Override
                    public void onResponse(JSONArray response) {

                        Log.d(TAG,response.toString());
                        Log.d(TAG,"Len "+response.length());
                        mMobileList = JSONParser.parseArrayFeed(response);

                        pDialog.hide();
                        MobileAdapter adapter = new MobileAdapter(mMobileList);
                        setListAdapter(adapter);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                // hide the progress dialog
                pDialog.hide();
            }
        });
        // Adding request to request queue
        Volley.newRequestQueue(getActivity()).add(jsonArrayReq);
    }

    private class MobileAdapter extends ArrayAdapter {
        public MobileAdapter(ArrayList mobiles) {
            super(getActivity(), 0, mobiles);
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
                // If we weren't given a view, inflate one

            Log.d(TAG,"pos "+position);
            if (convertView == null) {
                convertView = getActivity().getLayoutInflater()
                        .inflate(R.layout.category_list_item_1, null);
            }
               Mobile c = mMobileList.get(position);
            TextView nameTextView =
                        (TextView) convertView.findViewById(R.id.textview_name);
                nameTextView.setText(c.getName());

            nameTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent i = new Intent(getActivity(),ParseJSONArrayObject.class);
                    Bundle args = new Bundle();
                    //args.putSerializable(EXTRA_JSON_MOBILE_OBJECT, mMobileList.get(position));
                    i.putExtra(EXTRA_JSON_OBJECT, mMobileList.get(position));
                    startActivity(i);
                }
            });
            return convertView;
        }
    }
}

In the Above code we have created a custom ArrayAdapter for listing Mobiles:

  1. First we Override getView() method, in which we inflate category_list_item_1.xml file which we will be showing soon. Then we get Mobile item at corresponding position from the mMobileList and return the View.
  2. We have also created an OnClickListener that will start the ParseJSONArrayObject class and pass it the mobile phone you have clicked. We will be talking about this class shortly.
  3. In the onCreate method we do a Network request through Volley Library to get the JSONArray Request from the JSONArray URL.On receiving the response we parse it to get MobileList and then set the MobileAdapter on it.

We will be inflating following layout to show the entries. So create a layout resource file category_list_item_1.xml.To avoid complexity we have kept this layout and we are just using a TextView inside a LinearLayout.

category_list_item_1.xml

Now let’s talk about the ParseJSONArrayObject class which get’s called on clicking an item in the MobileList. Create a java class ParseJSONArrayObject and put following code.

ParseJSONArrayObject.java

package com.androidtutorialpoint.jsonparser;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class ParseJSONArrayObject extends AppCompatActivity{
    private static final String TAG ="ParseJSONObject";
    private Mobile mMobile;
    private TextView nameTextView;
    private TextView companyNameTextView;
    private TextView operatingSystemTextView;
    private TextView processorTextView;
    private TextView ramTextView;
    private TextView romTextView;
    private TextView frontCameraTextView;
    private TextView backCameraTextView;
    private TextView screenSizeTextView;
    private TextView batteryTextView;
    private ImageView photoImageView;
    private String photoUrl;
    private final String EXTRA_JSON_OBJECT = "mobileObject";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parsejsonobject);
        mMobile = (Mobile)getIntent().getSerializableExtra(EXTRA_JSON_OBJECT);
        nameTextView =(TextView)findViewById(R.id.edit_text_name);
        companyNameTextView =(TextView)findViewById(R.id.edit_text_company_name);
        operatingSystemTextView =(TextView)findViewById(R.id.edit_text_operating_system);
        processorTextView = (TextView)findViewById(R.id.edit_text_processor);
        ramTextView = (TextView)findViewById(R.id.edit_text_ram);
        romTextView = (TextView)findViewById(R.id.edit_text_rom);
        frontCameraTextView = (TextView)findViewById(R.id.edit_text_front_camera);
        backCameraTextView = (TextView)findViewById(R.id.edit_text_back_camera);
        screenSizeTextView = (TextView)findViewById(R.id.edit_text_screen_size);
        batteryTextView = (TextView)findViewById(R.id.edit_text_battery);
        photoImageView = (ImageView)findViewById(R.id.image_view_mobile_picture);
        final ProgressDialog pDialog = new ProgressDialog(ParseJSONArrayObject.this);
        pDialog.setMessage("Loading...");
        pDialog.show();
                        nameTextView.setText("Name :" + mMobile.getName());
                        companyNameTextView.setText("Company :" + mMobile.getCompanyName());
                        operatingSystemTextView.setText(" OS :" + mMobile.getOperatingSystem());
                        processorTextView.setText("Processor :" + mMobile.getProcessor());
                        ramTextView.setText("RAM :"+mMobile.getRam());
                        romTextView.setText("Memory :"+mMobile.getRom());
                        frontCameraTextView.setText("Front Camera :"+mMobile.getFrontCamera());
                        backCameraTextView.setText("Rear Camera :"+mMobile.getBackCamera());
                        screenSizeTextView.setText("Screen Size :"+mMobile.getScreenSize());
                        batteryTextView.setText("Battery :"+mMobile.getBattery());
                        photoUrl = (mMobile.getUrl());
                        ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(getApplicationContext()),
                                new LruBitmapCache());
                        imageLoader.get(photoUrl, new ImageLoader.ImageListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.e(TAG, "Image Load Error: " + error.getMessage());
                            }
                            @Override
                            public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                                if (response.getBitmap() != null) {
                                    // load image into imageview
                                    photoImageView.setImageBitmap(response.getBitmap());
                                    pDialog.hide();
                                }
                            }
                        });
    }
}

This Activity is similar to ParseJSONObject Activity however here we are receiving the Mobile Object in a Bundle.
In the onCreate method:

  1. We extract the Mobile Object from the intent.
  2. Reference the Layout elements from the Layout.
  3. Finally we set the TextView and create a network request for setting the ImageView

Additionally create the new java class LruBitmapCache.java. This class is used as cache for Image Loader in Volley, For more details please refer to our Volley Tutorial -> Android Volley Tutorial

LruBitmapCache.java

package com.androidtutorialpoint.jsonparser;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache implements
        ImageCache {
    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

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

    public LruBitmapCache(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);
    }
}

Now run the app on an Android Device or an Emulator, Do remember to turn on the Internet using Wifi or mobile data, since we have not added any logic to Check for Internet Connection in our android app.

And that’s pretty much it. We hope now you get the complete idea of JSON Parsing in android. Please comment if you have any doubts or suggestions.



What’s Next ?

Check our other tutorial, and create cool apps. Don’t forget to subscribe our blog for latest android tutorials. Also Like our Facebook Page or Add us on Twitter.

Click on the Download Now button to download the full code.


CodeProject

The post Android JSON Parsing Tutorial appeared first on Android Tutorial Point.



This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

Android JSON Parsing Tutorial

×

Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription

×