通过android从MySQL表中删除行

Posted

技术标签:

【中文标题】通过android从MySQL表中删除行【英文标题】:Delete row from MySQL table via android 【发布时间】:2015-07-21 02:53:52 【问题描述】:

单击时,我需要从 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));

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

【问题讨论】:

你需要定位问题。它是在Android还是服务器端?请求是否通过参数“id”到达服务器? @inmyth,我该如何检查? 你需要学习一些基本的调试来查看某些点的值是什么,才能知道哪里出错了。但我可以告诉你method == "POST" 是the wrong way to compare Strings in Java。 This might be helpful 以及 this part of the docs 【参考方案1】:

我注意到您添加了不需要的参数,尽管您只需要 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 等其他信息。

【讨论】:

您是否在线上传了php文件?

以上是关于通过android从MySQL表中删除行的主要内容,如果未能解决你的问题,请参考以下文章

MySQL 从表中删除所有行并将 ID 重置为零

MySQL 从表中删除所有行并将 ID 重置为零

MySQL InnoDB 从表中删除数据行后未释放磁盘空间

通过表单从 Access 联结表中删除行

删除/编辑 MySQL ODBC 链接表中的行导致 MS Access 出错

如何从 MySQL 表中删除重复记录? [复制]