Project Guide from Lab2, Lab6 & Lab7
- Create DB
- DB_Connect.php
- Set Permission
- Set Volley
- get_all_productsVolley.php and ListView
- create_productVolley.php
- get_product_detailsVolley.php
- update_productVolley.php
- delete_productVolley.php
- How to install your mobile app on your phone?
- How to change the icon for your mobile app?
Step 0: Create Database and Tables (See Lab2)
Create mySQL database: EXAMPLE
Get Familiarise with the use of phpMyAdmin
Start XAMPP Control Panel and start the Apache and MySQL module
Then click on the Admin button of MySQL.
Alternatively, you can open a web browser and type localhost/phpmyadmin
Click on the Database tab. Then key in MyDatabase and click Create.
Create Table “products” in MyDatabase
CREATE TABLE IF NOT EXISTS `products` (
`pid` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `price` decimal(10,2) NOT NULL, `description` text,
`qty` int(10),
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`pid`) )
Press Ctrl+Enter to execute
the SQL query to create the table “products”
Insert values to the “products” table
INSERT INTO products ( name, price, description) VALUES ( 'Long-grain rice, not parboiled, WKB', '3.00', '1000g');Insert more values to the products table
INSERT INTO products (name, price, description) VALUES ('Long-grain rice, not parboiled, BL', '4.00', '1000g'), ('Long-grain rice, parboiled, in cooking bags, WKB', '5.00', '1000g');Try other SQL statements likeSELECT * FROM `products` SELECT `name`,`price` from productsSELECT DISTINCT `name` FROM products;SELECT * FROM Products ORDER BY Price desc;SELECT * FROM `products` WHERE pid ='1' SELECT * FROM `products` WHERE name like '%not parboiled%' DELETE FROM `products` WHERE pid ='2' UPDATE `products` SET `price`= '3.80' WHERE `pid` = '3'SELECT AVG(Price) FROM Products;SELECT COUNT(`pid`) FROM products;SELECT * FROM products WHERE MONTH(`created_at`) = 7 AND YEAR(`created_at`) = 2024;
SELECT count(pid) FROM products WHERE YEAR(`created_at`) = 2024;SELECT sum(price) FROM products WHERE name ="apple";SELECT CURRENT_TIMESTAMP;
Reference on SQL Query: https://www.w3schools.com/sql/sql_intro.asp
Let’s get started with creating a db_connect.php and save it in C:\xampp\htdocs\products, using the Visual Studio Code.
Type the following codes into db_connect.php. It defines a class DB_CONNECT
db_connect.php
<?php /** * A class file to connect to database */ class DB_CONNECT { var $myconn; /* Function to connect with the database*/ function connect() { define('DB_USER', "root"); // db user define('DB_PASSWORD', ""); // db password (default is empty) define('DB_DATABASE', "mydatabase"); // database name define('DB_SERVER', "localhost"); // db server // Connecting to mysql database $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysqli_error($con)); $this->myconn = $con; // returning connection cursor return $this->myconn; } /* Function to close db connection */ function close($myconn) { // closing db connection mysqli_close($myconn); } } ?>
Step 1: Open the app's Module build.gradle file. Choose the correct build.gradle file as shown below:
dependencies { implementation 'com.android.volley:volley:1.2.1' ........................... }
Step 2: AndroidManifest.XML
In the AndroidManifest file, set the Internet permission, by adding this line
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <uses-feature android:name="android.hardware.camera" android:required="false" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.CAMERA" /> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.VolleySQLDatabase1" android:usesCleartextTraffic="true" tools:targetApi="31"> <activityandroid:name=".EditProductActivity" android:exported="false" /><activity android:name=".NewProductActivity" android:exported="false" /> <activity android:name=".AllProductsActivity" android:exported="false" /> <activity android:name=".MainActivity" android:exported="false" /> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
1. copy the XML codes below and paste on the activity_main.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>
1.
Modify MainActivity.java - Copy and paste the codes
below. Note that the codes inside the onClick(View view) are commented out.
package mdad.localdata.volleysqldatabase1; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; public class MainActivity extends AppCompatActivity { //public static String ipAddress = "http://192.168.10.114/"; public static String ipAddress = "http://mdad.atspace.cc/"; public static String ipBaseAddress = ipAddress+"products"; Button btnViewProducts; Button btnNewProduct; EditText etIpAddress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Buttons binding XML to Java btnViewProducts = findViewById(R.id.btnViewProducts); btnNewProduct = findViewById(R.id.btnCreateProduct); btnViewProducts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(),ipBaseAddress,Toast.LENGTH_LONG).show(); // 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) { // Create New Product Activity Intent i = new Intent(getApplicationContext(), NewProductActivity.class); startActivity(i); } }); }//onCreate }
http://172.30.103.225/products/get_all_productsVolley.phpget_all_productsVolley.php
<?php /** Following code will retrieve all the products */ // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $db= new DB_CONNECT(); $db->connect(); // get all products from products table $sqlCommand="SELECT * FROM products"; $result =mysqli_query($db->myconn, "$sqlCommand"); $productresult =""; // check for empty result if (mysqli_num_rows($result) > 0) { // looping through all results while ($row = mysqli_fetch_array($result)) { //each row of product is separated by ":" & each product information is separated by ";" $productresult = $productresult.$row["pid"].";" .$row["name"].";".$row["price"].":"; } // return all products with separators to requesting client //Android echo ($productresult); //echo to Android Client }else { // no products found echo("Error"); } ?>
<?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"> <!-- Main ListView Always give id value as list(@android:id/list) --> <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout>
AllProductsActivity.java
package mdad.localdata.volleysqldatabase1; import android.os.Bundle; import android.util.Log; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class AllProductsActivity extends AppCompatActivity { //variable to store ListView ListView lv; //ArrayLisr to store product list from database ArrayList<HashMap<String, String>> productsList; // url to get all products list via the php file get_all_productsJson.php //http://172.30.103.225/products/get_all_productsVolley.php private static String url_all_products = MainActivity.ipBaseAddress+"/get_all_productsVolley.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_all_products); Log.i("URL",url_all_products ); // get resource id of ListView lv = (ListView)findViewById(R.id.list); // ArrayList to store product info in Hashmap for ListView productsList = new ArrayList<HashMap<String, String>>(); // re-usable method to use Volley to retrieve products from database postData(url_all_products, null ); //http://172.30.103.225/products/get_all_productsVolley.php Log.i("URL",url_all_products); } //onCreate public void postData(String url, Map params) { //create a RequestQueue for Volley RequestQueue queue = Volley.newRequestQueue(this); //create a StringRequest for Volley for HTTP Post StringRequest stringRequest = new StringRequest( Request.Method.POST, url, //response from server new Response.Listener<String>() { @Override public void onResponse(String response) { //1;Long-grain rice, not parboiled, WKB;88.00:7;Pineapple King;19.00:11;Oat Bran;1.00:12;Apple;20.00:14;Soya Bean;2.00: //check if error code received from server. if (response.equals("Error")) { Toast.makeText(getApplicationContext(),"Error in retrieving database",Toast.LENGTH_LONG).show(); return; } //handle the response data received from server //store each product from database records in String array String[] products = response.split(":"); // for each product, retrieve the product details for (int i = 0; i < products.length; i++) { // Storing each product info in variable String[] details = products[i].split(";"); String id = details[0]; String name = details[1]; String price = details[2]; // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each product info to HashMap key-value pair map.put("product_id", id); map.put("product_name", name); map.put("product_price", price); // adding map HashList to ArrayList productsList.add(map); } //populate the listview with product information from Hashmap ListAdapter adapter = new SimpleAdapter( AllProductsActivity.this, productsList, R.layout.list_item, new String[]{"product_id", "product_name","product_price"}, new int[]{R.id.pid, R.id.name,R.id.price}); // updating listview lv.setAdapter(adapter); } }, //error in Volley new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handle error Toast.makeText(getApplicationContext(),"Error in retrieving database",Toast.LENGTH_LONG).show(); } } ); //add StringRequest to RequestQueue in Volley queue.add(stringRequest); } }//end class
To Add New Product to Database
PHP SERVER side
url_create_product = "http://172.30.103.225/products/create_productVolley.php";
create_productVolley.php
<?php if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description']) ) { //retrieve the values from html form $name = $_POST['name']; $price = $_POST['price']; $descp = $_POST['description']; // include db connect class require_once __DIR__ . '/db_connect.php'; // include db connect class // connecting to db $db= new DB_CONNECT(); $db->connect(); // get the search product from products table //if update button is clicked in form submission //$sqlCommand="INSERT INTO products (name,price,description) VALUES ('$name','$price','$description')"; $sqlCommand = "INSERT INTO products (name, price, description) VALUES ('$name', '$price', '$descp')"; //execute the sql command $result = mysqli_query($db->myconn, "$sqlCommand"); if ($result) { //if result is successful echo ("Success"); } else echo ("Error"); $db->close($db->myconn); } else { echo ("Error"); } ?>
<?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"/> <!-- Button Create Product --> <Button android:id="@+id/btnCreateProduct" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Create Product"/> </LinearLayout>
NewProductActivity.java
<?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" package mdad.localdata.volleysqldatabase1; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class NewProductActivity extends AppCompatActivity { EditText inputName; EditText inputPrice; EditText inputDesc; Button btnCreateProduct; String name ,price,description; // url_create_product = "http://172.30.103.225/products/create_productVolley.php"; private static String url_create_product =MainActivity.ipBaseAddress+"/create_productVolley.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_new_product); // retrieve the resource id for EditText inputName = (EditText) findViewById(R.id.inputName); inputPrice = (EditText) findViewById(R.id.inputPrice); inputDesc = (EditText) findViewById(R.id.inputDesc); // retrieve the resource id for button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct); // button click event btnCreateProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //retrieve the values in EditText entered by user name = inputName.getText().toString(); price = inputPrice.getText().toString(); description = inputDesc.getText().toString(); //check for no empty values in EditText if (name.isEmpty() || price.isEmpty() || description.isEmpty()) { Toast.makeText(getApplicationContext(), "All fields must be filled", Toast.LENGTH_LONG).show(); return; } //put the product info as key-values pair in HashMap Map<String,String> params_create = new HashMap<String,String>(); params_create.put("name",name); params_create.put("price",price); params_create.put("description",description); //postData method to use Volley to update new product details in database postData(url_create_product,params_create); } }); }//end of onCreate() public void postData(String url, Map params){ //create a RequestQueue for Volley RequestQueue requestQueue = Volley.newRequestQueue(this); //create StringRequest for http post web request to send new product info to database StringRequest stringRequest = new StringRequest(Request.Method.POST, url, //response from server new Response.Listener<String>() { @Override public void onResponse(String response) { 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); } } }, //error in Volley new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handle error Toast.makeText(getApplicationContext(),"Error in accessing database",Toast.LENGTH_LONG).show(); } } ) { @Nullable @Override // to send product info stored in HashMap params_create to server via HTTP Post protected Map<String, String> getParams() { return params; } }; //add StringRequest to Volley Queue requestQueue.add(stringRequest); } }// end of class>
Lab 7
Part 1: Get Selected Product Details
PHP SERVER side
private static final String url_product_details =
MainActivity.ipBaseAddress+"/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"); ?>
<?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"); } ?>
<?php /* * Following code will update the selected product information * All product details are read from HTTP Post Request from Volley */ // check for required fields //we only need the pid info so as to delete from the SQL table products if ( isset($_POST['pid']) ) { //retrieve the values for new product information $pid = $_POST['pid']; // 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="delete from products 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"); }?>
<?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>
EditProductActivity.javapackage mdad.localdata.volleysqldatabase; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class EditProductActivity extends AppCompatActivity { // 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; // 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" ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_edit_product); //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); //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); } }); //Save button click event btnDelete.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); //postData method to use Volley to update new product details in database postData(url_delete_product,params_update,update_delete_product); } }); } 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); } //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); } } } }, //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); } }
Comments
Post a Comment