Lab 7 (Part1 Update) [Part 2 Delete]

 

Part 1: Get Selected Product Details


In this segment, we will implement this portion of the program flow.  We will have to create the EditProductActivity in Android, and the get_product_detailsVolley.php file for server-side scripting

Let us proceed to create the EditProductActivity first.

 1.     Open your Android project that you have developed in Lab 10.  Add in an Empty Views Activity and name it “EditProductActivity”.

 Design the xml layout for this Activity similar to what is shown below.  You may use the xml codes shown in next page for this layout


The xml codes for activity_edit_product.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- Name Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Product Name"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>

    <!-- Input Name -->
    <EditText android:id="@+id/inputName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"/>

    <!-- Price Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Price"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>

    <!-- Input Price -->
    <EditText android:id="@+id/inputPrice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"
        android:inputType="numberDecimal"/>

    <!-- Description Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Description"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>

    <!-- Input description -->
    <EditText android:id="@+id/inputDesc"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:lines="4"
        android:gravity="top"/>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <!-- Button Create Product -->
        <Button android:id="@+id/btnSave"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Save Changes"
            android:layout_weight="1"/>

        <!-- Button Create Product -->
        <Button android:id="@+id/btnDelete"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Delete"
            android:layout_weight="1"/>
    </LinearLayout>

</LinearLayout>


Add a listener to the ListView  

1.     In the AllProductActivity.java, In order for the list item in the ListView to respond to the click event and load the EditProductActivity, add the following codes inside the OnCreate() method.  Note that we are passing the value of the product id to EditProductivity via Intent. 

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
        
        // getting pid value from selected ListItem
        String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();

        // Starting new intent
        Intent in = new Intent(getApplicationContext(), EditProductActivity.class);
        // sending pid to next activity
        in.putExtra("product_id", pid);
        // starting new activity EditProductActivity
        startActivity(in);
    }
});


Run the app now. You should be able to navigate to EditProductActivity from AllProductActivity, but the values of the Product Details are empty.

  In order to populate the product details in EditProductActivity, we need to send a Volley request with the selected product id, to the get_product_detailsVolley.php file.  This php file will retrieve the product id sent by Volley, connect to the database, retrieve the product details based on the product id, and echo the formatted result back.

EditProductActivity.java

1.     Add the following variable declarations at the correct section of EditProductActivity.java

// url to get selected product details
private static final String url_product_details = MainActivity.ipBaseAddress+"/get_product_detailsVolley.php";

//To store the value of product id sent from AllProductActivity
String pid;

//define the type of volley request to be used to distinguish different volley response.
private final int get_product_details = 1;
private final int update_delete_product = 2;

//variables to store resource ids of EditText & Buttons
EditText txtName;
EditText txtPrice;
EditText txtDesc;
Button btnSave;
Button btnDelete;


Inside the OnCreate() method of EditProductActivity.java file, add the following codes. Note that we need to define the method postData(), which needs to have 3 parameters, viz, url that specifies the php file to connect to, params that contains product id in Hashmap, and the 3rd parameter that specifies the Volley request type so that the Android app can distinguish the different Volley response from server.


//get the resource ids
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
// create an Intent to receive pid sent from AllProductsActivity
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra("product_id");
// use Hashmap to store product id in key-valye pair
Map<String,String> params_pid = new HashMap<String,String>();
params_pid.put("pid",pid);

//postData method to use Volley to retrieve selected product details from database
postData(url_product_details, params_pid, get_product_details);

1.     Add the following codes for the postData() method inside the EditProductActivity class, to send product id using Volley HTTP Post to server, and to handle the received product information from server and display them on the Android screen.


public void postData(String url, Map params, final int requestType) {
    //create a RequestQueue for Volley
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //create a StringRequest for Volley for HTTP Post and send pid stored in params Map
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            //response from server
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //if response from get product details request
                    if (requestType == get_product_details) {
                        //check if error code received from server.
                        if (response.equals("Error")) {
                            Toast.makeText(getApplicationContext(), "Error in accessing database", Toast.LENGTH_LONG).show();
                            return;
                        }
                        //handle the response data received from server
                        //store retrieved product from database in String array - only one product
                        String[] products = response.split(":");
                        //retrieve and store the product info in variable
                        String[] details = products[0].split(";");
                        String id = details[0];
                        String name = details[1];
                        String price = details[2];
                        String description = details[3];
                        //display product info in EditText
                        txtName.setText(name);
                        txtPrice.setText(price);
                        txtDesc.setText(description);
                    }
                }
            },
            //Error in Volley
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // handle Volley Error
                    Toast.makeText(getApplicationContext(), "Error in Volley ", Toast.LENGTH_LONG).show();
                }
            }
    ) {
        @Nullable
        @Override
        protected Map<String, String> getParams() {
            //send pid stored in HashMap using HTTP Post in Volley
            return params;
        }
    };
    //add StringRequest to Volley Queue
    requestQueue.add(stringRequest);
}



PHP file at webserver:  get_product_detailsVolley.php

 

1.     We will now work on the php file that will receive the Volley request, retrieve the product id, query the database, format and return the query result to the Android app.

 

Create a new php file in Visual Studio and enter the following codes. Save it in the C:\xampp\htdocs\products directory as “get_product_detailsVolley.php”


<?php  
/*/*
 * Following code will get single product details from database
 * A product is identified by product id (pid)
 */
//check that pid is sent in HTTP Post
 if (isset($_POST["pid"])) {
  
    //get the pid from http post
     $pid = $_POST['pid'];
  
    // include db connect class
      require_once __DIR__ . '/db_connect.php';
    // connecting to db
      $db= new DB_CONNECT();
      $db->connect();
  
    // get the product from products table with given pid
      $sqlCommand="SELECT * FROM products WHERE pid = $pid";
      $result =mysqli_query($db->myconn, "$sqlCommand");

    $productresult ="";
    // check for empty result
    if (mysqli_num_rows($result) > 0) 
    {
        // looping through all results – in this case, only one product
        while ($row = mysqli_fetch_array($result)) {
          //product information is separated by ";"
            $productresult = $productresult.$row["pid"].";" .$row["name"].";".$row["price"].";".$row["description"].":";
        }
        //return product with separator to requesting client
        echo ($productresult);
    }
    else {
     // no products found
     echo("Error"); 
    }
} else echo("Error");
?>

   Run the app now.  Ensure that you have started your Apache Webserver and MySQL database server in the XAMPP server.  You also have to update the IP address in the MainActivity.java. You should see the product details populated as shown below in the EditProductActivity.

Part 2: Update & Delete Selected Product from Database

 

In this segment, we will implement this portion of the program flow.  We will have to edit the EditProductActivity in Android, and create the two php files “update_productVolley.php” and “delete_productVolley.php”.

 

To Save the Updated Product Details

 1.     In the EditProductActivity.java file, add the following 2 variable declarations:

// url to update product
private static final String url_update_product = MainActivity.ipBaseAddress+"/update_productVolley.php";
// url to delete product
private static final String url_delete_product = MainActivity.ipBaseAddress+"/delete_productVolley.php";


1.     Then add the following codes for the “Save” Button inside the OnCreate() method.  These codes will get the updated product details from EditText, store them in HashMap and pass it to the postData() to send Volley request to webserver.

 


//Save button click event
btnSave.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0){
        //retrieve new product info from EditText
        String name = txtName.getText().toString();
        String price = txtPrice.getText().toString();
        String description = txtDesc.getText().toString();
        //store the new product info in HashMap for sending to server
        Map<String,String> params_update = new HashMap<String,String>();
        params_update.put("pid",pid);
        params_update.put("name",name);
        params_update.put("price",price);
        params_update.put("description",description);

        //postData method to use Volley to update new product details in database
        postData(url_update_product,params_update,update_delete_product);
    }
});

1.     Next, we will add the following codes inside the onResponse( ) method, highlighted in yellow shown next page, to handle the Volley response to either update or remove the product from the database.  In both the cases in updating and deleting product from the database, the server response will be either “Success” or “Error”. 



public void onResponse(String response) {
    //if response from get product details request
    if (requestType==get_product_details) {
	:
	:
	:
    }
    //if response from update delete request
    if (requestType==update_delete_product) {

        if (response.equals("Error"))
        {
            Toast.makeText(getApplicationContext(),"Error in updating database", Toast.LENGTH_LONG).show();
        }
        if(response.equals("Success"))
        {
            Toast.makeText(getApplicationContext(),"Success in updating database", Toast.LENGTH_LONG).show();
            finish();
            //load the AllProductActivity with updated ListView
            Intent i = new Intent (getApplicationContext(), AllProductsActivity.class);
            startActivity(i);
        }
    }
}



1.     We will next create the new PHP file, “update_productVolley.php” in Visual Studio Code, and save it in C:\xampp\htdocs\products folder.  Enter the following php codes:


<?php
/*
 * Following code will update the selected product information
 * All product details are read from HTTP Post Request from Volley
 */
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description']) && isset($_POST['pid']) ) {
 
    //retrieve the values for new product information
    $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
    $myConnection= new DB_CONNECT();
    $myConnection->connect();
    
    //sql command to update the product in database
    $sqlCommand="UPDATE products SET name='$name', price='$price', description='$description' WHERE pid='$pid'";
    
    //execute the sql command
    $result =mysqli_query($myConnection->myconn, "$sqlCommand");

    // check the result
    if ($result) {
        echo("Success");

    } else {
        // failed to update
        echo("Error");
    }
    //close database connection
    $myConnection->close($myConnection->myconn);
   
} else {
    echo("Error");
}
?>


1.     Run the app now.  The app should be able to update the new project details entered in the EditProductActivity.

 

On Your Own - To Delete the Product from Database

 

Complete the Android app by adding the function of deleting selected product from the database. 

delete_productVolley.php             (Similar to update_productVolley.php except for the SQL statement)



 

 Hint:

 ·        To add in the necessary codes to EditProductActivity.java to send the product id to server via Volley when the Delete button is clicked.

 ·        Create a new PHP file (delete_productVolley.php) to:

o Receive the product id sent via Volley HTTP Post from EditProductActivity.java

o Delete the selected product from database based on the product id

o Return “Success” or “Error” to EditProductActivity.java




Comments

Popular posts from this blog

Simple Login Example (PHP Server + Android Client)

Lab 6: Using split