У меня есть пользовательский список-представление, которое загружает данные из внешней базы данных MySQL
. Теперь у меня проблема при удалении данных, когда я проверяю какой-либо конкретный флажок и пытаюсь удалить данные, которые он удаляет, все данные в базе данных не выбраны, но я просто хочу удалить отмеченные записи.Как удалить данные из списка, который отмечен
Я знаю, почему эта проблема возникает, но я не знаю, как решить эту проблему. Проблема заключается в том, что при удалении она не получает проверочную позицию значения, потому что я не делал никакой кодировки относительно проверки конкретной позиции и удаления. Потому что я не знаю, как я могу получить проверенное значение.
Итак, кто-нибудь скажет мне, как удалить только проверенные значения ... Ниже мой полный код. FOr я использовал 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>
Теперь проблема в том, что я caled мой пользовательский класс как
ListAdapter adapter = new SimpleAdapter(
Classes_Ext_DB.this, productsList,
R.layout.custom_class, new String[] {
TAG_CLASSNAME, TAG_ID },
new int[] { R.id.classname});
Так я надеваю» t как я могу объявить свой Check-box
и получить значение check-box
для удаления или редактирования.
Пожалуйста, помогите мне разобраться с этой проблемой. Заранее спасибо. Любая помощь будет принята с благодарностью.
** EDIT **
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);
}
?>
Спасение: http://android.amberfog.com/?p=296 – Skynet
Опубликовать список-адаптер тоже. – Skynet
Нет класса ListAdapter. Это единственный класс, который загружает данные из базы данных и показывает их в List-view. для справки ознакомьтесь с приведенной ниже ссылкой http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ – InnocentKiller