【问题标题】:Delete row from MySQL table via android通过android从MySQL表中删除行
【发布时间】: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));

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

【问题讨论】:

标签: php android mysql json android-listview


【解决方案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文件?
猜你喜欢
  • 2012-10-10
  • 2023-03-03
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 2015-08-23
相关资源
最近更新 更多