2014-01-06 3 views
0

У меня есть пользовательский список-представление, которое загружает данные из внешней базы данных 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); 
} 
?> 
+0

Спасение: http://android.amberfog.com/?p=296 – Skynet

+0

Опубликовать список-адаптер тоже. – Skynet

+0

Нет класса ListAdapter. Это единственный класс, который загружает данные из базы данных и показывает их в List-view. для справки ознакомьтесь с приведенной ниже ссылкой http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ – InnocentKiller

ответ

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.

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(); 
      } 

Затем в doSomчто вы можете вызвать файл php для удаления элементов в таблице.

Смежные вопросы