首页 > 解决方案 > I was trying to use room database and mysql database, sending data on room database is working fine while on mysql is not

问题描述

When I try to send debug the app it gives

09-02 14:56:41.137 32737-32737/com.example.motasemx.itsproject D/KANZEN_DEBUG: {"amount":1,"id":0,"link":"https://s6.postimg.cc/y2upelugx/menu1.jpg","name":"California Maki x1","price":99.0} 09-02 14:56:41.140 32737-32737/com.example.motasemx.itsproject D/DEBUG: null

Please tell me what I am doing wrong

Here's my FoodAdapter

package com.example.motasemx.itsproject.Adapter;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.telecom.Call;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.example.motasemx.itsproject.Database.BackgroundTask;
import com.example.motasemx.itsproject.Database.ModelDB.Cart;
import com.example.motasemx.itsproject.HomeActivity;
import com.example.motasemx.itsproject.Interface.ItemClickListener;
import com.example.motasemx.itsproject.MainActivity;
import com.example.motasemx.itsproject.Model.Food;
import com.example.motasemx.itsproject.Model.order;
import com.example.motasemx.itsproject.R;
import com.example.motasemx.itsproject.Retrofit.IKanzenAPI;
import com.example.motasemx.itsproject.Utils.Common;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.w3c.dom.Text;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dmax.dialog.SpotsDialog;
import retrofit2.Callback;
import retrofit2.Response;

public class FoodAdapter extends RecyclerView.Adapter<FoodViewHolder> {

    Context context;
    List<Food> foodList;

    IKanzenAPI mService;

    RequestQueue requestQueue;


    public FoodAdapter(Context context, List<Food> foodList) {
        this.context = context;
        this.foodList = foodList;
    }


    @NonNull
    @Override
    public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.food_item_layout,null);
        return new FoodViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull FoodViewHolder holder, final int position) {

        holder.txt_price.setText(new StringBuilder("₱").append(foodList.get(position).Price).toString());
        holder.txt_food_name.setText(foodList.get(position).Name);

        Picasso.with(context)
                .load(foodList.get(position).Link)
                .into(holder.img_product);

        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onCLick(View v) {
                Toast.makeText(context, "Clicked!", Toast.LENGTH_SHORT).show();
            }
        });

        holder.btn_add_to_cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAddToCartDialog(position);
            }
        });

    }


    private void showAddToCartDialog(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View itemView = LayoutInflater.from(context)
                .inflate(R.layout.add_to_cart_layout,null);

        ImageView img_product_dialog = (ImageView)itemView.findViewById(R.id.img_cart_product);
        final ElegantNumberButton txt_count = (ElegantNumberButton)itemView.findViewById(R.id.txt_count);
        TextView txt_product_name = (TextView)itemView.findViewById(R.id.txt_cart_product_name);

        TextView txt_descript = (TextView)itemView.findViewById(R.id.txt_descript);



        Picasso.with(context)
                .load(foodList.get(position).Link)
                .into(img_product_dialog);
        txt_product_name.setText(foodList.get(position).Name);
        txt_descript.setText(foodList.get(position).Description);

        builder.setView(itemView);
        builder.setNegativeButton("ADD TO CART", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                showConfirmDialog(position,txt_count.getNumber());
                dialogInterface.dismiss();
            }
        });

        builder.show();
    }

    private void showConfirmDialog(final int position, final String number) {
        AlertDialog .Builder builder = new AlertDialog.Builder(context);
        View itemView = LayoutInflater.from(context)
                .inflate(R.layout.confirm_add_to_cart_layout,null);

        final ImageView img_product_dialog = (ImageView)itemView.findViewById(R.id.img_product);
        final TextView txt_product_price = (TextView)itemView.findViewById(R.id.txt_cart_product_price);
        final TextView txt_product_dialog = (TextView)itemView.findViewById(R.id.txt_cart_product_name);
        final ElegantNumberButton enb_amount = (ElegantNumberButton)itemView.findViewById(R.id.txt_amount) ;


        requestQueue = Volley.newRequestQueue(context);

        final String insertURL = "http://192.168.254.121/itsproject/sendorder.php";

        Picasso.with(context).load(foodList.get(position).Link).into(img_product_dialog);
        txt_product_dialog.setText(new StringBuilder(foodList.get(position).Name).append(" x").append(number).toString());

        final double price1 = (Double.parseDouble(foodList.get(position).Price)* Double.parseDouble(number));

        final double finalPrice = price1;

        txt_product_price.setText(new StringBuilder("₱").append(price1));

        builder.setNegativeButton("CONFIRM", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();

                try {

                    mService = Common.getAPI();

                    Cart cartItem = new Cart();
                    cartItem.name = txt_product_dialog.getText().toString();
                    cartItem.amount = Integer.parseInt(number);
                    cartItem.price = finalPrice;
                    cartItem.link = foodList.get(position).Link;

                    StringRequest request = new StringRequest(Request.Method.POST, insertURL, new com.android.volley.Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                        }
                    }, new com.android.volley.Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    }){
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String,String> parameters = new HashMap<String,String>();
                            parameters.put("Name",txt_product_dialog.getText().toString());
                            parameters.put("Link",foodList.get(position).Link);
                            parameters.put("Amount", String.valueOf(Integer.parseInt(number)));
                            parameters.put("Price", String.valueOf(finalPrice));

                            return parameters;
                        }
                    };

                    requestQueue.add(request);

                    Common.cartRepository.insertToCart(cartItem);

                    Log.d("KANZEN_DEBUG", new Gson().toJson(cartItem));
                    Log.d("DEBUG", new Gson().toJson(request));

                    Toast.makeText(context, "Successfully Added To Your Order!", Toast.LENGTH_SHORT).show();
                } catch (Exception ex) {
                    Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.setView(itemView);
        builder.show();
    }

    @Override
    public int getItemCount() {
        return foodList.size();
    }
}

Heres my sendorder.php

<?php
require_once 'db_functions.php';
$db = new DB_Functions();

// json response array
$response = array();
if(isset($_POST['name']) &&
    isset($_POST['link']) &&
    isset($_POST['amount']) &&
    isset($_POST['price']))
{
    $name = $_POST['name'];
    $link = $_POST['link']; 
    $amount = $_POST['amount'];
    $price = $_POST['price'];

    if($db->checkExistUser($name))
    {
        $response["error_msg"] = "user already exist with this phone number ".$name;
        echo json_encode($response);
    }   
    else
    {
        $order_tbl = $db->SendOrder($name, $link, $amount, $price);
        if($order_tbl)  
        {
            $response["name"] = $order_tbl["Name"];
            $response["link"] = $order_tbl["Link"];
            $response["amount"] = $order_tbl["Amount"];
            $response["price"] = $order_tbl["Price"];
            echo json_encode($response);
        }
        else
        {
            $response["error_msg"] = "Unknown error occurred on sending order!";
            echo json_encode($response);
        }
    }
}
else
{
    $response["error_msg"] = "Required parameter (name,link,amount,price) is missing!";
    echo json_encode($response);
}
?>

Heres my db_functions.php

<?php
class DB_Functions {

private $conn;

// constructor
function __construct() {
    require_once 'db_connect.php';
    // connecting to database
    $db = new Db_Connect();
    $this->conn = $db->connect();
}

// destructor
function __destruct() {

}

/**
 * Check user is existed or not
 */
    public function checkExistUser($phone) {
    $stmt = $this->conn->prepare("SELECT * from User WHERE Phone = ?");

    $stmt->bind_param("s", $phone);

    $stmt->execute();

    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        // user existed 
        $stmt->close();
        return true;
    } else {
        // user not existed
        $stmt->close();
        return false;
    }
  }

/**
 * Storing new user
 * returns user details
 */
public function registerNewUser($phone, $name, $birthdate, $address) {

    $stmt = $this->conn->prepare("INSERT INTO User(Phone, Name, Birthdate, Address) VALUES(?, ?, ?, ?)");
    $stmt->bind_param("ssss", $phone, $name, $birthdate, $address);
    $result = $stmt->execute();
    $stmt->close();

    // check for successful store
    if ($result) {
        $stmt = $this->conn->prepare("SELECT * FROM User WHERE Phone = ?");
        $stmt->bind_param("s", $phone);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        return $user;
    } else {
        return false;
    }
   }

public function getUserInformation($phone)
{
    $stmt = $this->conn->prepare("SELECT * FROM User WHERE phone=?");
    $stmt->bind_param("s",$phone);

    if($stmt->execute())
    {
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        return $user;
    }
    else
    {
        return NULL;
    }
}

public function getBanners()
{
    $result = $this->conn->query("SELECT * FROM Banner ORDER BY ID LIMIT 3");

    $banners = array();

    while($item = $result->fetch_assoc())
        $banners[] = $item;
    return $banners;
}

public function getMenu()
{
    $result = $this->conn->query("SELECT * FROM Menu");

    $menu = array();

    while($item = $result->fetch_assoc())
        $menu[] = $item;
    return $menu;
}

public function getFoodByMenuID($menuId)
{
    $query = "SELECT * FROM Food WHERE MenuId ='".$menuId."'";
    $result = $this->conn->query($query);

    $foods = array();

    while($item = $result->fetch_assoc())
        $foods[] = $item;
    return $foods;
}

public function SendOrder($name, $link, $amount, $price) {

    $stmt = $this->conn->prepare("INSERT INTO order_tbl(Name, Link, Amount, Price) VALUES(?, ?, ?, ?)");
    $stmt->bind_param("ssii", $name, $link, $amount, $price);
    $result = $stmt->execute();
    $stmt->close();

    // check for successful store
    if ($result) {
        $stmt = $this->conn->prepare("SELECT * FROM order_tbl WHERE Name = ?");
        $stmt->bind_param("s", $name);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        return $user;
    } else {
        return false;
    }
   }
}
 ?>

标签: androidmysql

解决方案


推荐阅读