Wednesday, July 31, 2013

Android MySQL PHP & JSON tutorial

In this post I'm going to describe how we can read data from MySQL database and show them in a Android list view. You can download the complete Android project from here. To fetch data here I used a PHP script which encodes data into json format.
This project has three main parts.
1. MySQL database
2. PHP web service
3.Android web service client

1. MySQL database.
My database has only one table named "emp_info" and it has two columns. "employee name" and "employee no". "employee no" is the primary key.

2.PHP web service
Use following PHP script to fetch data from the database and to encode data in to json format.

$host="XXXXX"; //replace with database hostname 
$username="XXXXX"; //replace with database username 
$password="XXXXX"; //replace with database password 
$db_name="XXXXXX"; //replace with database name

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info"; 
$result = mysql_query($sql);
$json = array();

echo json_encode($json); 
You can see the output of  php by clicking below url:

3.Android web service client.
This part is bit complected. Android activity is a combination of Async Task json and list view. If you are not familiar with those stuff look following tutorials.

Android Async Task and web service access

Android list view

Here is the code for main Android activity.
package com.axel.mysqlphpjson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
 private String jsonResult;
 private String url = "";
 private ListView listView;

 protected void onCreate(Bundle savedInstanceState) {
  listView = (ListView) findViewById(;

 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(, menu);
  return true;

 // Async Task to access the web
 private class JsonReadTask extends AsyncTask<String, Void, String> {
  protected String doInBackground(String... params) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(params[0]);
   try {
    HttpResponse response = httpclient.execute(httppost);
    jsonResult = inputStreamToString(

   catch (ClientProtocolException e) {
   } catch (IOException e) {
   return null;

  private StringBuilder inputStreamToString(InputStream is) {
   String rLine = "";
   StringBuilder answer = new StringBuilder();
   BufferedReader rd = new BufferedReader(new InputStreamReader(is));

   try {
    while ((rLine = rd.readLine()) != null) {

   catch (IOException e) {
    // e.printStackTrace();
      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
   return answer;

  protected void onPostExecute(String result) {
 }// end async task

 public void accessWebService() {
  JsonReadTask task = new JsonReadTask();
  // passes values for the urls string array
  task.execute(new String[] { url });

 // build hash set for list view
 public void ListDrwaer() {
  List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

  try {
   JSONObject jsonResponse = new JSONObject(jsonResult);
   JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");

   for (int i = 0; i < jsonMainNode.length(); i++) {
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
    String name = jsonChildNode.optString("employee name");
    String number = jsonChildNode.optString("employee no");
    String outPut = name + "-" + number;
    employeeList.add(createEmployee("employees", outPut));
  } catch (JSONException e) {
   Toast.makeText(getApplicationContext(), "Error" + e.toString(),

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
    new String[] { "employees" }, new int[] { });

 private HashMap<String, String> createEmployee(String name, String number) {
  HashMap<String, String> employeeNameNo = new HashMap<String, String>();
  employeeNameNo.put(name, number);
  return employeeNameNo;

Add Internet permission to AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="17" />

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

        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


Code for main activity layout.
<RelativeLayout xmlns:android=""
    tools:context=".MainActivity" >

        android:layout_marginTop="14dp" >

Quick demo of the application:

Was above information helpful?
Your comments always encourage me to write more...

Monday, July 29, 2013

How to create a basic Android module for Appcelerator Titanium

In Titanium  using a module we can extend the built-in functionality of the Titanium Mobile SDK. In this post I'm going to illustrate how we can create a default Hello world Android module and how to install it to your project.
First of all we need to setup the development environment. See below requirements.
- Titanium studio with Android sdk
- Download the appropriate version of Android ndk from here and extract it.
- Install Python 2.5 or above and set path for Python  in Windows system variables
- Install Eclipse jdt plugin for Titanium.!/guide/Installing_the_Java_Development_Tools

Note : Your Titanium work space name should not have spaces

Then lets see how to create the Android module using ide.
Open Titanium studio.
Select File >> New >> Mobile Module Project

In next window, enter following information

Project name: Desired project name
Titanium SDK Version: Targeted version of Titanium SDK
Deployment target: Since this is Android module select Android


Click Next to edit Module Manifest File.

Version: Version of the module.

Author, License and description, etc.

At last click Finish to create the module.
After creating the module you can see src folder under project directory. By default there are two java classes and
Open under the platform directory

By default that configures for the paths of


You need to include path for Android ndk there. ie the location where you extracted the ndk archive. Add following line to
android.ndk = C:\\android_ndk\\android-ndk-r8e

Then right click on Build.xml and select Run As Ant Build

After complete the build process finally you should be able to see BUILD SUCCESSFUL message.

Then let's see how can we install created module in to Android Titanium project.
First of all Create new mobile project.(File >> New >> Mobile Project)

In next window select Classic from left side pane. Then select Default Project and click Next.

Fill Project name and app id fields. Select Android as Deployment target. Finally click Finish to create the project.

Next we need to install the created module in to our project. Open the module from project explorer. And open “dist” folder. In dist directory you can find the module in zipped  and jar formats.

Copy and paste the zipped archive to the root of your newly created project.

Then open tiapp.xml in xml view

Add following lines after the </mobileweb> tag to add and register the module.
        <module platform="android" version="1.0"></module>
Here give same module version and module id as you provided when creating the module. Then press ctrl + s to save the change to Tiapp.xml. And test run the project on emulator. Make sure that your project is running without any module related errors.