Lab6 Codes Part1 (List All Products)

 

get_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"); }    
        
        ?>


MainActivity.java

package mdad.localdata.volleysqldatabase1;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
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 ipBaseAddress = "http://172.30.103.225/products";
    Button btnViewProducts;
    Button btnNewProduct;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // Buttons  binding XML to Java
       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 v) {

                // 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);
            }
        });










    }
}


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);


        // 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




Comments

Popular posts from this blog

Simple Login Example (PHP Server + Android Client)

Lab 6: Using split