php – 在循环中执行网络呼叫后,相同的项目被删除两次

前端之家收集整理的这篇文章主要介绍了php – 在循环中执行网络呼叫后,相同的项目被删除两次前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我面临着一个奇怪的问题.我试图从 mysql数据库删除所选项目.虽然查询的一切都是正确的,我测试了查询,它的工作,但它不会从数据库删除项目.

代码

private class DeleteData extends AsyncTask<String,Void,List<CartList>> {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = new ProgressDialog(CartActivity.this);
    progressDialog.setMessage(getString(R.string.get_stocks));
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);
    progressDialog.show();
}

@Override
protected List<CartList> doInBackground(String... params) {
    nameValuePairs = new ArrayList<>();
    cartItems = new ArrayList<>();
    try {
        url = new URL(params[0]);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setReadTimeout(10000);
        httpURLConnection.setConnectTimeout(15000);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        deleteDataInDB();
        outputStream = httpURLConnection.getOutputStream();
        bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write(StringGenerator.queryResults(nameValuePairs));
        bufferedWriter.flush();
        bufferedWriter.close();
        outputStream.close();
        httpURLConnection.connect();
        inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
        jsonResult = StringGenerator.inputStreamToString(inputStream,CartActivity.this);
        Log.e("Response: ",jsonResult.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return cartItems;
}

@Override
protected void onPostExecute(List<CartList> cartLists) {
    super.onPostExecute(cartLists);
    progressDialog.dismiss();
}
}

设置方法

private void deleteDataInDB(){

        nameValuePairs.add(new BasicNameValuePair(AppConstant.PRODUCT_NAME_VALUE_PAIR,nameAdapter));
        Log.e("Name Adapter Value: ",nameAdapter);
        nameValuePairs.add(new BasicNameValuePair(AppConstant.COMPANY_INTENT_ID,magazi_id));
        Log.e("Magazi id: ",magazi_id);
        nameValuePairs.add(new BasicNameValuePair(AppConstant.PRODUCT_WAITER_ID_VALUE_PAIR,servitoros_id));
        Log.e("Servitoros id: ",servitoros_id);
        nameValuePairs.add(new BasicNameValuePair(AppConstant.PRODUCT_TABLE_ID_VALUE_PAIR,table));
        Log.e("Table: ",table);
    }

我执行任务的地方:

@Override
        public boolean onActionItemClicked(ActionMode mode,MenuItem item) {
            switch (item.getItemId()){
                case R.id.deleteCartItemModification:{
                    for (int position = 0; position<names.size(); position++){
                        nameAdapter = names.get(position);
                        deleteDataWebService();
                        adapter.notifyItemRemoved(position);
                    }
                    setupTotalValue();
                    Toast.makeText(CartActivity.this,"Items Deleted",Toast.LENGTH_SHORT).show();
                    adapter.notifyDataSetChanged();
                    AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
                    builder.setTitle(getString(R.string.delete));
                    builder.setMessage(getString(R.string.delete_msg));
                    builder.setPositiveButton(getString(R.string.yes),new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,int which) {
                            deleteDataWebService();
                            Toast.makeText(CartActivity.this,Toast.LENGTH_SHORT).show();
                            adapter.notifyDataSetChanged();
                        }
                    });
                    builder.setNegativeButton(getString(R.string.no),int which) {
                            dialog.cancel();
                        }
                    });
                    builder.create();
                    builder.show();
                }
            }
            return true;
        }

响应:

12-17 05:37:24.043 2099-2099/com.order.app.order E/NamesAdded:: [BLT Sandwich,Club Sandwich]
12-17 05:37:24.045 2099-2099/com.order.app.order I/AppCompatDelegate: The Activity's LayoutInflater already has a Factory installed so we can not install AppCompat's
12-17 05:37:24.086 2099-2118/com.order.app.order W/EGL_emulation: eglSurfaceAttrib not implemented
12-17 05:37:24.086 2099-2118/com.order.app.order W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa0883cc0,error=EGL_SUCCESS
12-17 05:37:26.390 2099-2118/com.order.app.order D/OpenGLRenderer: endAllStagingAnimators on 0xa1ce1b00 (RippleDrawable) with handle 0xa18d8700
12-17 05:37:26.417 2099-2123/com.order.app.order E/Response:: DELETE FROM cart WHERE product_name='Club Sandwich' AND magazi_id='53' AND servitoros_id='724' AND trapezi='3'
12-17 05:37:26.430 2099-2118/com.order.app.order W/EGL_emulation: eglSurfaceAttrib not implemented
12-17 05:37:26.430 2099-2118/com.order.app.order W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa0883cc0,error=EGL_SUCCESS
12-17 05:37:26.445 2099-2123/com.order.app.order E/Response:: DELETE FROM cart WHERE product_name='Club Sandwich' AND magazi_id='53' AND servitoros_id='724' AND trapezi='3'

虽然添加名称是:[BLT三明治,俱乐部三明治]

响应是最后一个对象的两倍:

E/Response:: DELETE FROM cart WHERE product_name='Club Sandwich' AND magazi_id='53' AND servitoros_id='724' AND trapezi='3'
E/Response:: DELETE FROM cart WHERE product_name='Club Sandwich' AND magazi_id='53' AND servitoros_id='724' AND trapezi='3'

deleteDataWebService:

private void deleteDataWebService(){
        DeleteData deleteData = new DeleteData();
        deleteData.execute(AppConstant.DELETE_URL);
    }

PHP文件

<?PHP
ini_set("default_charset","UTF-8");
    header('Content-type: text/html; charset=UTF-8');
try {
    $handler = new PDO('MysqL:host=my_server;dbname=database','username','password');
        $handler->setAttribute(PDO::MysqL_ATTR_INIT_COMMAND,"SET NAMES utf8 ");
    $handler->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        $handler->exec("SET CHARACTER SET 'utf8'"); 
} catch (Exception $e) {
    echo $e->getMessage();
    die();
}
$productName = $_POST['productName'];
$magazi = $_POST['magazi_id'];
$servitoros = $_POST['servitoros_id'];
$trapezi = $_POST['trapezi'];
$handler->query("DELETE FROM cart WHERE product_name='$productName' AND magazi_id='$magazi' AND servitoros_id='$servitoros' AND trapezi='$trapezi'");
die("Deleted");
?>

只有最后一个项目被删除.有任何想法吗?

这是因为异步执行.调用deleteDataWebService()方法仅调度执行DeleteData任务,不会立即执行.任务实际上是在一段时间后进行的.

假设你有两个要删除的项目,在for循环中:

> nameAdapter为item1设置,
>任务计划执行,
> nameAdapter为item2设置,

一段时间之后

> task2使用nameAdapter执行任务,
> task2使用nameAdapter执行任务,

将值作为参数传递给异步任务,而不是通过nameAdapter共享变量传递它将解决问题.也可以在任务实例之间共享nameValuePairs.

例如:

private class DeleteData extends AsyncTask<String,List<CartList>> {
    ArrayList<BasicNameValuePair> nameValuePairs;

    private void deleteDataInDB(String name){
        nameValuePairs.add(new BasicNameValuePair(AppConstant.PRODUCT_NAME_VALUE_PAIR,name));
        ...
    }
    ...

    @Override
    protected List<CartList> doInBackground(String... params) {
        ...
        deleteDataInDB(params[1]);
        ...
    }

    ...
}

private void deleteDataWebService(String name){
    DeleteData deleteData = new DeleteData();
    deleteData.execute(AppConstant.DELETE_URL,name);
}
原文链接:https://www.f2er.com/php/131944.html

猜你在找的PHP相关文章