2014-01-28 4 views
2

Я сделал этот учебник. hereбаза данных обновлений от проблемы Android

У этого есть много проблем, которые окончательно решены. но все же создать новый элемент не будет работать. Я проверил файл .php, передав аргументы в url, и он работает правильно. но из Android App

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

Смежные вопросы