Cara menghubungkan Android dengan PHP, MySQL 2017 PART 4

Android Codelist

6.d) Updating a Row in MySQL (Updating product details)

Create a php file named update_product.php to update product details. Each product is identified by pid.
update_product.php
<?php
/*
 * Following code will update a product information
 * A product is identified by product id (pid)
 */
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['pid']) && isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
    $pid = $_POST['pid'];
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];
    // 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 products SET name = '$name', price = '$price', description = '$description' WHERE pid = $pid");
    // 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);
}
?>
The json reponse of above code, when product is updated successfully
{
    "success": 1,
    "message": "Product successfully updated."
}

6.e) Deleting a Row in MySQL (Deleting a product)

The last operation is deletion on database. Create a new php file called delete_product.php and paste the following code. The main functionality of this file is to delete a product from database.
delete_product.php
<?php
/*
 * Following code will delete a product from table
 * A product is identified by product id (pid)
 */
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
    // 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("DELETE FROM products WHERE pid = $pid");
    // 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);
}
?>
When product successfully deleted
{
    "success": 1,
    "message": "Product successfully deleted"
}
When product not found
{
    "success": 0,
    "message": "No product found"
}
Until now, we built a simple api for our products table. We are now done with the server side coding (PHP) and its time to take a break and start our actual android application coding.

7. Creating Android Application

Create a new project in your Eclipse IDE by filling the required details.
1. Create new project in Eclipse IDE by going to File ⇒ New ⇒ Android Project and name the Activity class name as MainScreenActivity.
2. Open your AndroidManifest.xml file and add following code. First i am adding all the classes i am creating to manifest file. Also i am adding INTERNET Connect permission.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:configChanges="keyboardHidden|orientation"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainScreenActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- All Product Activity -->
        <activity
            android:name=".AllProductsActivity"
            android:label="All Products" >
        </activity>
        <!-- Add Product Activity -->
        <activity
            android:name=".NewProductActivity"
            android:label="Add New Product" >
        </activity>
        <!-- Edit Product Activity -->
        <activity
            android:name=".EditProductActivity"
            android:label="Edit Product" >
        </activity>
    </application>
    <!--  Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>
3. Now create a new xml file under res ⇒ layout folder and name it as main_screen.xml This layout file contains two simple buttons to view all products and add a new product.
main_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">
    <!--  Sample Dashboard screen with Two buttons -->
    <!--  Button to view all products screen -->
    <Button android:id="@+id/btnViewProducts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="View Products"
        android:layout_marginTop="25dip"/>
    <!--  Button to create a new product screen -->
    <Button android:id="@+id/btnCreateProduct"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add New Products"
        android:layout_marginTop="25dip"/>
</LinearLayout>
main screen
4. Open you main activity class which is MainScreenActivity.java and write click events for two button which are mentioned in main_screen.xml layout.
MainScreenActivity.java
package com.example.androidhive;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainScreenActivity extends Activity{
    Button btnViewProducts;
    Button btnNewProduct;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);
        // Buttons
        btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
        btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);
        // view products click event
        btnViewProducts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Launching All products Activity
                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);
            }
        });
        // view products click event
        btnNewProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Launching create new product activity
                Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
                startActivity(i);
            }
        });
    }
}

COMMENT