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.

<?php
$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();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
?> 
You can see the output of  php by clicking below url:
http://cpriyankara.coolpage.biz/employee_details.php

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
http://codeoncloud.blogspot.com/2013/07/android-web-service-access-using-async.html

Android list view
http://codeoncloud.blogspot.com/2013/07/how-to-populate-android-list-view-from.html

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.app.Activity;
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 = "http://cpriyankara.coolpage.biz/employee_details.php";
 private ListView listView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listView = (ListView) findViewById(R.id.listView1);
  accessWebService();
 }

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

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

   catch (ClientProtocolException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   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) {
     answer.append(rLine);
    }
   }

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

  @Override
  protected void onPostExecute(String result) {
   ListDrwaer();
  }
 }// 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(),
     Toast.LENGTH_SHORT).show();
  }

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
    android.R.layout.simple_list_item_1,
    new String[] { "employees" }, new int[] { android.R.id.text1 });
  listView.setAdapter(simpleAdapter);
 }

 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="http://schemas.android.com/apk/res/android"
    package="com.axel.mysqlphpjson"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <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="com.axel.mysqlphpjson.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>

Code for main activity layout.
<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=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp" >
    </ListView>

</RelativeLayout>
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.
Prerequisites.
- Titanium studio with Android sdk
- Download the appropriate version of Android ndk from here http://developer.android.com/tools/sdk/ndk/index.html and extract it.
- Install Python 2.5 or above and set path for Python  in Windows system variables http://www.python.org/getit/
- Install Eclipse jdt plugin for Titanium.
http://docs.appcelerator.com/titanium/latest/#!/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.



Enter
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 ExampleProxy.java and Module.java
Open build.properties under the platform directory


By default that configures for the paths of
         titanium.platform
         android.platform
         google.apis


titanium.platform=C:\\Users\\cpriyankara\\AppData\\Roaming\\Titanium\\mobilesdk\\win32\\3.1.1.GA\\android
android.platform=C:\\SDK-Titanium\\sdk\\platforms\\android-10
google.apis=C:\\SDK-Titanium\\sdk\\add-ons\\addon-google_apis-google-10

You need to include path for Android ndk there. ie the location where you extracted the ndk archive. Add following line to build.properties
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.
<modules>
        <module platform="android" version="1.0">com.my.module</module>
</modules>
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.

References:
http://docs.appcelerator.com/titanium/3.0/#!/guide/Android_Module_Development_Guide-section-29004945_AndroidModuleDevelopmentGuide-Overview
https://wiki.appcelerator.org/display/tis/Using+Titanium+Modules