dsvq5069 2014-10-17 14:56
浏览 101
已采纳

mysql数据未使用JSON更新

I've been stucked with my problem for almost 3 days. Been searching through internet for the solution.

I'm developing an android program that use JSON and php mysql for data management. My main revision is from here http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/.

Here is my JSON Parser code:`

/*
 * a JSON Parser class to get JSON from URL. This class supports two http request   methods GET and POST to get json from url.
 * 
 */
 public class JSONParser {


    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }
 // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {
            // check for request method

            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                Log.i("postData", httpResponse.getStatusLine().toString());
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                Log.i("value is for POST", is.toString());

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                Log.i("value is for GET", is.toString());
            }     
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "
");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
     // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

`

Here is my EditProduct code:

public class EditProduct extends FragmentActivity{

//  EditText inputName;
//    EditText inputPrice;
//    EditText inputDesc;
//    EditText inputQty;
ImageView preview;
ImageButton camera;
public static Bitmap bm;
Button btnSave;
Button btnDelete;
String pid;


EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
EditText txtQty;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// single product url
private static final String url_product_detials = "http://myweb.com/myproject/get_product_details.php";

// url to update product
private static final String url_update_product = "http://myweb.com/myproject/update_product.php";

// url to delete product
private static final String url_delete_product = "http://myweb.com/myproject/delete_product.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";
private static final String TAG_IMAGE="image";
public static final String TAG_QTY = "qty";

private Uri fileUri;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
private static final int CHOOSE_IMAGE_FROM_GALLERY=2;
public static final int MEDIA_TYPE_IMAGE = 1;

static File mediaFile;
static String mCurrentPhotoPath;

static JSONObject product;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_products);
 // save button
    btnSave = (Button) findViewById(R.id.btnSave);
    btnDelete = (Button) findViewById(R.id.btnDelete);

//camera button
    camera=(ImageButton)findViewById(R.id.imageButton1);

    // getting product details from intent
    Intent i = getIntent();

    // getting product id (pid) from intent
    pid = i.getStringExtra(TAG_PID);

    // Getting complete product details in background thread
    new GetProductDetails().execute();

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

        @Override
        public void onClick(View v) {
            // starting background task to update product
            new SaveProductDetails().execute();
        }
    });

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

        @Override
        public void onClick(View arg0) {
            // deleting product in background thread
            new DeleteProduct().execute();
        }
    });

    //Camera button event
    camera.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


            selectImage();
            //galleryAddPic();

        }
    });

}









/**
 * Background Async Task to Get complete product details
 * */
class GetProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProduct.this);
        pDialog.setMessage("Loading product details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {

        // updating UI from Background Thread

                // Check for success tag
                int success;
                // Building Parameters
                    List<NameValuePair> paramse = new ArrayList<NameValuePair>();
                    paramse.add(new BasicNameValuePair("pid", pid));

                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_product_detials, "GET", paramse);

                    // check your log for json response
                    Log.d("Single Product Details", json.toString());
                    try {
                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received product details
                        JSONArray productObj = json
                                .getJSONArray(TAG_PRODUCT); // JSON Array

                        // get first product object from JSON Array
                         product = productObj.getJSONObject(0);



                    }else{
                        // product with pid not found
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }




        return null;
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
        // product with this pid found
        // Edit Text
       txtName = (EditText) findViewById(R.id.editText1);
       txtPrice =(EditText)findViewById(R.id.editText3);
       txtDesc = (EditText) findViewById(R.id.editText2);
       txtQty=(EditText) findViewById(R.id.editText4);
       preview=(ImageView)findViewById(R.id.imagePreview);

    // display product data in EditText
       try {
        txtName.setText(product.getString(TAG_NAME));
        txtPrice.setText(product.getString(TAG_PRICE));
       txtDesc.setText(product.getString(TAG_DESCRIPTION));
       txtQty.setText(product.getString(TAG_QTY));
       preview.setImageBitmap(viewImage(product.getString(TAG_IMAGE)));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}

}

/**
 * Background Async Task to  Save product Details
 * */
class SaveProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProduct.this);
        pDialog.setMessage("Saving product ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Saving product
     * */
    protected String doInBackground(String... args) {

        // getting updated data from EditTexts
        String name = txtName.getText().toString();
        String price = txtPrice.getText().toString();
        String description = txtDesc.getText().toString();
        String img=preview.toString();
        String qty=txtQty.getText().toString();

        //Check Log untuk setiap nilai di atas yaww..
        Log.d("Nilai String name lepas Saving",name);
        Log.d("Nilai String price lepas Saving",price);
        Log.d("Nilai String desc lepas Saving",description);
        Log.d("Nilai String img lepas Saving",img);
        Log.d("Nilai String qty lepas Saving",qty);
        Log.d("Nilai String pid lepas Saving",pid);

        try {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_PID, pid));
        params.add(new BasicNameValuePair(TAG_NAME, name));
        params.add(new BasicNameValuePair(TAG_PRICE, price));
        params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
        params.add(new BasicNameValuePair(TAG_IMAGE,img));
        params.add(new BasicNameValuePair(TAG_QTY,qty));

        //Nak cek value params ade ke x
        System.out.println(params);


        // sending modified data through http request
        // Notice that update product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                "POST", params);


        Log.d("Saving Response", json.toString());
        // check json success tag

            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully updated
                Intent i = getIntent();
                // send result code 100 to notify about product update
                setResult(100, i);
                finish();
            } else {

                System.out.println("Fuck not updated shit!");
                // failed to update product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product uupdated
        pDialog.dismiss();
    }

}

/*****************************************************************
 * Background Async Task to Delete Product
 * */
class DeleteProduct extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProduct.this);
        pDialog.setMessage("Deleting Product...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Deleting product
     * */
    protected String doInBackground(String... args) {

        // Check for success tag
        int success;
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("pid", pid));

            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                    url_delete_product, "POST", params);

            // check your log for json response
            Log.d("Delete Product", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // product successfully deleted
                // notify previous activity by sending code 100
                Intent i = getIntent();

                // send result code 100 to notify about product deletion
                setResult(100, i);
                finish();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

    }

}

Here is my AddNewProduct code

public class AddProducts extends Fragment{

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
EditText inputQty;
String image_str;
ImageView preview;
//    Fragment fragment=this;
Bitmap bm;
String media_photo_file;
String photo_file;

// url to create new product
private static String url_create_product ="http://myweb.com/myproject   /create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private Uri fileUri;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
private static final int CHOOSE_IMAGE_FROM_GALLERY=2;
public static final int MEDIA_TYPE_IMAGE = 1;
static File mediaFile;
static String mCurrentPhotoPath;




@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //setContentView(R.layout.add_products);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View aV = inflater.inflate(R.layout.add_products,container,false);
//      TextView tV1=(TextView)aV.findViewById(R.id.textView1);
     inputName=(EditText)aV.findViewById(R.id.editText1);
//      TextView tV2=(TextView)aV.findViewById(R.id.textView2);
    inputDesc=(EditText)aV.findViewById(R.id.editText2);
//      TextView tV3=(TextView)aV.findViewById(R.id.textView3);
     inputPrice=(EditText)aV.findViewById(R.id.editText3);
    ImageButton camera=(ImageButton)aV.findViewById(R.id.imageButton1);
//      ImageButton gallery=(ImageButton)aV.findViewById(R.id.imageButton2);
    preview=(ImageView)aV.findViewById(R.id.imagePreview);
//      TextView tV4=(TextView)aV.findViewById(R.id.textView4);
    inputQty=(EditText)aV.findViewById(R.id.editText4);
    final ImageButton addItem=(ImageButton)aV.findViewById(R.id.imageButton3);



    camera.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


            selectImage();
            //galleryAddPic();

        }
    });
    // addItem button click event
    addItem.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // creating new product in background thread
            if (bm==null){ /
                Toast.makeText(getActivity(), "Sila Isi Semua Tempat Kosong Syaithonn..", Toast.LENGTH_LONG).show();

            }
            else{

            new CreateNewProduct().execute();
            //addItem.setEnabled(true)  ;
            }
        }
    });




    return aV;



}

/**
 * Button AddItem
 * Background Async Task to Create new product
 * */
class CreateNewProduct extends AsyncTask<String, String, String> {

     /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Creating product
     * */
    @Override
    protected String doInBackground(String... args) {
        String name = inputName.getText().toString();
        String price = inputPrice.getText().toString();
        String description = inputDesc.getText().toString();
        String qty=inputQty.getText().toString();
        String image_str = getImageString( bm);

        //Check Log for image_str value;
        Log.d("Value for String image_str", image_str);

        // 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("qty", qty));
        params.add(new BasicNameValuePair("img", image_str));

        System.out.println(params);
     // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());
     // check for success tag
       try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
                Intent i = new Intent(getActivity().getApplicationContext(), HomeActivity.class);
                startActivity(i);

                // closing this screen
                getActivity().finish();
            } else {
                // failed to create product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
}

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

    }

}

}

Here is my PHP script for addnewproduct (create):

  <?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

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

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

$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
$qty = $_POST['qty'];
$image=$_POST['img'];



// 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, description,qty,image )  VALUES('$name', '$price', '$description', '$qty','$image' )");

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

Here is my deleteproduct php script

                            <?php

/*
 * Following code will delete a product from table
 * A product is identified by product id (pid)
 */

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

// check for required fields
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];

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

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

// mysql update row with matched pid
$result = mysql_query("DELETE FROM products WHERE pid = $pid");

// check if row deleted or not
if (mysql_affected_rows() > 0) {
    // successfully updated
    $response["success"] = 1;
    $response["message"] = "Product successfully deleted";

    // echoing JSON response
    echo json_encode($response);
} else {
    // no product found
    $response["success"] = 0;
    $response["message"] = "No product found";

    // echo no users JSON
    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);
}
?>                                

My big problem is, whenever I run and wanted to update my product details, the data inside the MySQL is not updated at all. My update product code starts here :

/**
 * Background Async Task to  Save product Details
 * */
class SaveProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProduct.this);
        pDialog.setMessage("Saving product ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Saving product
     * */

which is part of my EditProductCode.

I've also checked if the data is null but everything seems find. Here is myLogcat when I run the SaveProductDetails class above

10-17 09:46:59.760: D/Nilai String name lepas Saving(7728): shiyh update
10-17 09:46:59.760: D/Nilai String price lepas Saving(7728): 3.00
10-17 09:46:59.760: D/Nilai String desc lepas Saving(7728): afagfeag
10-17 09:46:59.760: D/Nilai String img lepas Saving(7728):    android.widget.ImageView{137dff73 V.ED.... ......I. 10,60-170,180 #7f08005a app:id/imagePreview}
10-17 09:46:59.760: D/Nilai String qty lepas Saving(7728): 3.00
10-17 09:46:59.760: D/Nilai String pid lepas Saving(7728): 11
10-17 09:46:59.760: I/System.out(7728): [pid=11, name=shiyh update, price=3.00,   description=afagfeag, image=android.widget.ImageView{137dff73 V.ED.... ......I.      10,60-170,180 #7f08005a app:id/imagePreview}, qty=3.00]
10-17 09:46:59.863: I/Choreographer(7728): Skipped 61 frames!  The application may be   doing too much work on its main thread.
10-17 09:46:59.969: I/art(7728): Background sticky concurrent mark sweep GC freed  2613(116KB) AllocSpace objects, 0(0B) LOS objects, 689% free, 3MB/6MB, paused 3.561ms total 119.584ms
10-17 09:46:59.991: I/postData(7728): HTTP/1.1 200 OK
10-17 09:46:59.991: I/value is for POST(7728):   org.apache.http.conn.EofSensorInputStream@1527e9eb
10-17 09:46:59.993: D/Saving Response(7728): {"success":0,"message":"Required field(s) is missing"}
10-17 09:46:59.994: I/System.out(7728): Fuck not updated shit!

Here is my PHP script for updating the data supposed POST by the SaveProductDetails class

<?php 
/*
 * Following code will update a product information
 * A product is identified by product id (pid)
 */

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

// check for required fields
if (isset($_POST['pid']) && isset($_POST['name']) && isset($_POST['price'])  &&   isset($_POST['description'] )&& isset($_POST['img'] )&& isset($_POST['qty'] ) ) {

  $pid = $_POST['pid'];
  $name = $_POST['name'];
  $price = $_POST['price'];
  $description = $_POST['description'];
  $base=$_POST['img'];
 $qty = $_POST['qty'];
// include db connect class
//require_once __DIR__ . '/db_connect.php';

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

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

// mysql update row with matched pid
$result = mysql_query("UPDATE products SET name = '$name', price = '$price',  description = '$description', image='$base', qty='$qty' WHERE pid = $pid" );

// check if row inserted or not
if ($result) {
    // successfully updated
    $response["success"] = 1;
    $response["message"] = "Product successfully updated.";

    // echoing JSON response
    echo json_encode($response);
} else {

}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

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

?>                               

I have no problem when i want to delete the product or create new product. The only problem I had is when i'm using UPDATE in the Php script for updating the data. Could anyone please guide me why I am not able to update my data from android JSON to my MYSql database using the UPDATE method? Thanks in advance..

  • 写回答

1条回答 默认 最新

  • duanmei1930 2014-10-17 17:33
    关注

    Attention !! EditProduct code.

    private static final String TAG_IMAGE="image";
    ...
    params.add(new BasicNameValuePair(TAG_IMAGE,img));
    //TAG_IMAGE="image";
    

    PHP script.

    if (isset($_POST['pid']) && isset($_POST['name']) && isset($_POST['price'])  && isset($_POST['description'] )&& isset($_POST['img'] )&& isset($_POST['qty'] ) ) {
    
    //but $_POST['img'] is not existing
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突