简体   繁体   English

OnItemLongClick从ListView中删除,数据库不删除

[英]OnItemLongClick to delete from ListView and database not deleting

I have created a ListView and populated it with items from a database. 我创建了一个ListView并用数据库中的项目填充它。 Currently I am trying to make it so you can long click on an item and delete it from both the ListView and the database together, but something seems to be going wrong. 目前,我正在尝试使它成为可能,以便您可以长按一个项目并将其从ListView和数据库中一起删除,但是似乎出现了问题。 Everything works correctly up until the deleting part. 一切正常,直到删除部分。 I have it so it deletes the item by fetching its id, which is where I think it is going wrong. 我有它,因此它通过获取其ID删除了该项目,这是我认为出问题的地方。 I have found a way to show the id and everytime it is returning 0. I have no idea why it is doing this. 我找到了一种显示ID的方法,并且每次返回0时都不知道。为什么不这样做呢。 I am getting no errors, but it is not working as I am hoping for it to. 我没有收到任何错误,但是它没有按我希望的那样工作。 If anybody could point me in the right direction for this that would be awesome. 如果有人能为此指出正确的方向,那就太好了。

Here is my databaseHelper class: 这是我的databaseHelper类:

public class HabitDbHelper extends SQLiteOpenHelper{
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME="habits";

    public static final String TABLE_HABITS = "habit_names";
    public static final String KEY_NAME = "hname";
    public static final String KEY_ID = "id";
    public static final String KEY_STARTDATE = "start_date";
    public static final String KEY_ENDDATE = "end_date";
    public static final String KEY_DAYCOUNT = "day_count";

    public HabitDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE "+TABLE_HABITS+" ("
                +KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
                +KEY_NAME+" TEXT, "
                +KEY_STARTDATE+" TEXT, "
                +KEY_ENDDATE+" TEXT, "
                +KEY_DAYCOUNT+" INTEGER);");
    }

    // Upgrading Database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_HABITS);
        onCreate(db);
    }

    //Adding new habit
    public void addHabit(Habit habit) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, habit.getName()); // Habit Name
        values.put(KEY_STARTDATE, habit.getStartDate()); // Start Date
        values.put(KEY_ENDDATE, habit.getEndDate()); // End Date
        values.put(KEY_DAYCOUNT, habit.getDayCount());

        // Inserting Row
        db.insert(TABLE_HABITS, null, values);
        db.close(); // Closing database connection
    }

    // Fetching 1 Habit
    public Habit getHabit(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_HABITS, new String[] { KEY_ID,
                        KEY_NAME, KEY_STARTDATE ,KEY_ENDDATE, KEY_DAYCOUNT }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Habit habit = new Habit(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), Integer.parseInt(cursor.getString(4)));
        // return contact
        return habit;
    }

    // Fetching all Habits
    public ArrayList<Habit> getAllHabits() {
        ArrayList<Habit> habitList = new ArrayList<Habit>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_HABITS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Habit habit = new Habit();
                habit.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
                habit.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
                habit.setStartDate(cursor.getString(cursor.getColumnIndex(KEY_STARTDATE)));
                habit.setEndDate(cursor.getString(cursor.getColumnIndex(KEY_ENDDATE)));
                habit.setDayCount(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_DAYCOUNT))));

                // Adding contact to list
                habitList.add(habit);
            } while (cursor.moveToNext());
        }
        return habitList;
    }

    //Updating single habit
    public int updateHabit(Habit habit) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, habit.getName());
        values.put(KEY_STARTDATE, String.valueOf(habit.getStartDate())); // Start Date
        values.put(KEY_ENDDATE, habit.getEndDate()); // End Date
        values.put(KEY_DAYCOUNT, habit.getDayCount()); // Day Count

        // updating row
        return db.update(TABLE_HABITS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(habit.getID()) });
    }

    // Deleting Single Habit
    public void deleteHabit(Habit habit) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_HABITS, KEY_ID + " = ?",
                new String[] { Integer.toString(habit.getID()) });
        db.close();
    }

    // Getting habits count
    public int getHabitsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_HABITS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}

And my mainActivity where I am calling the onItemLongClickListener with the delete method: 我的mainActivity中,我使用delete方法调用onItemLongClickListener:

public class fourtyMain extends Activity
{
    private HabitDbHelper               mDB;
    private ListView                    mList;

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

        mList = (ListView)findViewById(R.id.habit_list);
        mDB = new HabitDbHelper(this);

        getActionBar().setDisplayShowTitleEnabled(false);

        //long click to delete data
        mList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> parent, final View view, int position, long id) {

                final Habit habit = (Habit) parent.getAdapter().getItem(position);
                deleteHabitInListView(habit);
                return true;
            }

            private void deleteHabitInListView(final Habit habit){
                Builder deleteDialog = new AlertDialog.Builder(fourtyMain.this);
                deleteDialog.setTitle("Delete " + habit.getName() + "?");
                deleteDialog.setMessage("Are you sure you want to delete this habit? All your progress will be lost!");
                deleteDialog.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDB.deleteHabit(habit);
                        displayData();

                    }
                });

                deleteDialog.setNegativeButton("No", new AlertDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                deleteDialog.show();
            }
        });
    }

My ListView adapter class: 我的ListView适配器类:

public class HabitAdapter extends BaseAdapter {

    private ArrayList<Habit> habits;
    private Context context;
    private int layoutId, id1;

    public HabitAdapter(Context c, int LayoutId,ArrayList<Habit> habits) {
        this.context = c;
        this.layoutId = LayoutId;
        this.habits = habits;
    }

    @Override
    public int getCount() {
        return habits.size();
    }

    @Override
    public Habit getItem(int position) {
        return habits.get(position);
    }

    @Override
    public long getItemId(int position) {
        Habit habit = (Habit)habits.get(position);
        Long idInt = Long.parseLong(habit.getIDString());
        return id1;
    }

    public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutInflater;
        Habit habit = habits.get(pos);
        if (child == null) {
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.fragment_start_habit_item, null);
            mHolder = new Holder();
            mHolder.title = (TextView)child.findViewById(R.id.fragment_title);
            mHolder.dayCount = (TextView)child.findViewById(R.id.fragment_days_left);
            mHolder.startDate = (TextView)child.findViewById(R.id.fragment_start_date);
            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.title.setText(habit.getName());
        mHolder.dayCount.setText("Days Completed: " + habit.getDayCountString());
        mHolder.startDate.setText("Date Started: " + habit.getStartDate());
        return child;
    }

    public class Holder {
        TextView title;
        TextView dayCount;
        TextView startDate;
    }

}

And finally my Habit Object Class: 最后是我的习惯对象类:

public class Habit {

    private int day_count;
    private int _id;
    private String habit_name, date_started, end_date, day_count_string, id_string;

    public Habit(){
    }

    public Habit(int id, String name, String startDate, String endDate, int dayCount){
        this._id = id;
        this.habit_name = name;
        this.date_started = startDate;
        this.end_date = endDate;
        this.day_count = dayCount;
    }

    public Habit(String name, String startDate, String endDate, int dayCount){
        this.habit_name = name;
        this.date_started = startDate;
        this.end_date = endDate;
        this.day_count = dayCount;
    }

    public int getID()
    {
        return _id;
    }

    public int setID(int id)
    {
        return this._id;
    }

    public String getIDString()
    {
        id_string = "" + this._id;
        return id_string;
    }

    public int getDayCount()
    {
        return this.day_count;
    }

    public String getDayCountString()
    {
        day_count_string = "" + this.day_count;
        return day_count_string;
    }

    public int setDayCount(int dayCount)
    {
        return this.day_count;
    }

    public String getName()
    {
        return this.habit_name;
    }

    public void setName(String name)
    {
        this.habit_name = name;
    }

    public String getStartDate()
    {
        return this.date_started;
    }

    public void setStartDate(String startDate)
    {
        this.date_started = startDate;
    }

    public String getEndDate()
    {
        return this.end_date;
    }

    public void setEndDate(String endDate)
    {
        this.end_date = endDate;
    }

}

Now I think I am retrieving the id wrong either from my Habit object class or from the Listview adapter. 现在我想我从我的Habit对象类或从Listview适配器检索id错误。 I am not sure and I am completely lost on this one. 我不确定,对此我完全迷失了。 Any help is greatly appreciated! 任何帮助是极大的赞赏!

How are you populating your ArrayList? 您如何填充ArrayList? How are you setting the id of each Habit? 您如何设置每个习惯的ID? This is just a guess, but perhaps you are using the position in the Listview as an ID, which does not match the database id? 这只是一个猜测,但是也许您将Listview中的位置用作ID,但与数据库ID不匹配? Also, can you clarify "not working"? 另外,您能否澄清“不起作用”? Is it deleting? 它正在删除吗? Not deleting? 不删除?

尝试在适配器上调用notifyDataSetChanged()或尝试在listview上调用invalidateViews()。

the database is not deleting because the id in your table is different than the one in your listview.Every time you create an entry, it is established with a new unique id not by its order in the table as the listview does. 数据库不会删除,因为表中的ID与列表视图中的ID不同。每次创建条目时,都会使用一个新的唯一ID建立该条目,而不是像列表视图那样在表中按其顺序排列。 So add this method to your habitDbHelper class: 因此,将此方法添加到您的habitDbHelper类中:

                    public void delete(int orderInList){//orederInList is the position in your listView
                    SQLiteDatabase db = this.getWritableDatabase();
                    List<Integer> database_ids = new ArrayList<Integer>();
                    Cursor c = db.rawQuery("SELECT*FROM "+TABLE_HABITS,null);
                    while(c.moveToNext){
                    database_ids.add(Integer.parseInt(c.getString(0)));
                    }
                    db.delete(TABLE_HABITS,KEY_ID + " =?",new String[]{String.valueOf(database_ids.get(orderInList)});

And if you want to delete it OnLongClick add this: 如果要删除它,请在OnLongClick上添加以下内容:

                    ListView lv = (ListView)findViewById(R.id.your_id);
                    lv.setLongClickable(true);
                    lv.setOnLongClickListener(new OnLongClickListener(){

                    @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                 int position,  long id) {
                                     AlertDialog.Builder aat = new AlertDialog.Builder(this);
        aat.setTitle("Delete?")
                .setMessage("Are you sure you want to delete "+parent.getItemAtPosition(position).toString()+"?")
                .setCancelable(true)
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel();
                    }

                })
                .setPositiveButton("Delete", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub

                       HabitDbHelper helper = new HabitDBHelper(this);

                        helper.delete(position);


                        helper.close();
                        onCreate(null);//call it here to refresh listView upon delete

    }
});
 AlertDialog art = aat.create();

 art.show();

           }

          });

hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM