Android AsyncTask无法将值传递给数据库

时间:2016-11-12 22:54:17

标签: java php android multithreading

这是一个包含RecyclerView的类。我想要的是,当我对列表的任何对象执行leftSwipe时,它应该对本地主机PHP页面进行POST调用,该页面将滑动对象的值作为条目添加到MYSQL数据库中的表。但是,我的ServiceHandler类无法将变量传递给PHP页面来添加条目。

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder>  {

private ArrayList<ProductInfo> inf;
ProductAdapter selfRef=this;
String url_add_product = "http://10.0.2.2/FinalProject/add_basket_product.php";
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
public String nm,pr,dis,st;

//helper method to get ProductInfo object
private ProductInfo getInfo(String name){
    ProductInfo pinfo=null;
    for(ProductInfo x:inf){
        if(x.getName().equalsIgnoreCase(name))
            pinfo=x;
    }
    return pinfo;
}


public class ViewHolder extends RecyclerView.ViewHolder {
    TextView pName;
    TextView pPrice;
    TextView aDistance;
    TextView aStore;
    private Context ctx=null;
    OnSwipeTouchListener onSwipeTouchListener;
    ProductInfo p;

    public ViewHolder(final View view){
        super(view);
        ctx=view.getContext();
        pName = (TextView) view.findViewById(R.id.selected_prod_name);
        pPrice = (TextView) view.findViewById(R.id.selected_prod_price);
        aDistance = (TextView) view.findViewById(R.id.product_distance);
        aStore = (TextView) view.findViewById(R.id.product_store);

       onSwipeTouchListener=(new OnSwipeTouchListener(ctx) {
            public void onSwipeTop() {
                Toast.makeText(ctx, "top", Toast.LENGTH_SHORT).show();
            }

            public void onSwipeRight() {
                Toast.makeText(ctx, "right", Toast.LENGTH_SHORT).show();
            }

            public void onSwipeLeft() {

                Toast.makeText(ctx, "Added to cart", Toast.LENGTH_SHORT).show();
              //  p.setName(pName.getText().toString());
                nm=(pName.getText().toString());
               // p.setPrice(Double.parseDouble(pPrice.getText().toString()));
                pr=(pPrice.getText().toString());
               // p.setDistance(Double.parseDouble(aDistance.getText().toString()));
                dis=aDistance.getText().toString();
               // p.setStore(aStore.getText().toString());
                st=aStore.getText().toString();

              //  add product to Basket activity
              //  String jsonStr="";
              //  ServiceHandler sh = new ServiceHandler();
              /*  List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("name", pinfo.getName()));
                params.add(new BasicNameValuePair("price", Double.toString(pinfo.getPrice())));
                params.add(new BasicNameValuePair("description", pinfo.getName()));
                params.add(new BasicNameValuePair("location", pinfo.getStore()));
                params.add(new BasicNameValuePair("distance", Double.toString(pinfo.getDistance())));
                jsonStr=sh.makeServiceCall(url_add_product,ServiceHandler.POST,params); */
                new CreateNewProduct().execute();


            }
            public void onSwipeBottom() {
                Toast.makeText(ctx, "bottom", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onClick() {
                super.onClick();
                Intent i;
                ProductInfo pinfo= getInfo(pName.getText().toString());
                Toast.makeText(view.getContext(),pName.getText().toString(),Toast.LENGTH_LONG).show();
                String name=pinfo.getName();
                String price=Double.toString(pinfo.getPrice());
                String store=pinfo.getStore();
                String dist=Double.toString(pinfo.getDistance());
                i=new Intent(ctx,ProductLocation.class);
                Bundle b=new Bundle();
                b.putString("PROD_NAME",name);
                b.putString("PROD_PRICE",price);
                b.putString("PROD_STORE",store);
                b.putString("PROD_DIST",dist);

                i.putExtras(b);
                view.getContext().startActivity(i);

            }
        });

        //To set onClick Listener for each item which is held by ViewHolder
    view.setOnTouchListener(onSwipeTouchListener);
}
    class CreateNewProduct extends AsyncTask<String, String, String> {

        String name;
        String price;
        String location;
        String distance;
        String description;
        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ctx);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            name =nm;// p.getName();
            price =pr;// Double.toString(p.getPrice());
            location=st ;// p.getStore();
            distance=dis;//Double.toString(p.getDistance());
            description = "yellow";// p.getName();
        }

        /**
         * Creating product
         */

        protected String doInBackground(String... args) {
            String jsonStr="";
            try {
                ServiceHandler sh = new ServiceHandler();
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("name", name));
                params.add(new BasicNameValuePair("price", price));
                params.add(new BasicNameValuePair("description", description));
                params.add(new BasicNameValuePair("location", location));
                params.add(new BasicNameValuePair("distance", distance));

                Log.d("Create Response", name);
                jsonStr = sh.makeServiceCall(url_add_product, ServiceHandler.POST, params);
                // check log cat fro response
                Log.d("Create Response", jsonStr.toString());
            }catch(Exception e){

            }
            // check for success tag
            return "success";

        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute(Void result) {
            // dismiss the dialog once done

            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
        }
    }

}

public ProductAdapter(ArrayList<ProductInfo> prinfo){
    this.inf = prinfo;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_card,parent,false);
    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position){
    ProductInfo product = inf.get(position);
    holder.pName.setText(product.getName());
    double n = product.getPrice();
    String s = String.valueOf(n) + " HKD";
    holder.pPrice.setText(s);
    double m = product.getDistance();
    String q = String.valueOf(m) + " KM";
    holder.aDistance.setText(q);
    holder.aStore.setText(product.getStore());
}

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

}

我的ServiceHandler类如下:

package com.example.dayle_fernandes.final_project;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;


public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
                              List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);
            return "success";

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}
}

我的PHP文件add_basket_product.php是

<?php



// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description']) && isset($_POST['location']) && isset($_POST['distance'])) {

$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
$location = $_POST['location'];
$distance = $_POST['distance'];
$created_at = $_POST['created_at'];
$updated_at = $_POST['updated_at'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, location, distance, description) VALUES('$name', '$price', '$location', '$distance', '$description')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $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);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

我不知道为什么不通过。在doInBackground()中的Log活动 - Log.d(“Create Response”,name); ,我可以看到我可以访问名称,但无法将其传递给php文件

0 个答案:

没有答案