我有自定义列表视图,它从外部数据库MySQL
加载数据。现在我在删除数据时遇到问题,当我检查任何特定的复选框并尝试删除数据时,它删除了数据库中的所有数据而不是所选数据,但我只想删除已检查的记录。
我知道为什么会出现这个问题,但我不知道如何解决这个问题,问题是虽然删除它没有获得检查值位置,因为我没有做任何关于检查特定位置和删除的编码。因为我不知道如何获得检查值。
所以有人请告诉我如何只删除选中的值...以下是我的完整代码。我使用http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/作为参考的信息。
public class Classes_Ext_DB extends Activity implements OnClickListener {
ImageView imageViewNewClass, imageViewDelete;
ListView mListView;
/** Sliding Menu */
boolean alreadyShowing = false;
private int windowWidth;
private Animation animationClasses;
private RelativeLayout classesSlider;
LayoutInflater layoutInflaterClasses;
ArrayAdapter<CharSequence> adapterSpinner;
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_classDetail = "http://my-server/get_all_classdetail.php";
// url to delete product
private static final String url_delete_class = "http://my-server/delete_class.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_ID = "ID";
private static final String TAG_CLASSNAME = "class_name";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classes);
imageViewNewClass = (ImageView) findViewById(R.id.newclass);
imageViewDelete = (ImageView) findViewById(R.id.deletemenu);
mListView = (ListView) findViewById(R.id.displaydata);
productsList = new ArrayList<HashMap<String, String>>();
imageViewNewClass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Classes_Ext_DB.this,
Class_Create_Ext_DB.class);
startActivity(intent);
}
});
imageViewDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Classes_Ext_DB.this);
final Spinner spinnerDelete = new Spinner(Classes_Ext_DB.this);
alertDialog.setView(spinnerDelete);
adapterSpinner = ArrayAdapter.createFromResource(
Classes_Ext_DB.this, R.array.delete_menu,
android.R.layout.simple_spinner_item);
adapterSpinner
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDelete.setAdapter(adapterSpinner);
alertDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
if (spinnerDelete.getSelectedItemPosition() == 0) {
new DeleteProduct().execute();
}
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
alertDialog.show();
}
});
new LoadAllClassDetail().execute();
}
class LoadAllClassDetail extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Classes_Ext_DB.this);
pDialog.setMessage("Loading Classes. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_classDetail,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Classes: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String cid = c.getString(TAG_ID);
String cn = c.getString(TAG_CLASSNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, cid);
map.put(TAG_CLASSNAME, cn);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Class_Create_Ext_DB.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Classes_Ext_DB.this, productsList,
R.layout.custom_class, new String[] {
TAG_CLASSNAME, TAG_ID },
new int[] { R.id.classname});
// updating listview
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setDivider(new ColorDrawable(0x99000000));
mListView.setDividerHeight(1);
}
});
}
}
/*****************************************************************
* Background Async Task to Delete Class
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Classes_Ext_DB.this);
pDialog.setMessage("Deleting Class... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ID", TAG_ID));
// getting product details by making HTTP request
JSONObject json = jParser.makeHttpRequest(url_delete_class,
"POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
custom_class.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/classname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textStyle="bold" />
</LinearLayout>
现在的问题是,我已经将我的自定义类调整为
ListAdapter adapter = new SimpleAdapter(
Classes_Ext_DB.this, productsList,
R.layout.custom_class, new String[] {
TAG_CLASSNAME, TAG_ID },
new int[] { R.id.classname});
所以我不知道如何声明我的Check-box
并获取删除或编辑的特定check-box
值。
请帮我解决这个问题。先感谢您。任何帮助将不胜感激。
**编辑**
delete_class.php
<?php
/*
* Following code will delete a product from table
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['ID'])) {
$ID= $_POST['ID'];
// include db connect class
require_once ('db_connect.php');
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("DELETE FROM class_create 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);
}
?>
get_all_classdetail.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once ('db_connect.php');
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT * FROM class_create") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["ID"] = $row["ID"];
$product["class_name"] = $row["class_name"];
$product["class_days"] = $row["class_days"];
$product["class_time"] = $row["class_time"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
答案 0 :(得分:0)
package com.example.test;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
ArrayList<String> delteID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView) findViewById(R.id.listView1);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
"OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
"Android", "iPhone", "WindowsMobile" };
MySimpleArrayAdapter adapter=new MySimpleArrayAdapter(getApplicationContext(), values);
listView.setAdapter(adapter);
delteID=new ArrayList<String>();
Button deleteButton=(Button) findViewById(R.id.deleteBt);
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for (String string : delteID) {
Log.i("TAG", string);
//U can send the Delete Request from HERE
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.custom_list, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.custom_list, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.text1);
CheckBox checkBox = (CheckBox) rowView.findViewById(R.id.check1);
textView.setText(values[position]);
checkBox.setOnCheckedChangeListener(new CheckUpdateListener(position));
// Change the icon for Windows and iPhone
String s = values[position];
return rowView;
}
private final class CheckUpdateListener implements OnCheckedChangeListener
{
private final int index;
/**
* @param child
*/
private CheckUpdateListener(int index)
{
this.index = index;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if(isChecked)
{
delteID.add("ID"+index);
//U may get the id from the actual data u received form the server itself with **index** variable
}
else
{
delteID.remove("ID"+index);
//remove the unchecked id from list
}
}
}
}
}
<强> activity_main.xml中强>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/deleteBt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Delete" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="15dp" >
</ListView>
</RelativeLayout>
<强> custom_list.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_weight="1.0" />
<CheckBox
android:id="@+id/check1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.1" />
</LinearLayout>
这是代码将具有如何处理listView中的复选框的基本模型。
答案 1 :(得分:0)
使用BaseAdapter而不是CustomAdapter,在基本适配器中,您可以使用按钮和复选框。
CheckBox = cbx;
for (int x = 0; x<lst.getChildCount();x++){
cbx = (CheckBox)lst.getChildAt(x).findViewById(R.id.checkBox);
if(cb.isChecked()){
doSomething();
}
然后在doSomething中你可以调用一个php文件删除表中的项目。