Simple JSON Parsing Example in Android – Part V

In this blog post, ill show you how to Retrieving JSON data from a Secured Site with Basic Authentication.

My Other blog post on JSON Tutorial.

  1. Part I – What is JSON and how to code JSON data on Php
  2. Part II – How to retrieve a simplest JSON data in Android
  3. Part III – How to retrieve a JSON data to ListView in Android
  4. Part IV – How to retrieve a complex typed JSON data in Android
  5. Part V – How to retrieve a JSON data from a Secured Site with Basic Authentication
  6. Part VI – How to Pass a JSON data to Php as a Parameters

 

Please read Part I of this blog, there you can create JSON data in php. I’m using Example 3 from that blog in this tutorial for making this blog to be simple. Hope you have created JSON data in php, so lets get started with retrieving in Android.

Step 1: Create a new project File -> Android Project. While creating a new project give activity name as MainActivity and copy paste this code.


package com.skholingua.android.retrieving_secured_json_data;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
/** Called when the activity is first created. */
ListView list;
Button getdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private static String url = "http://serviceapi.skholingua.com/secured-feeds/list_multipletext_json.php";
private static final String TAG_OS = "Android Version List";
private static final String TAG_VER = "Version No";
private static final String TAG_NAME = "Version Name";
private static final String TAG_API = "API Level";

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

getdata = (Button) findViewById(R.id.getdata);
getdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONParse().execute();
getdata.setVisibility(View.INVISIBLE);
}
});

list = (ListView) findViewById(R.id.list);

}

private class JSONParse extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();

pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected Void doInBackground(Void... args) {
String _username = "admin";
String _password = "password";
String content = MyHttpURLConnection.getData(url, _username, _password);
try {
// Getting JSON Object from URL Content
JSONObject json = new JSONObject(content);
JSONArray jsonArray = json.getJSONArray(TAG_OS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String ver = c.getString(TAG_VER);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);

}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void args) {
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_child, new String[] { TAG_VER, TAG_NAME,
TAG_API }, new int[] { R.id.vers, R.id.name,
R.id.api });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(
MainActivity.this,
"You Clicked at "
+ oslist.get(+position).get(TAG_NAME),
Toast.LENGTH_SHORT).show();
}
});
}
}

}

Step 2: Create a new class, MyHttpURLConnection.java and copy paste this code.


package com.skholingua.android.retrieving_secured_json_data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.protocol.HTTP;

import android.util.Base64;

public class MyHttpURLConnection {

public static String getData(String uri, String userName, String password) {

BufferedReader reader = null;
byte[] loginBytes = (userName + ":" + password).getBytes();
StringBuilder loginBuilder = new StringBuilder().append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.NO_WRAP));
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.addRequestProperty("Authorization", loginBuilder.toString());
con.setUseCaches(false);
con.connect();
InputStream is = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8));
String data = null;
StringBuilder sb = new StringBuilder();
while ((data = reader.readLine()) != null) {
sb.append(data + "\n");
}
return sb.toString();

} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

}
}

Step 3: Open your activity_main.xml and copy paste this code:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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.skholingua.android.retrieving_secured_json_data.MainActivity" >

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/getdata"
android:layout_alignParentTop="true" />

<Button
android:id="@+id/getdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Get Data" />

</RelativeLayout>

Step 4: Open your AndroidManifest.xml and add Internet Permission.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.skholingua.android.retrieving_secured_json_data"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />

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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

ScreenShot:

Screenshot_2015-04-06-18-33-00 Screenshot_2015-04-06-18-33-08 Screenshot_2015-04-06-18-33-12


Tips to Remember always:

1. There is Nothing much difference between Part III blog vs this blog, except accessing a secured site with username and password credentials.

2. For Basic authentication, i’m using via .htaccess with password protecting a directory. for more details please this blog post.

3. The client-side authentication consists on a HTTP header called Authorization. Its value is a Base64-encoded string, with the following format:

username:password

After encoded, the header will look like this:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==


 

Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.

Download Source Code from here.




durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi

Leave a Reply

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