2014-01-28 108 views
2

我做了本教程。 here從android問題更新數據庫

最終解決了很多問題。但仍然創建新的項目將無法正常工作。我通過將參數傳遞給url來檢查.php文件,它的工作正常。但從android應用程序

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

結果不成功,success=0是我的結果。

這是我的活動:

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(); 
     } 

    } 
} 

這是PHP文件:

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

這是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

試試這個,在所有使用$_POST,而不是$_GET發生你的PHP代碼。

既然你已經使用jsonParser.makeHttpRequest(url_create_product, "POST", params);

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

,而不是

if (isset($_GET['name']) && isset($_GET['price']) && isset($_GET['description'])) { 
+0

它的工作原理就知道了。但爲什麼發佈?你能解釋一下get和post的不同用法嗎?謝謝 – Kenji

+0

@Kenji,瞭解更多關於'http:// www.tutorialspoint.com/php/php_get_post.htm' –

+0

好的,謝謝我會檢查。在這個改變後我的應用程序工作,但我不能從URL傳遞參數。是對的嗎? – Kenji