使用动态添加的复选框从android中的数据库填充的listview中删除数据?

时间:2014-06-28 14:23:37

标签: android database sqlite listview checkbox

您好我正在构建一个Android应用程序,它使用复选框从SQLite数据库中删除已检查的数据。我编写此代码来填充SQlite数据库中的数据。

public class DisplayAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<String> id;
    private ArrayList<String> firstName;
    private ArrayList<String> lastName;
    public static ArrayList<Integer> position=new ArrayList<Integer>();


    public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
        this.mContext = c;

        this.id = id;
        this.firstName = fname;
        this.lastName = lname;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return id.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public View getView(int pos, View child, ViewGroup parent) {
        final Holder mHolder;
        final int a=pos;
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.listcell, null);
            mHolder = new Holder();
            mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
            mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
            mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
            mHolder.checkbox  = (CheckBox) child.findViewById(R.id.checkbox);
            mHolder.checkbox.setTag(a);
            position.add(a);
            mHolder.checkbox.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    if(((CheckBox)v).isChecked()){
                        //Toast.makeText(mContext, ""+a,Toast.LENGTH_LONG).show();
                    }
                }
            });
            child.setTag(mHolder);

        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_id.setText(id.get(pos));
        mHolder.txt_fName.setText(firstName.get(pos));
        mHolder.txt_lName.setText(lastName.get(pos));

        return child;
    }

    public class Holder {
        CheckBox checkbox;
        TextView txt_id;
        TextView txt_fName;
        TextView txt_lName;
    }

}

我在listView活动上有一个按钮(删除)。检查复选框后当用户按下删除按钮时它将删除从数据库中删除的数据并显示数据库中剩余的其余数据。 这是我处理点击的活动。

public class DisplayActivity extends Activity {

    private DbHelper mHelper;
    private SQLiteDatabase dataBase;

    private ArrayList<String> userId = new ArrayList<String>();
    private ArrayList<String> user_fName = new ArrayList<String>();
    private ArrayList<String> user_lName = new ArrayList<String>();

    private ListView userList;
    private AlertDialog.Builder build;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_activity);


        userList = (ListView) findViewById(R.id.List);

        mHelper = new DbHelper(this);
        Button delete=(Button) findViewById(R.id.deleteBtn);
        delete.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                try {
                    if(userId.size()>0){

                        for(int i=0;i<DisplayAdapter.position.size();i++){
                            Toast.makeText(DisplayActivity.this, ""+i, Toast.LENGTH_SHORT).show();
                            View getView=userList.findViewWithTag(DisplayAdapter.position.get(i));
                            CheckBox checkbox = (CheckBox) getView
                                    .findViewById(R.id.checkbox);
                            if(checkbox.isChecked()){
                                //Toast.makeText(DisplayActivity.this, ""+i, Toast.LENGTH_SHORT).show();
                                dataBase.delete(
                                        DbHelper.TABLE_NAME,
                                        DbHelper.KEY_ID + "="
                                                +userId.get(i), null);

                                displayData();
                            }

                        }

                    }
                } catch (Exception e) {
                    Toast.makeText(DisplayActivity.this, "Nothing Selected", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }

            }
        });
        //add new record
        findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(),
                        AddActivity.class);
                i.putExtra("update", false);
                startActivity(i);

            }
        });

        //click to update data
        userList.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {

                Intent i = new Intent(getApplicationContext(),
                        AddActivity.class);
                i.putExtra("Fname", user_fName.get(arg2));
                i.putExtra("Lname", user_lName.get(arg2));
                i.putExtra("ID", userId.get(arg2));
                i.putExtra("update", true);
                startActivity(i);

            }
        });
    }

    @Override
    protected void onResume() {
        displayData();
        super.onResume();
    }

    /**
     * displays data from SQLite
     */
    private void displayData() {
        dataBase = mHelper.getWritableDatabase();
        Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
                + DbHelper.TABLE_NAME, null);

        userId.clear();
        user_fName.clear();
        user_lName.clear();
        if (mCursor.moveToFirst()) {
            do {
                userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
                user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
                user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

            } while (mCursor.moveToNext());
        }
        DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
        userList.setAdapter(disadpt);
        mCursor.close();

    }



}

它只删除listview中的第一个已检查项目以及数据库。但是我想从数据库中删除所有已检查的数据。我该怎么做?详情代码和解释将不胜感激。如果我犯了任何错误,请提前感谢并抱歉。

2 个答案:

答案 0 :(得分:0)

我使用并因此推荐的方法是:

在适配器上添加已选中的回调:

    List<YOUR_OBJ> checkedObjs;
    onUserCheckBoxCallback callback;
    ...
    public void OnCheckBoxCheckedCallback(onUserCheckBoxCallback callback) {
        this.callback = callback;
    }

    //this part goes on bindView
    yourCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        callback.onUserCheckBoxChanged(your_obj.get(pos), isChecked);
        }
    });

if (checkedObjs!= null && checkedObjs.size() > 0)
        yourCheckbox.setChecked(checkedObjs.contains(your_obj));

//this goes inside the adapter class
 public interface onUserCheckBoxCallback {
        void onUserCheckBoxChanged(YOUR_OBJECT_HERE, boolean isChecked);
    }

在您的活动中,您只需执行以下操作: 声明你的适配器

HashSet<YOUR_OBJ> checkedObjs;
...

//this part goes on onCreate()
adapter.OnCheckBoxCheckedCallback(new onUserCheckBoxCallback() {

@Override
public void onUserCheckBoxChanged(your_obj_type your_obj,boolean isChecked) {
        if (isChecked)
            checkedObjs.add(your_obj);
        else
        checkedObjs.remove(your_obj);
            }
        });

只需通过此列表重复删除所有对象!

希望它有所帮助!

答案 1 :(得分:0)

我可以为您提供一种方法来实现这一目标。

您可以将ArrayList保留为成员变量,并将其传递给DisplayAdapter的构造函数。每当用户点击您的CheckCox时,将点击的项目的位置添加到ArrayList,只要用户再次点击它,只需将其从ArrayList中移除。

然后您可以使用AsyncTask,在doInBackground()中,您可以从数据库执行删除操作,也可以从ArrayList删除数据。然后在onpostExecute()内,您可以拨打适配器的notifyDatasetChanged()