Android:无法将数据发送到MYSQL。导致崩溃

时间:2014-11-16 18:13:31

标签: php android mysql

我正在尝试构建一个Android应用程序,它从用户输入填充数据库表,但应用程序不会填充所有列,有些将故意为空。每当我尝试提交它只是崩溃我做错了什么?

我已经尝试逐个删除java类和php中的变量,但没有运气。

班级代码

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText start;
EditText end;
EditText reasonfield;
Spinner spinner;
// url to create new product
private static String url_create_contact = "http://10.0.3.2/sunshie-ems/create_contact.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.leave);

    // Edit Text
    start = (EditText) findViewById(R.id.start);
    end = (EditText) findViewById(R.id.end);
    reasonfield = (EditText) findViewById(R.id.reasonfield);
    Spinner mySpinner=(Spinner) findViewById(R.id.spinner);

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

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

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {
        String name = start.getText().toString();
        String number = end.getText().toString();
        String about = reasonfield.getText().toString();
        String leave = spinner.getSelectedItem().toString();


        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("about", about));
        params.add(new BasicNameValuePair("leave", leave));
        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_contact,
                "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
                Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_LONG).show();
                //Intent i = new Intent(getApplicationContext(), MainActivity.class);
                //startActivity(i);

                // closing this screen
                finish();
            } else {
                Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
                // 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();
    }

}
}

错误报告:

11-16 17:58:16.763: E/AndroidRuntime(1455): FATAL EXCEPTION: AsyncTask #1
11-16 17:58:16.763: E/AndroidRuntime(1455): java.lang.RuntimeException: An error occured while executing doInBackground()
11-16 17:58:16.763: E/AndroidRuntime(1455):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at java.lang.Thread.run(Thread.java:856)
11-16 17:58:16.763: E/AndroidRuntime(1455): Caused by: java.lang.NullPointerException
11-16 17:58:16.763: E/AndroidRuntime(1455):     at com.example.itmaproject.Leave$CreateNewProduct.doInBackground(Leave.java:104)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at com.example.itmaproject.Leave$CreateNewProduct.doInBackground(Leave.java:1)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-16 17:58:16.763: E/AndroidRuntime(1455):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

PHP“create-contact”

$response = array();


if (isset($_POST['leavetype']) && isset($_POST['date']) && isset($_POST['start'])&& isset($_POST['end'])&& isset($_POST['reason'])) {


    $leavetype = $_POST['leavetype'];
$date = $_POST['date'];
$start = $_POST['start'];
$end = $_POST['end'];
$reason = $_POST['reasons'];

    // 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 leavelist(leavetype, date, start, end, reason) VALUES(''$leavetype', '$date', '$start', '$end', '$reason')");

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

1 个答案:

答案 0 :(得分:1)

您将微调器设置为mySpinner并从spinner获取导致NullPointerException的值,因此请更改

  Spinner mySpinner=(Spinner) findViewById(R.id.spinner)

  spinner=(Spinner) findViewById(R.id.spinner)

同时从您的查询中删除额外的引用,即。变化

$result = mysql_query("INSERT INTO leavelist(leavetype, date, start, end, reason) VALUES(''$leavetype', '$date', '$start', '$end', '$reason')");

$result = mysql_query("INSERT INTO leavelist(leavetype, date, start, end, reason) VALUES('$leavetype', '$date', '$start', '$end', '$reason')");