0

嗨,我想从列表视图和数据库中删除选中的项目。我正在使用菜单。如果从菜单中选择删除,那么我想从列表视图和数据库中删除选定的项目。如果单击全选菜单我想设置列表项的所有复选框已选中,然后从列表视图中删除所有值并删除数据库中的所有记录。我使用以下代码在列表视图中使用复选框填充数据库中的数据。如果有人知道,请帮助我。

代码:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.senthistory);               
        lvhistory = (ListView) findViewById(android.R.id.list);     
        PopulateSentList();             
    }

    public void PopulateSentList() {

        String strquery = "SELECT * FROM sent_history";
        Cursor Cursor = (MainscreenActivity.JEEMAAndroSMSDB).rawQuery(
                strquery, null);

        MyAdapter adapter = new MyAdapter(SentHistoryActivity.this, Cursor);
        setListAdapter(adapter);    
        lvhistory.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                // TODO Auto-generated method stub
                SQLiteCursor selectedValue = (SQLiteCursor) getListAdapter()
                        .getItem(position);
                String id1 = selectedValue.getString(0);
                System.out.println("DATA-->>>" + id1);
                Intent intent = new Intent(getApplicationContext(),
                        Historydisplay.class);
                intent.putExtra("Id", id1);
                final int result = 1;
                startActivityForResult(intent, result);
            }           
        });
    }


    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(SentHistoryActivity.this,
                MainscreenActivity.class);
        startActivity(intent);
        finish();
    }

    private void CreateMenu(Menu menu) {
        menu.setQwertyMode(true);
        MenuItem mnu1 = menu.add(0, 0, 0, "Delete");
        {
            mnu1.setAlphabeticShortcut('D');
        }
        MenuItem mnu2 = menu.add(0, 0, 0, "Select All");
        {
            mnu2.setAlphabeticShortcut('S');
        }
    }

    private boolean MenuChoice(MenuItem item) throws Exception {
        switch (item.getItemId()) {
        case 0:
            int count = (int) getListAdapter().getCount();
            for (int i = 1; i <= count; i++) {
                if (this.lvhistory.isItemChecked(i)) {
                    listItems.remove(i);
                    adapter.notifyDataSetChanged();
                    MainscreenActivity.JEEMAAndroSMSDB.delete(
                            MainscreenActivity.Table_SentHistory, "_id=" +i, null); 
                    finish();
                    Intent intent = new Intent(getApplicationContext(),
                            SentHistoryActivity.class);
                    startActivity(intent);
                }
            }

            return true;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        try {
            return MenuChoice(item);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }       

    private class MyAdapter extends ResourceCursorAdapter {

        public MyAdapter(Context context, Cursor cur) {
            super(context, R.layout.dummy, cur);
        }

        @Override
        public View newView(Context context, Cursor cur, ViewGroup parent) {
            LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return li.inflate(R.layout.dummy, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cur) {
            TextView tvListText = (TextView)view.findViewById(R.id.Mobile);
            final CheckBox chkBox = (CheckBox)view.findViewById(R.id.check);            

            tvListText.setText(cur.getString(cur.getColumnIndex(MainscreenActivity.COL_Mobile)));
            chkBox.setTag(cur.getString(cur.getColumnIndex(MainscreenActivity.COL_Sent_id))); 

            chkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // TODO Auto-generated method stub
                    Log.v("Checked", chkBox.getTag().toString());                      
                }
            });
        }
    }
4

3 回答 3

2

要删除选中的项目,您可以对 CheckBox 使用 isChecked() 方法。在您的代码中,您可以按以下方式使用。

    chkBox.setOnClickListener(new new OnClickListener() {               
            @Override
            public void onClick(View v) { 
                // TODO Auto-generated method stub              
            CheckBox cb = (CheckBox)v;

            if(cb.isChecked() == true)
             { 
                  String getStrinValue = cb.getTExt().toString(); // here you will get the value of selected CheckBox
                     //  And now you have to perform your deletion operation as usual.                
              }
   }
于 2012-08-03T08:12:50.380 回答
0

好的,我将概述如何完成。这就是我为我的应用程序所做的。

首先,您需要为列表项创建一个模型类,该模型类具有维护状态(选中)的属性,然后每当您从数据库中获取项目时,都会创建项目列表,例如 arraylist。

然后,每当检查复选框时,请更改特定列表项目的状态属性。最后,当您从菜单中单击删除时,将分为三个步骤

  1. 从arraylist中获取选中的项目
  2. 从适配器中删除项目
  3. 从数据库中删除项目

我认为这是有道理的

编辑

你试过这个以前的SO问题吗?顺便说一句,这仅有助于从适配器中删除项目。您必须找到一种从数据库中删除项目的方法。

于 2012-08-03T09:20:36.930 回答
0

我就是这样做的。我发现这是始终匹配正确 ID 的最简单的解决方案。因为适配器和光标将始终具有相同的计数和位置。两者的起始索引均为 0。

这就是我的菜单项的内容。我还添加了一个警报对话框作为安全步骤。

    if (mListView.getCount() == 0 || mListView.getCheckedItemCount() == 0) {
        Toast.makeText(this, "Select an item by holding", Toast.LENGTH_SHORT).show();
        return false;
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Are you sure you want to delete these items?");
    builder.setCancelable(true);

    builder.setPositiveButton(
        "Yes",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                SparseBooleanArray selection = mListView.getCheckedItemPositions();
                Cursor data = mDBHandler.getAllIDs(); // "SELECT " + COLUMN_ID + " FROM " + TABLE_NAME;
                int itemID;
                int itemCount = arrayAdapter.getCount();
                for (int i=itemCount-1; i >= 0; i--) {
                    if (selection.get(i)) {
                        data.moveToPosition(i);
                        itemID = data.getInt(data.getColumnIndexOrThrow("id")); // COLUMN_ID = "id"
                        mDBHandler.deleteItem(itemID);
                    }
                }
                selection.clear();
                updateListView();
                dialog.cancel();
            }
        });

    builder.setNegativeButton(
        "No",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
    });

    AlertDialog alertDelete = builder.create();
    alertDelete.show();
    return true;


public void updateListView() {
    mListView.setAdapter(arrayAdapter);
    Cursor data = mDBHandler.getItems();
    arrayList.clear();
    while (data.moveToNext()) {
        arrayList.add(data.getString(1));
    }
    arrayAdapter.notifyDataSetChanged();
}
于 2018-01-11T10:28:46.840 回答