插入MySQL时会丢失一些数据

时间:2014-05-30 00:47:30

标签: android mysql

像许多人一样,我是Android和Java编程的新手。我正在为我的雇主制作一个项目来扫描标签并比较序列号以进行匹配,然后上传到数据库。我在家里设置了一个MySQL数据库,它按预期插入数据,但表中缺少一些'contLabel'扫描,即使它们显然在EditText框中。请原谅我的鹅卵石代码,我还在学习相当多的东西,我正在做这个测试。有人可以解释为什么有些数据会丢失,即使有必要字段中的数据吗?提前谢谢大家。

这是我的JSONParser:

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params, 
"utf-8"));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

这是我的异步活动:

 // Called when Compare button is clicked   
public void compareAndInsert(View view) {
    HashMap<String, String> queryValues = new HashMap<String, String>();
    queryValues.put("pickTicket", getPickTicket.getText().toString());
    queryValues.put("userId", getUserId.getText().toString());
    queryValues.put("contLabel", getContLabel.getText().toString());
    queryValues.put("qrLabel", getQrLabel.getText().toString());
    String cL = getContLabel.getText().toString();
    String qL = getQrLabel.getText().toString();
    String subClabel = cL.substring(3);
    String subQlabel = qL.substring(3);

        if (subClabel.equals(subQlabel) && trigger == true) {
            Toast toast = new Toast(this);
            ImageView view1 = new ImageView(this);
            view1.setImageResource(R.drawable.pass);
            toast.setView(view1);
            toast.show();
            //controller.insertUser(queryValues);
            new InsertToDb().execute();
            ((EditText) findViewById(R.id.etContLabel)).setText("");
            ((EditText) findViewById(R.id.etQrLabel)).setText("");
            getContLabel.requestFocus();
        } else {
            Toast toast = new Toast(this);
            ImageView view1 = new ImageView(this);
            view1.setImageResource(R.drawable.fail1);
            toast.setView(view1);
            toast.show();
        }       
}       
public void clickToChange(View view) {
    trigger = false;
    this.callHomeActivity(view);
}
public void callHomeActivity(View view) {
    Intent objIntent = new Intent(getApplicationContext(),
            MainActivity.class);
    startActivity(objIntent);
}

class InsertToDb extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ScanTruck.this);
        pDialog.setMessage("Updating Database...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... args) {
        String pickTicket = getPickTicket.getText().toString();
        String userId = getUserId.getText().toString();
        String contLabel = getContLabel.getText().toString();
        String qrLabel = getQrLabel.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("pickTicket", pickTicket));
        params.add(new BasicNameValuePair("userId", userId));
        params.add(new BasicNameValuePair("contLabel", contLabel));
        params.add(new BasicNameValuePair("qrLabel", qrLabel));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,

        // check log cat for 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(),"DbUpdated!", 
Toast.LENGTH_SHORT).show();

                // closing this screen
                finish();
            } else {
                // failed to create product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }catch (NullPointerException ex){
            ex.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 verify row
 * All fields are read from HTTP Post Request
 */
// array for JSON response
$response = array();
print_r($_POST);
// check for required fields
if (isset($_POST["pickTicket"]) && isset($_POST["userId"])&&isset
($_POST["contLabel"])&& isset ($_POST["qrLabel"])) {

$pickTicket = $_POST['pickTicket'];
$userId = $_POST['userId'];
$contLabel = $_POST['contLabel'];
$qrLabel = $_POST['qrLabel'];

// 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 verifyqr(pickTicket,userId, contLabel, qrLabel)  
VALUES('$pickTicket', '$userId', '$contLabel', '$qrLabel')");

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

我没有足够的代表来发布图像但是contLabel字段缺少一些数据,即使数据显然位于EditText框中。任何帮助将不胜感激。而且我已经广泛地搜索过这个问题,但没有像我的那样。谢谢!

无政府

1 个答案:

答案 0 :(得分:0)

在您的活动中,您有:

new InsertToDb().execute();
((EditText) findViewById(R.id.etContLabel)).setText("");
((EditText) findViewById(R.id.etQrLabel)).setText("");

因此,这将调用AsyncTask,然后将EditTexts设置为空字符串 由于AsyncTasks在另一个线程中运行,因此您的UI线程在重置内容之前不会等待任务完成,我猜想在AsyncTask访问您想要的信息之前,EditTexts会被清除。

你应该:

  • 如果您不介意任务工作量导致的任何延迟,请将清算移至AsyncTask中的onPostExecute()
  • 或者将通过构造函数读取的值传递给AsyncTask,而不是直接从AsyncTask读取它们,因为值可能已经更改。

如果您需要澄清任何问题,我可以提供示例代码。

另外,您应该将要访问的EditTexts和其他视图作为类级变量。在你的onCreate中分配它们,然后只需通过变量名称引用它们,而不是从你的布局中拉出它们,并在每次需要使用它们时再重新铸造它们。