2

I did this tutorial. here

It has many problem that finaly solved. but still create new item won't work. I checked the .php file by passing arguments to url and it's works correctly. but from android app

jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

result is not successful and success=0 is my result.

This is my activity :

import android.app.Activity;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewProductActivity extends Activity{

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputPrice;
    EditText inputDesc;

    // url to create new product
    private static String url_create_product = "http://192.168.19.101:81/android/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);

        //StrictMode.enableDefaults();

        // 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) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }

    /**
     * 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(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String price = inputPrice.getText().toString();
            String description = inputDesc.getText().toString();

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

            // getting JSON Object
            // Note that create product url accepts POST method
            Log.i("WEB", "c1");
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);
            Log.i("WEB", "c2");
            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
                Log.i("WEB", "c success="+success);
                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create 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 done
            pDialog.dismiss();
        }

    }
}

And this is php file:

<?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($_GET['name']) && isset($_GET['price']) && isset($_GET['description'])) {

    $name = $_GET['name'];
    $price = $_GET['price'];
    $description = $_GET['description'];

    // 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) VALUES('$name', '$price', '$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);
}
?>

This is logcat:

01-28 12:41:18.046: D/ProgressBar(28763): setProgress = 0
01-28 12:41:18.046: D/ProgressBar(28763): setProgress = 0, fromUser = false
01-28 12:41:18.046: D/ProgressBar(28763): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
01-28 12:41:18.136: I/WEB(28763): c1
01-28 12:41:18.156: D/ProgressBar(28763): updateDrawableBounds: left = 0
01-28 12:41:18.156: D/ProgressBar(28763): updateDrawableBounds: top = 0
01-28 12:41:18.156: D/ProgressBar(28763): updateDrawableBounds: right = 96
01-28 12:41:18.156: D/ProgressBar(28763): updateDrawableBounds: bottom = 96
01-28 12:41:18.236: D/dalvikvm(28763): GC_FOR_ALLOC freed 367K, 39% free 12037K/19624K, paused 31ms, total 31ms
01-28 12:41:18.266: I/WEB(28763): c2
01-28 12:41:18.266: D/Create Response(28763): {"message":"Required field(s) is missing","success":0}
01-28 12:41:18.266: I/WEB(28763): c success=0
01-28 12:41:18.286: E/ViewRootImpl(28763): sendUserActionEvent() mView == null

1 Answer 1

1

Try this, Use $_POST instead of $_GET in all occurence of your php code.

Since you have used jsonParser.makeHttpRequest(url_create_product, "POST", params);

if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {

instead of

if (isset($_GET['name']) && isset($_GET['price']) && isset($_GET['description'])) {
Sign up to request clarification or add additional context in comments.

3 Comments

it works know. but why post? can you explain me difference usage of get and post? thanks
Ok thanks I'll check. after this change my apps works but i can not pass the parameters from url. is that right?
You can also pass the parameter from url, If you plan to pass parameter in url, then you need to use $_GET method for that parameter, say ex.com?id=1333, $_GET['id']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.