Json had became quickly my favorite and more comfortable way to output the data, because of the simplicity of convert any data type into this type of representation. Two weeks ago I had the need to read a json server response from within an android application, althought this should be quite straight forward in any language, I couldn´t help to feel a little misplaced since I haven´t touched the sdk in a long time.
The problem is as follow:
- We need to send a HTTP request to the server passing username and password in order to get the response. this must be done by a click button.
- Once we got the response we need to parse it into a json object.
- If the response was right then store the user and login values into the preferences.

And this is the code, hope it helps.
Layout : Generic login screen ( see reference )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/welcome_text"
android:text = "Welcome to My Application!n"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
/>
<TextView android:id="@+id/username_text"
android:text = "username:"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/welcome_text"
/>
<EditText android:id="@+id/txt_username"
android:layout_height="wrap_content"
android:layout_width="250px"
android:layout_centerHorizontal="true"
android:layout_below="@+id/username_text"
android:singleLine="true" />
<TextView android:id="@+id/password_text"
android:text = "password:"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txt_username"
/>
<EditText android:id="@+id/txt_password"
android:password="true"
android:layout_height="wrap_content"
android:layout_width="250px"
android:layout_centerHorizontal="true"
android:layout_below="@+id/password_text"
android:singleLine="true" />
<Button android:id="@+id/login_button"
android:text="Login!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/txt_password"
/>
</RelativeLayout>
Code : Json Client
package com.instropy.androiddexamples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class RestJsonClient {
public static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
JSONObject json = new JSONObject();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
json=new JSONObject(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
/**
*
* @param is
* @return String
*/
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Code : Front Activity
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class RestClient {
public static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
JSONObject json = new JSONObject();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
json=new JSONObject(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
/**
*
* @param is
* @return String
*/
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + “\n”);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
package com.instropy.androiddexamples;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.instropy.androiddexamples.net.RestJsonClient;
// implements OnClickListener so we don´t have to create a nested class << #ugly
public class HelloAndroid extends Activity implements OnClickListener {
private static final int SERVER_PORT = 80;
private static final String DEB_TAG = "Json_Android";
private String SERVER_HOST="instropy.com";
public static final String PREFS_NAME = "HelloAndroidPREFS";
private SharedPreferences settings;
private ProgressDialog progress;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(icicle);
// Restore preferences
settings = getSharedPreferences(PREFS_NAME, 0);
// load up the layout
setContentView(R.layout.main);
// get the button resource in the xml file and assign it to a local variable of type Button
Button login = (Button)findViewById(R.id.login_button);
Log.i(DEB_TAG,"onCreate");
login.setOnClickListener(this);
setUserNameText(settings.getString("Login", ""));
setPasswordText(settings.getString("Password", ""));
}
public void setUserNameText(String $username){
EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
usernameEditText.setText($username);
}
public void setPasswordText(String $username){
EditText passwordEditText = (EditText) findViewById(R.id.txt_password);
passwordEditText.setText($username);
}
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
//Handle based on which view was clicked.
Log.i(DEB_TAG+" onClick ","onClick");
// this gets the resources in the xml file
//and assigns it to a local variable of type EditText
EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
EditText passwordEditText = (EditText) findViewById(R.id.txt_password);
// the getText() gets the current value of the text box
// the toString() converts the value to String data type
// then assigns it to a variable of type String
String sUserName = usernameEditText.getText().toString();
String sPassword = passwordEditText.getText().toString();
//call the backend using Get parameters (discouraged but works good for this exampl
)
String address = "http://"+SERVER_HOST+":"+SERVER_PORT+"/jbackend.php?action=login&Login="+sUserName+"&Password="+sPassword+"";
if(usernameEditText == null || passwordEditText == null){
// show some warning
}else{
// display the username and the password in string format
try {
showBusyCursor(true);
progress = ProgressDialog.show(this,
"Please wait...", "Login in process", true);
Log.i(DEB_TAG, "Username: " + sUserName + "nPassword: " + sPassword);
Log.i(DEB_TAG, "Requesting to "+address);
JSONObject json = RestJsonClient.connect(address);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showBusyCursor(false);
}//end try
progress.dismiss();
SharedPreferences.Editor editor = settings.edit();
editor.putString("Login", (String) user.get("Login"));
editor.putString("Password", (String) user.get("Password"));
editor.commit();
showBusyCursor(false);
next();
}//end else
}//end OnClick
/*
*
*/
private void showBusyCursor(Boolean $show){
setProgressBarIndeterminateVisibility($show);
}
private void next(){
// you can call another activity by uncommenting the above lines
//Intent myIntent = new Intent( this.getBaseContext() , LoggedActivity.class);
//startActivityForResult(myIntent, 0);
}
}
Update
As of the write of this post I`ve received several comments telling me to use a SSL connection , the aim of this post is just to show the concept proof of how to connect your interface to the backend using android and json, you can use this source code as you want but keep in mind use a secure connection for the login for god sake.
Here´s a good link to begin http://java.sun.com/developer/technicalArticles/Security/secureinternet/