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

以下の 2 つのステートメントを 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 に答える