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

时间:2014-05-06 23:32:36

标签: java android listview android-listview

我创建了一个ListView,并用数据库中的项填充它。目前我正在努力使它能够长时间点击一个项目并将它从ListView和数据库中一起删除,但似乎出现了问题。一切正常,直到删除部分。我有它所以它通过获取其ID来删除该项,这是我认为它出错的地方。我找到了一种方法来显示id并且每次它返回0.我不知道它为什么这样做。我没有得到任何错误,但它没有按照我希望的那样工作。如果有人能指出我正确的方向,这将是非常棒的。

这是我的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();
    }

}

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

我的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;
    }

}

最后我的习惯对象类:

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

}

现在我认为我从我的Habit对象类或Listview适配器检索id错误。我不确定,我完全失去了这个。非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

你如何填充你的ArrayList?你如何设置每个习惯的id?这只是一个猜测,但也许您使用Listview中的位置作为ID,它与数据库ID不匹配?另外,你能否澄清一下&#34;不工作&#34;?是删除吗?不删除?

答案 1 :(得分:0)

尝试在适配器上调用notifyDataSetChanged()或尝试在列表视图上调用invalidateViews()。

答案 2 :(得分:0)

数据库没有删除,因为表中的id与listview中的id不同。每次创建条目时,都会使用新的唯一ID建立,而不是像listview那样按表中的顺序建立。 所以将此方法添加到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)});

如果你想删除它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();

           }

          });

希望这会有所帮助。