CRUD operation using jquery mobile on android – Part 3

Hi, I’m coming back. Unfortunately I’m not writing this tutorial for part 3 because I found a lot of flawless using jquery mobile especially to DOM issue. If you still resist want to learn developing a hybrid app for iOS and android from A-Z, you can go to this tutorial.

http://blog.revivalx.com/2014/07/15/simple-hybrid-mobile-app-using-cordova-and-ratchet-2-complete/

sorry..

sorry..

I’m apologise for my mistake..

CRUD operation using jquery mobile on android – Part 2

This is a second part of 2-part tutorial series on CRUD operation using jquery mobile on android. In the first tutorial, you learned how to setup your android environment, create cordova/phonegap project using eclipse and node.js and how to test your app using android simulator without device.

http://blog.revivalx.com/2014/02/21/crud-operation-using-jquery-mobile-on-android-part-1/

In this second part, you will learn how to create a simple web service for your app. Your web service will enable to create, read, update and data using JSON ( Javascript Object Notation) to your database. We will not using SOAP (Simple Object Access Protocol) for this tutorial because JSON is easy to learn and simple compare to SOAP is too complex for beginner. It basically works on HTTP protocol.

URL Structure

In web service design the URL endpoints should be well formed and should be easily understandable. Every URL for a resource should be uniquely identified.

For example

GET – http://localhost:8888/crud_tutorial/product/index

GET – http://localhost:8888/crud_tutorial/product/display?productId=1

POST – http://localhost:8888/crud_tutorial/product/create

POST – http://localhost:8888/crud_tutorial/product/update?productId=1

POST – http://localhost:8888/crud_tutorial/product/delete?productId=1

Why we using JSON for mobile application? Why not we access directly to our database without using JSON instead PHP or JAVA. It is because hybrid mobile app support client side languages, not servers side languages. Hybrid mobile app consists these 3 languages are HTML5, CSS and Javascript. We can’t simply run PHP or JAVA in mobile app. This video will answer these questions.

Getting started.

For this tutorial you need to have basic in PHP and Mysql. You need to have eclipse Helios to complete the project. Compare to previous tutorial we using eclipse Juno. It is because we develop an android app. For eclipse PHP we develop web service using PHP.

First you need to setup a web server in your machine. I’m using MAMP (stands for Mac, Apache, Mysql and Php) for this tutorial. It’s ok if your want to use other than this such as XAMPP or WAMP. No problem with that. But i suggest you using MAMP if you using Mac. There will be a lot of glitches if you using XAMPP or WAMP in your apple machine.

Download MAMP from this site and install to your machine. After finish installed MAMP to your machine, start apache server and mysql server. So far I didn’t get any issues starting my web server compare to XAMPP. If you got problem start up your apache server, make sure you check port 80 because maybe other applications using the same port especially skype. you need to terminate the application before start the apache server. This issue always happened to windows users.

If your apache and mysql server running successful, you will get like this (green light on both server status).

MAMP

MAMP

Then open your chrome browser. Why I’m using chrome rather than other browser because there are a tons of chrome extensions available in chrome marketplace. That’s why i choose to live with it. Type this to open your MAMP start page in your browser.

http://localhost:8888/MAMP/?language=English

Then click phpMyAdmin at top of the bar. You will see this page.

phpmyadmin

phpmyadmin

You need to create a database and a table for this tutorial. Click database tab. Then create ‘crud_tutorial‘. Copy this sql script to your sql tab to generate product table.

CREATE TABLE `product` (
`productId` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
`description` varchar(500) NOT NULL,
`quantity` decimal(10,0) NOT NULL,
`price` decimal(10,0) NOT NULL,
`dateCreated` datetime NOT NULL,
`dateUpdated` datetime NOT NULL,
PRIMARY KEY (`productId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

After executing these queries go through each tables and make sure that everything created correctly. Until now we are done with getting your system ready for development. Run your eclipse Helios to start develop web service. Right click in PHP explore > New > PHP Project.

eclipe helios

eclipe helios

Type crud_tutorial in project name. At content part, choose create project at existing location (from existing source). Type path name in directory field. /Applications/MAMP/htdocs/crud_tutorial  . Click Finish.

create project

create project

Right click in your project, select New > PHP File .

PHP File

PHP File

Type db_config.php and click Finish.

New php file

New php file

You need to create 5 more php files for db_connect.php, create_product.phpget_product_details.php, get_all_products.php, update_product.php and delete_product.php. You can check reference that I take from this site for this tutorial.

db_connect.php – database configuration / setting.

db_connect.php – database connection.

create_product.php – create product details into database.

get_product_details.php – get product details base on product id from database.

get_all_products – retrieve all list of products.

update_product.php – update product into database base on product id.

delete_product.php – delete product from database base on product id.

Fill up all these PHP files using these code.

db_connect.php

<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', "root"); // db password (mention your db password here)
define('DB_DATABASE', "crud_tutorial"); // database name
define('DB_SERVER', "localhost"); // db server
?>

db_connect.php

<?php
class DB_CONNECT {
 
    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }
 
    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }
 
    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';
 
        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
 
        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
 
        // returing connection cursor
        return $con;
    }
 
    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }
 
}
 
?>

create_product.php

<?php
  
/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */
  
// array for JSON response
$response = array();
  
// check for required fields
if (isset($_POST['name']) && isset($_POST['description']) && isset($_POST['quantity']) && isset($_POST['price'])) {
  
    $name = $_POST['name'];
    $description = $_POST['description'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
  
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
  
    // connecting to db
    $db = new DB_CONNECT();
  
    // mysql inserting a new row
    $result = mysql_query("INSERT INTO product(name, description, quantity, price, dateCreated, dateUpdated) VALUES('$name', '$description', '$quantity', '$price', NOW(), NOW())");
  
    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
  
        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
  
        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
  
    // echoing JSON response
    echo json_encode($response);
}
?>

get_product_details.php

<?php
  
/*
 * Following code will get single product details
 * A product is identified by product id (productId)
 */
  
// array for JSON response
$response = array();
  
// include db connect class
require_once __DIR__ . '/db_connect.php';
  
// connecting to db
$db = new DB_CONNECT();
  
// check for post data
if (isset($_GET["productId"])) {
    $productId = $_GET['productId'];
  
    // get a product from product table
    $result = mysql_query("SELECT *FROM product WHERE productId = $productId");
  
    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {
  
            $result = mysql_fetch_array($result);
  
            $product = array();
            $product["productId"] = $result["productId"];
            $product["name"] = $result["name"];
            $product["description"] = $result["description"];
            $product["price"] = $result["price"];
            $product["price"] = $result["price"];
            $product["dateCreated"] = $result["dateCreated"];
            $product["dateUpdated"] = $result["dateUpdated"];
            // success
            $response["success"] = 1;
  
            // user node
            $response["product"] = array();
  
            array_push($response["product"], $product);
  
            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No product found";
  
            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";
  
        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
  
    // echoing JSON response
    echo json_encode($response);
}
?>

get_all_products.php

<?php
  
/*
 * Following code will list all the products
 */
  
// array for JSON response
$response = array();
  
// include db connect class
require_once __DIR__ . '/db_connect.php';
  
// connecting to db
$db = new DB_CONNECT();
  
// get all products from product table
$result = mysql_query("SELECT *FROM product") or die(mysql_error());
  
// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();
  
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["productId"] = $row["productId"];
        $product["name"] = $row["name"];
        $product["description"] = $row["description"];
        $product["quantity"] = $row["quantity"];
        $product["price"] = $row["price"];
        $product["dateCreated"] = $row["dateCreated"];
        $product["dateUpdated"] = $row["dateUpdated"];
  
        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;
  
    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";
  
    // echo no users JSON
    echo json_encode($response);
}
?>

update_product.php

<?php
  
/*
 * Following code will update a product information
 * A product is identified by product id (productId)
 */
  
// array for JSON response
$response = array();
  
// check for required fields
if (isset($_POST['productId']) && isset($_POST['name']) && isset($_POST['description']) && isset($_POST['quantity']) && isset($_POST['price'])) {
  
    $productId = $_POST['productId'];
    $name = $_POST['name'];
    $description = $_POST['description'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
     
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
  
    // connecting to db
    $db = new DB_CONNECT();
  
    // mysql update row with matched pid
    $result = mysql_query("UPDATE product SET name = '$name', description = '$description' , quantity = '$quantity' , price = '$price', dateUpdated = NOW() WHERE productId = $productId");
  
    // check if row inserted or not
    if ($result) {
        // successfully updated
        $response["success"] = 1;
        $response["message"] = "Product successfully updated.";
  
        // echoing JSON response
        echo json_encode($response);
    } else {
  
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
  
    // echoing JSON response
    echo json_encode($response);
}
?>

delete_product.php

<?php
  
/*
 * Following code will delete a product from table
 * A product is identified by product id (productId)
 */
  
// array for JSON response
$response = array();
  
// check for required fields
if (isset($_POST['productId'])) {
    $productId = $_POST['productId'];
  
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
  
    // connecting to db
    $db = new DB_CONNECT();
  
    // mysql update row with matched productId
    $result = mysql_query("DELETE FROM product WHERE productId = $productId");
  
    // check if row deleted or not
    if (mysql_affected_rows() > 0) {
        // successfully updated
        $response["success"] = 1;
        $response["message"] = "Product successfully deleted";
  
        // echoing JSON response
        echo json_encode($response);
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";
  
        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
  
    // echoing JSON response
    echo json_encode($response);
}
?>

After you fill up the files, you need to install Curl in your machine. Curl is a command line tool for transferring data with URL syntax. Install curl via npm. Type this command to install. If you using windows, run this command in your command prompt. Make sure you install node.js first.

npm install curl

npm install curl

npm install curl

Run this command to test create_product.php in your terminal.

curl POST

curl POST

curl -X POST -F name=The\ Promise\ of\ Spring -F description=With\ Valentine’s\ Day\ come,\ can\ Spring\ be\ far\ behind? -F quantity=3 -F price=21 http://localhost:8888/crud_tutorial/create_product.php

Success status for create_product.php

{"success":1,"message":"Product successfully created."}

Proceed all these curl commands for each URLs

get_product_details.php

curl http://localhost:8888/crud_tutorial/get_product_details.php?productId=1

Success status for get_product_details.php

{
    "success": 1,
    "product": [{
        "productId": "1",
        "name": "The Promise of Spring",
        "description": "With Valentine\u2019s Day come, can Spring be far behind?",
        "price": "21",
        "dateCreated": "2014-02-26 10:26:19",
        "dateUpdated": "2014-02-26 10:26:19"
    }]
}

get_all_products.php

curl http://localhost:8888/crud_tutorial/get_all_products.php

Success status for get_all_products.php

{
    "products": [{
        "productId": "1",
        "name": "The Promise of Spring",
        "description": "With Valentine\u2019s Day come, can Spring be far behind?",
        "quantity": "3",
        "price": "21",
        "dateCreated": "2014-02-26 10:26:19",
        "dateUpdated": "2014-02-26 10:26:19"
    }, {
        "productId": "2",
        "name": "The Rapture of Psyche",
        "description": "Now we're getting a bit more serious!",
        "quantity": "3",
        "price": "21",
        "dateCreated": "2014-02-26 00:00:00",
        "dateUpdated": "2014-02-26 00:00:00"
    }, {
        "productId": "3",
        "name": "Thrilling Love",
        "description": "This girl's got her hockey hunk right where she wants him!",
        "quantity": "3",
        "price": "21",
        "dateCreated": "2014-02-26 00:00:00",
        "dateUpdated": "2014-02-26 00:00:00"
    }],
    "success": 1
}

update_product.php

curl -X POST -F productId=1 -F name=The\ Promise\ of\ Spring -F description=With\ Valentine’s\ Day\ come,\ can\ Spring\ be\ far\ behind? -F quantity=3 -F price=21 http://localhost:8888/crud_tutorial/update_product.php

Success status for update_product.php

{"success":1,"message":"Product successfully updated."}

delete_product.php

curl -X POST -F productId=3 http://localhost:8888/crud_tutorial/delete_product.php

Success status for delete_product.php

{"success":1,"message":"Product successfully deleted"}

I thinks thats all tutorial for a simple web service. Later we will integrate this web service with android app. Stay tune and enjoy!!

Service Finder Mobile

Service Finder Mobile is an open source mobile application built using PhoneGap (Apache Cordova) that helps users provide and find services in Malaysia.

The Service Finder Mobile uses the following technologies:

The entire user interface of the application is created dynamically at runtime based on jquery mobile.  You can download the full application source code at https://github.com/datomnurdin/service-finder-mobile.  Feel free to fork it, or use it as a learning tool to build UI experiences for PhoneGap applications.

Enjoy !

4 great hybrid mobile app references

What is hybrid mobile app? Referring to  Nielsan Norman Group, “hybrid mobile app is part native apps, part web apps. Like native apps, they live in an app store and can take advantage of the many device features available. Like web apps, they rely on HTML being rendered in a browser, with the caveat that the browser is embedded within the app”.

Many amateur programmers didn’t know how to develop a simple hybrid mobile app. It is because they didn’t know where to start, how to develop with correct tools and techniques and when they can actually start build the hybrid mobile app. Sometimes the hybrid mobile app can be done but without correct tools, it can’t be done on time.

Nowadays the mobile is very important in daily life. Mobile is primary. According to Gartner, 91% of mobile users keep their device within arm’s reach 100% of the time. They mostly prefer using mobile rather than laptop or PC to surf internet. It because it so much easier to carry out everywhere.

Today I would like to share with you 10 great hybrid mobile app references.

Jquery

jquery

http://jquery.com

Jquery Mobile

jquery mobile

http://jquerymobile.com

Phonegap

phonegap

http://phonegap.com

Backbone.js

http://backbonetutorials.com