0

我是 android 编码的新手。我无法在我的数据库中插入值,尽管 logcat 显示我已插入其中,但数据库无法显示我已插入的值。附上所有代码:

AlertDialogManager.java

public class AlertDialogManager extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputQty;
EditText inputPrice;


// url to create new product
private static String url_create_product = "http://10.0.2.2/Schemes_NAV/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.alert_dialog_text_date_entry);

    // Edit Text
    inputPrice = (EditText) findViewById(R.id.et_price);
    inputQty = (EditText) findViewById(R.id.et_qty);

    // Create button
    Button btnCreateProduct = (Button) findViewById(R.id.OkButton);

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

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {
        String Qty = inputQty.getText().toString();
        String price = inputPrice.getText().toString();


        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("Qty", Qty));
        params.add(new BasicNameValuePair("price", price));


        // 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(getApplicationContext(), Nav.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();
    }

}

}

接下来是它的布局,即 alert_dialog_text_date_entry.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
   android:gravity="center"
    >

    <TextView
        android:layout_width="248dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20.0dip"
        android:layout_marginRight="20.0dip"
        android:gravity="left"
        android:text="Qty"
        android:textAppearance="?android:textAppearanceMedium" />

    <EditText
        android:id="@+id/et_qty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20.0dip"
        android:layout_marginRight="20.0dip"
        android:autoText="false"
        android:capitalize="none"
        android:digits="0123456789"
        android:gravity="fill_horizontal"
        android:imeActionLabel="Done"
        android:imeOptions="actionDone"
        android:inputType="phone"
        android:numeric="decimal"
        android:scrollHorizontally="true"
        android:textAppearance="?android:textAppearanceMedium" />

    <TextView
        android:layout_width="248dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20.0dip"
        android:layout_marginRight="20.0dip"
        android:gravity="left"
        android:text="Price"
        android:textAppearance="?android:textAppearanceMedium" />

    <EditText
        android:id="@+id/et_price"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20.0dip"
        android:layout_marginRight="20.0dip"
        android:autoText="false"
        android:capitalize="none"
        android:gravity="fill_horizontal"
        android:imeActionLabel="Done"
        android:imeOptions="actionDone"
        android:numeric="decimal"
        android:scrollHorizontally="true"
        android:textAppearance="?android:textAppearanceMedium" 

    <TextView
        android:layout_width="252dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20.0dip"
        android:layout_marginRight="20.0dip"
        android:gravity="left"
        android:text="Buy Date"
        android:textAppearance="?android:textAppearanceMedium" />

    <DatePicker
        android:id="@+id/et_datePicker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
       android:id="@+id/linearLayout1"
       android:layout_width="302dp"
       android:layout_height="wrap_content" >

  <Button
    android:id="@+id/OkButton"
    android:layout_width="130dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_marginLeft="20.0dip"
    android:text="OK" />

  <Button
    android:id="@+id/cancelButton"
    android:layout_width="130dp"
    android:layout_height="wrap_content"
    android:layout_marginRight="20.0dip"
    android:text="Cancel" />

  </LinearLayout>

  </LinearLayout>

接下来,php文件create_product.php

<?php

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

 // check for required fields
 if (isset($_POST['Qty']) && isset($_POST['price'])) {

$Qty = $_POST['Qty'];
$price = $_POST['price'];


// 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 schemes(Qty, price) VALUES('$Qty', '$price')");


// 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 确实表明它创造了新产品。

 D/dalvikvm(686): GC_FOR_MALLOC freed 6754 objects / 755288 bytes in 236ms
 03-29 15:40:09.499: D/Create Response(686): {"message":"Product successfully created.","success":1}

请帮忙。谢谢你。

4

1 回答 1

0

您需要将以下两个语句从 doInBackground 移动到 onPreExecute 方法。

String Qty = inputQty.getText().toString();
String price = inputPrice.getText().toString();

doInBackground 在不同的线程上运行,因此无法访问您的活动视图,而 onPreExecute 和 onPostExecute 方法在您的 UI/主线程上运行并且可以访问活动视图。

您的服务器端代码不会验证它收到的任何输入。在您的代码中,doInBackground 为 Quantity 和 Price 发送空白值,如果这些字段上没有数据库约束,则使用这些选项将插入一个带有空白值的行。

于 2013-03-29T10:53:57.987 回答