Lab9 Part2 Android Create Product at Mysql DB (Volley)

Lab9 Part2 Android Create Product at Mysql DB



Php Server Side

Create create_productJson.php and save in C:\wamp64\www\products


<?php
 
//php
// Get raw data from request
$json = file_get_contents('php://input');

// Convert json to php object
$json_object = json_decode($json, true);

// Get pid value from json object

$name = $json_object['name']; //htmlspecialchars to be added
$price = $json_object['price']; //htmlspecialchars to be added
$description = $json_object['description']; //htmlspecialchars to be added
 
// array for JSON response
$response = array();
  
 
  // include db connect class
    require_once __DIR__ . '/db_connect.php';
 // connecting to db
    $myConnection= new DB_CONNECT();
    $myConnection->connect();
 
 // mysql inserting a new row
    $sqlCommand="INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')";
    
   // echo $sqlCommand;
    $result =mysqli_query($myConnection->myconn, "$sqlCommand");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
      //  $response["message"] = "Product successfully created.   ".$sqlCommand;
      $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);
    }
 
?>


Android Client Side
Step 1: Create another activity called NewProductActivity

Right clicked on app>new>Activity>Empty Activity. Name it as NewProductActivity.
Copy and paste the codes below for activity_new_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"/>

    <!-- Button Create Product -->
    <Button android:id="@+id/btnCreateProduct"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Create Product"/>

</LinearLayout>



Step 2: Modify NewProductActivity.java.  Copy and paste the codes below:

package networkclient.mdad.sql_databaseexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;


public class NewProductActivity extends AppCompatActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    EditText inputName;
    EditText inputPrice;
    EditText inputDesc;

    String name ,price,description;


    // url to create new product

    private static String url_create_product =MainActivity.ipBaseAddress+"/create_productJson.php";

// JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCT = "product";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_DESCRIPTION = "description";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_product);


        Log.i("Ip address CREATE ", url_create_product);
        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputPrice = (EditText) findViewById(R.id.inputPrice);
        inputDesc = (EditText) findViewById(R.id.inputDesc);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {


                 name = inputName.getText().toString();
                 price = inputPrice.getText().toString();
                 description = inputDesc.getText().toString();


                pDialog = new ProgressDialog(NewProductActivity.this);
                pDialog.setMessage("Adding product ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();


                JSONObject dataJson = new JSONObject();
                try{
                    dataJson.put(TAG_NAME, name);
                    dataJson.put(TAG_PRICE, price);
                    dataJson.put(TAG_DESCRIPTION, description);


                }catch(JSONException e){

                }

                postData(url_create_product,dataJson,1 );


                // creating new product in background thread
               // new CreateNewProduct().execute();
            }
        });
    }


    public void postData(String url, final JSONObject json, final int option){
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest json_obj_req = new JsonObjectRequest(
                Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {


                switch (option){
                    case 1:checkResponseCreate_Product(response); break;

                }

            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
//                String alert_message;
//                alert_message = error.toString();
//                showAlertDialogue("Error", alert_message);
            }

        });
        requestQueue.add(json_obj_req);
    }


    public void checkResponseCreate_Product(JSONObject response)
    {
            Log.i("----Response", response+" ");
        try {
            if(response.getInt(TAG_SUCCESS)==1){

                finish();
                Intent i = new Intent(this, AllProductsActivity.class);
                startActivity(i);

                // dismiss the dialog once product uupdated
                pDialog.dismiss();

            }else{
                // product with pid not found
            }

        } catch (JSONException e) {
            e.printStackTrace();

        }

    }



 }






import java.util.ArrayList;

public class ArrayListExample{



     public static void main(String []args){
         
            ArrayList<String> listName = new ArrayList<>();
    
         listName.add("AA");
         listName.add("BB");
         listName.add("CC");     
         
         
    int i = 0;
    for  (i=0; i<listName.size(); i++)
        System.out.println(listName.get(i));
     }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.