繁体   English   中英

通过Android从MySQL表删除行

[英]Delete row from MySQL table via android

单击时,我需要从android的列表视图中删除一个项目。 问题是,我的表不在电话(SQLite)上,而是在服务器上。 因此,我为此使用了PHP代码。 我已经设置了onClickListener。

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> a, View v,int position, long id) {
                            Show_Alert_box(v.getContext(),
                                    "Please select action.", position);
                        }
                    });

public void Show_Alert_box(Context context, String message, int position) {
    final int pos = position;

    final AlertDialog alertDialog = new AlertDialog.Builder(context)
            .create();
    //alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
    alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            DBHandlerComments dbhelper = new DBHandlerComments(Comments.this);
            SQLiteDatabase db = dbhelper.getWritableDatabase();
            try{

                JSONObject json2 = JSONParser.makeHttpRequest(urlDelete, "POST", params);


                try {
                    int success = json2.getInt(TAG_SUCCESS);

                    if (success == 1) {
                        // successfully updated
                        Intent i = getIntent();
                        // send result code 100 to notify about product update
                        setResult(100, i);
                        finish();
                    } else {
                        // failed to update product
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //adapter.notifyDataSetChanged();
                db.close();
            }catch(Exception e){
            }


        }
    });
    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            alertDialog.dismiss();
        }
    });

    alertDialog.setMessage(message);
    alertDialog.show();
}

这是我的JSONParser的makehttprequest代码:

public static 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));

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

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

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

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        //from here
        while ((line = reader.readLine()) != null) {
            if(!line.startsWith("<", 0)){
                if(!line.startsWith("(", 0)){
                    sb.append(line + "\n");
                }
            }
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

`这是我的PHP代码:

$response = array();

if (isset($_POST['id'])) {
$id = $_POST['id'];

// include db connect class
$db = mysql_connect("localhost","tbl","password");

if (!$db) {

    die('Could not connect to db: ' . mysql_error());

}


//Select the Database

mysql_select_db("shareity",$db);

// mysql update row with matched id
$result = mysql_query("DELETE FROM comments_activities WHERE id = $id");

// check if row deleted or not
if (mysql_affected_rows() > 0) {
    // successfully updated
    $response["success"] = 1;
    $response["message"] = "Product successfully deleted";

    // echoing JSON response
    echo json_encode($response);
} else {
    // no product found
    $response["success"] = 0;
    $response["message"] = "No product found";

    // echo no users JSON
    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);
}

我正在添加这样的参数:

            params.add(new BasicNameValuePair(KEY_ID, id));
            params.add(new BasicNameValuePair(KEY_AID, aid));
            params.add(new BasicNameValuePair(KEY_ANAME, an));
            params.add(new BasicNameValuePair(KEY_EVENT, ev));
            params.add(new BasicNameValuePair(KEY_COMMENT, cb));
            params.add(new BasicNameValuePair(KEY_USER, cby));
            params.add(new BasicNameValuePair(KEY_TIME, cd));

我没有任何结果。 我能知道为什么吗?

我注意到您添加了不需要的参数,尽管您只需要ID。

这是删除给定ID的简单代码,您可以尝试一下。 如果成功,则错误将出现在您的android代码中。

<?php
    $servername = "your servername";
    $username = "your username";
    $password = "your password";
    $dbname = "your dbname";

    $link = mysql_connect($servername, $username, $password);
    mysql_select_db($dbname, $link);
    $id=$_POST['id'];
    $result = mysql_query("DELETE FROM table_name WHERE id=$id", $link);

    $response["success"] = 1;
    $response["message"] = "Deleted successfully!";
    echo json_encode($response); 
?> 

将服务器名称更改为您的数据库URL,等等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM