Android JSON, GridView and HttpURLConnection Tutorial and Examples.

In this article we want to look at several examples of how to use three technologies:

  • JSON
  • HttpURLConnection
  • AsyncTask
  • GridView

 

What is JSON

JSON stands for JavaScript Object Notation and is a language-independent data format that expresses JSON objects as human-readable lists of properties(name-value pairs).

It is a data format derived from the literals of the JavaScript programming language.

Learn more about JSON here

What We do With JSON

Well we will parse or process JSON data to obtain our data. JSON has to be parsed and we will use the native JSONArray and JSONObject classes. These two alongside an AsyncTask allow us parse or process json data thus filling an ArrayList.

What is HttpUrlConnection?

HttpUrlconnection is a UrlConnection for HTTP used to send as well receive data over the web. These data may be of any type and length.

Basically it is a networking class that allows us make HTTP calls. HTTP stands for Hyper Text Transfer Protocol and allows data transfer over the web.

Thus our android app also needs a way to transfer data to and from the web. Thus it has to make HTTP calls. And it is this HttpUrlConnection that powers that.

Learn more about HttpURLConnection here.

What is AsyncTask?

AsyncTask is a helper class for performing easy threading and created around Thread.

It allows us to perform our HTTP calls safely in a background thread. This is very important as doing them in the main thread can cause the user interface to freeze.

What is GridView?

A gridview is an adapterview that shows items in a two-dimensional grid.

GridView allows us render our items in a grid like manner. It is an alternative to using a ListView.

Learn more about GridView here.

Examples We Look At.

Well we look at three examples:

  1. Android JSON – Simple GridView – Download,Parse and Show
  2. Android Native JSON – GridView Multiple Fields – Download,Parse then Show
  3. Android JSON – GridView Master Detail – Download,Parse,Show [Open Detail Activity]

1. Android JSON – Simple GridView – Download,Parse and Show

[center]Android JSON – Simple GridView – Download,Parse and Show tutorial. [/center]

Here’s the demo of what we create:

Android Simple GridView JSON

Java Code

(a). Our Connector Class
  • Establish connection for us.
  • Set connection properties.
package com.tutorials.hp.jsongridview.m_JSON;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/*
 * ----------------------ROLES----------------
 * 1.Establish connection
 * 2. Connection props
 */
public class Connector {

    public static Object connect(String jsonURL)
    {
        try
        {
            URL url=new URL(jsonURL);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();

            //CON PROPS
            con.setRequestMethod("GET");
            con.setConnectTimeout(15000);
            con.setReadTimeout(15000);
            con.setDoInput(true);

            return con;

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();

        } catch (IOException e) {
            e.printStackTrace();
            return "Error "+e.getMessage();

        }
    }

}
(b). Our JSON Downloader Class
  • Where we download our json data from network.
  • We do this in background thread using AsyncTask.
  • Meanwhile we show a progress dialog.
  • After this, we pass our json data to JSONParser class to be parsed.
(c). Our JSON Parser Class
  • Receives the JSON string we downloaded.
  • So we parse this particular json,filling an arraylist.
  • Then we bind our arraylist of data our view component via an adapter.
(d). Our MainActivity Class
  • Our launcher activity.
  • We start our downloader, passing in URL as well as other parameters.

Our Layouts

(a). activity_main.xml
(b). content_main.xml
  • Displays our view

Our Manifest

  • Make sure you add permission for accessing internet.

Download

You can download the full project here.

No. Resource Direct Links
1. GitHub Source Code Browse
2. Source Code Download
3. YouTube Channel

2. Android Native JSON – GridView Multiple Fields – Download,Parse then Show

[center]Android Native JSON – GridView Multiple Fields – Download,Parse then Show tutorial.[/center]

In this tutorial we want to now see how to work with a custom gridview with multiple texts. We will be rendering multiple textviews in every single grid of our gridview.

Here’s the demo project.

Java Code

(a). Our Connector Class
  • Establish connection for us.
  • Set connection properties.
(b). Our JSON Downloader Class
  • Where we download our json data from network.
  • We do this in background thread using AsyncTask.
  • Meanwhile we show a progress dialog.
  • After this, we pass our json data to JSONParser class to be parsed.
(c). Our JSON Parser Class
  • Receives the JSON string we downloaded.
  • So we parse this particular json,filling an arraylist.
  • Then we bind our arraylist of data our view component via an adapter.
(d). Our CustomAdapter Class
  • Inflate our Custom Model into a View Item for our gridview.
  • Bind data to our AdapterView.
(e). Our MainActivity Class
  • Our launcher activity.
  • We start our downloader, passing in URL as well as other parameters.

Our Layouts

(a). activity_main.xml
(b). content_main.xml
  • Displays our adapter view
(c). model.xml
  • Inflated into a single viewitem for our gridview.

Our AndroidManifest.xml

  • Make sure you add permission for accessing internet.

Download

You can download the full project here.

No. Resource Direct Links
1. GitHub Source Code Browse
2. Source Code Download
3. YouTube Channel

3. Android JSON – GridView Master Detail – Download,Parse,Show [Open Detail Activity]

[center]Android JSON – GridView Master Detail – Download,Parse,Show [Open Detail Activity][/center]
The Plan
  1. Download json data from online url in background thread.
  2. Parse this data using org.json classes,jsonObject and jsonArray.
  3. Show it in Custom GridView.
  4. Handle our gridview itemClicks and open detail activity.
  5. Pass data to our detail activity

Here’s the demo:

That’s it lets get started.

Java Code

(a). Our Connector Class

  • Establish connection for us.
  • Set connection properties.
(b). Our JSON Downloader Class
  • Where we download our json data from network.
  • We do this in background thread using AsyncTask.
  • Meanwhile we show a progress dialog.
  • After this, we pass our json data to JSONParser class to be parsed.
(c). Our JSON Parser Class
  • Receives the JSON string we downloaded.
  • So we parse this particular json,filling an arraylist.
  • Then we bind our arraylist of data our view component via an adapter.
(d). Our CustomAdapter Class
  • Inflates our Custom View Item Layout
  • Binds data to our views
  • Starts and Sends data to our DetailActivity using Intent Object and StartActivity(intent)
(e). Our DetailActivity Class
  • Our Detail activity.
  • Receives data from our MainActivity via Intent.
  • Binds this data in detail activity hosted views.
(f). Our MainActivity Class
  • Our launcher activity.
  • Our Master Activity
  • We start our downloader, passing in URL as well as other parameters.

Our Layout

(a). activity_main.xml
(b). content_main.xml
  • Displays our GridView
(c). model.xml
  • Inflated into a single view item for our gridview.
(d). activity_detail.xml
  • Detail Activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
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="com.tutorials.hp.jsongridviewmdetail.DetailActivity">
<android.support.v7.widget.CardView 
android_orientation="horizontal" android_layout_width="match_parent"
android_layout_margin="5dp"
card_view_cardCornerRadius="10dp"
card_view_cardElevation="5dp"
android_layout_height="match_parent">
<LinearLayout
android_orientation="vertical"
android_layout_width="match_parent"
android_layout_height="match_parent"
android_weightSum="1">
<LinearLayout
android_orientation="horizontal"
android_layout_width="match_parent"
android_layout_height="wrap_content">
<ImageView
android_id="@+id/articleDetailImg"
android_layout_width="160dp"
android_layout_height="wrap_content"
android_paddingLeft="10dp"
android_paddingRight="10dp"
android_layout_alignParentTop="true"
android_scaleType="centerCrop"
android_src="@drawable/user" />
<LinearLayout
android_orientation="vertical"
android_layout_width="match_parent"
android_layout_height="wrap_content">
<TextView
android_id="@+id/nameDetailTxt"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_padding="5dp"
android_minLines="1"
android_textStyle="bold"
android_textColor="@color/colorAccent"
android_text="Title" />
<TextView
android_id="@+id/usernameDetailTxt"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_padding="5dp"
android_minLines="1"
android_textStyle="bold"
android_text="Username" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android_layout_width="fill_parent"
android_layout_height="match_parent"
android_layout_marginTop="?attr/actionBarSize"
android_orientation="vertical"
android_paddingLeft="5dp"
android_paddingRight="5dp"
android_paddingTop="5dp">
<TextView
android_id="@+id/emailDetailTxt"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_padding="5dp"
android_textColor="@color/colorAccent"
android_text="DATE" />
<TextView
android_id="@+id/descDetailTxt"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_padding="5dp"
android_textColor="#0f0f0f"
android_minLines="4"
android_text="This user has worked with our company for two years now.He has been dedicated and really a team player.The tasks we have assigned him have been executed expertly.He is a true professional..." />
<TextView
android_id="@+id/linkDetailTxt"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceMedium"
android_padding="5dp"
android_textColor="@color/colorPrimaryDark"
android_textStyle="italic"
android_text="Link" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>

Our Manifest

  • Make sure you add permission for accessing internet.
<?xml version="1.0" encoding="utf-8"?>
<manifest 
package="com.tutorials.hp.jsongridviewmdetail">
<uses-permission android_name="android.permission.INTERNET"/>
...
</manifest>

Download

You can download the full project here.

No. Resource Direct Links
1. GitHub Source Code Browse
2. Source Code Download
3. YouTube Channel