如何在listview中使用longclick从sqlite中删除listview数据?

时间:2016-05-19 13:46:29

标签: android sqlite listview

我想从sqlite中删除ListView填充的项目,使用警告对话框onLongClick上的ListView删除该项目

活动:

public class ResultActivity extends ListActivity {

     private String selectedItem;
     private final Context context = this;
     private ArrayAdapter<String> adapter;

    Intent intent;
    TextView Id;
    SaveData controller = new SaveData(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);


        ArrayList<HashMap<String, String>> hasilList = controller.getAllhasil();

        /* jikta tidak kosong, tampilkan data ke ListView
         *
         */

         if(hasilList.size()!=0) {

                    ListAdapter adapter = new SimpleAdapter(ResultActivity.this,
                            hasilList, R.layout.activity_view, new String[] {
                                    "Id", "inggris", "indonesia" }, new int[] {
                                    R.id.Id, R.id.inggris, R.id.indonesia });
                    setListAdapter(adapter);

                    ListView lv = getListView();
                    // Create the listener for long item clicks
                  //  OnItemLongClickListener itemLongListener = new OnItemLongClickListener() {
                   lv.setOnItemLongClickListener(new OnItemLongClickListener() {

                        @Override
                        public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long rowid) {

                             // Id = (TextView) v.findViewById(R.id.Id);
                             // String valId = Id.getText().toString();

                            // Store selected item in global variable
                            selectedItem = parent.getItemAtPosition(position).toString();

                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setMessage("Yakin Hapus " + selectedItem + "?");
                            builder.setCancelable(false);
                            builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {


                                    controller.deletehasil(selectedItem);
                                    controller.getAllhasil();


                                   // adapter.remove(selectedItem);
                                   // adapter.notifyDataSetChanged();


                                    Toast.makeText(
                                            getApplicationContext(),
                                            selectedItem + " Sudah Di Hapus.",
                                            Toast.LENGTH_SHORT).show();

                                }
                            });



                            builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });

                            // Create and show the dialog
                            builder.show();

                            // Signal OK to avoid further processing of the long click
                            return true;
                        }
                    });


         } 
                }



    @Override
     public void onBackPressed() {

         super.onBackPressed();
         overridePendingTransition(R.anim.fadein, R.anim.fadeout);
     }

}

dbhelper:

public class SaveData extends SQLiteOpenHelper {

    private static final String LOGCAT = null;

    public SaveData(Context applicationcontext) {
        super(applicationcontext, "hasil.db", null, 1);
        Log.d(LOGCAT,"Created");
    }

    @Override

    public void onCreate(SQLiteDatabase database) {
        String query;
        query = "CREATE TABLE hasil ( Id INTEGER PRIMARY KEY," +
                " inggris TEXT,indonesia TEXT)";
        database.execSQL(query);
        Log.d(LOGCAT,"hasil Created");
    }
    @Override

    public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
        String query;
        query = "DROP TABLE IF EXISTS hasil";
        database.execSQL(query);
        onCreate(database);
    }

    public void addhasil(HashMap<String, String> queryValues) {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("inggris", queryValues.get("inggris"));
        values.put("indonesia", queryValues.get("indonesia"));
        database.insert("hasil", null, values);
        database.close();
    }


    public void deletehasil(String id) {
        Log.d(LOGCAT,"delete");
        SQLiteDatabase database = this.getWritableDatabase();    
        String deleteQuery = "DELETE FROM hasil where Id='"+ id +"'";
        Log.d("query",deleteQuery);    
        database.execSQL(deleteQuery);
    }


    public ArrayList<HashMap<String, String>> getAllhasil() {
        ArrayList<HashMap<String, String>> hasilList;
        hasilList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  * FROM hasil";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Id", cursor.getString(0));
                map.put("inggris", cursor.getString(1));
                map.put("indonesia", cursor.getString(2));
                hasilList.add(map);
            } while (cursor.moveToNext());
        }

        // return contact list
        return hasilList;
    }

}

1 个答案:

答案 0 :(得分:0)

请查看以下longclick侦听器代码,其中有可删除元素注释的代码。

 lv.setOnItemLongClickListener(new OnItemLongClickListener() {

                            @Override
                            public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, long rowid) {

                                 // Id = (TextView) v.findViewById(R.id.Id);
                                 // String valId = Id.getText().toString();

                                // Store selected item in global variable
                                selectedItem = parent.getItemAtPosition(position).toString();

                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                builder.setMessage("Yakin Hapus " + selectedItem + "?");
                                builder.setCancelable(false);
                                builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {


                                        controller.deletehasil(selectedItem);
                                        controller.getAllhasil();

                                        //------------Code to remove element-----------
                                       hasilList.remove(position);
                                       adapter.notifyDataSetChanged();
                                       //-------------xxxxxxxxxxxxx-------------


                                        Toast.makeText(
                                                getApplicationContext(),
                                                selectedItem + " Sudah Di Hapus.",
                                                Toast.LENGTH_SHORT).show();

                                    }
                                });



                                builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                });

                                // Create and show the dialog
                                builder.show();

                                // Signal OK to avoid further processing of the long click
                                return true;
                            }
                        });