Android:Listview项目未删除。我没有被检索

时间:2014-05-08 03:54:47

标签: java android database listview

我目前正在尝试向ListView onItemLongClick添加删除功能。不幸的是,出于某种原因我似乎无法做到这一点。每当我长按,对话框都会正确显示,当我按是删除时,根本不会发生任何事情。该项仍然保留在Listview和数据库中,因为我调用该方法在我调用delete方法后立即显示更新数据库中的所有项。我一直试图解决这个问题两天,但我无处可去。好像它无法从数据库中为每个项目检索Id,但我不确定为什么会这样做。

这是我的习惯对象类:

public class Habit extends Object implements Serializable{

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

这是我的databaseHelper代码,我调用add习惯在数据库中创建一个习惯项,我调用deleteHabit来删除习惯对象类中id的位置的习惯:

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

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

}

这是我的Listview适配器,其中每个项目都放入自定义项目布局:

public class HabitAdapter extends BaseAdapter {

    private ArrayList<Habit> habits;
    private Context context;
    private int layoutId;
    private long 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);
        id1 = 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;
    }

}

最后,我的主要活动是删除在onItemLongClick上选择的项目:

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

        //Start new activity with click
        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long arg3)
            {
                Intent singleI = new Intent(fourtyMain.this, SingleHabitView.class);
                final Habit habit = (Habit) parent.getAdapter().getItem(position);
                singleI.putExtra("habit", habit);
                startActivity(singleI);
            }
        });

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

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

    private void displayData()
    {
        ArrayList<Habit> habitList = mDB.getAllHabits();

        HabitAdapter disadpt = new HabitAdapter(fourtyMain.this, R.layout.fragment_start_habit_item, habitList);
        mList.setAdapter(disadpt);
        disadpt.notifyDataSetChanged();
    }
}

我绝对迷失于此。我已经工作了两天,试图解决这个问题而且我无处可去。如果我不得不猜测,我认为从数据库中检索ID或者错误地存储它我都会出错。

编辑: 为了增加这一点,我只是找到了一种方法,只要单击该项,就可以将id写入toast。无论列表中的哪个项目,它都会返回0作为id。这让我觉得我要么错误地获取id或者存储错误而我的删除功能是正确的。

5 个答案:

答案 0 :(得分:0)

不处理listview的setOnItemLongClickListener方法,而是处理特定单元格的setOnItemLongClickListener 就像bleow一样:

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.llCellLayout = (LinearLayout)child.findViewById(R.id.llCellLayout);
        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());
    mHolder.llCellLayout.setOnItemLongClickListener(new OnItemLongClickListener(){
      //** you can get id here and write code here for delete**
   });
    return child;
}

public class Holder {
    TextView title;
    TextView dayCount;
    TextView startDate;
    LinearLayout llCellLayout; //** this is the layout of cell**


}

答案 1 :(得分:0)

尝试删除如下,

 // Deleting Single Habit

public void deleteHabit(Habit habit) {
        SQLiteDatabase  database = this.getWritableDatabase();
            {
                database.execSQL("delete from " + "TABLE_HABITS"
                        + " where KEY_ID='" + String.valueOf(habit.getID())+ "'");
            }

        database .close();
    }

答案 2 :(得分:0)

尝试使用此代码进行删除操作

public float delete(String table,String colmName,String data) {
        // TODO Auto-generated method stub
        SQLiteDatabase db=dbhlpr.getWritableDatabase();
        String[] arr={data};
        colmName=colmName+"=?";
        float res=db.delete(table, colmName,arr );
        db.close();
        return res;
    }

答案 3 :(得分:0)

你可以尝试以下方法:

1.将查询更改为原始查询,如下所示:

public void deleteHabit(Habit habit) {
    SQLiteDatabase db = this.getWritableDatabase();
    String sql = "delete from " + TABLE_HABITS + " where " 
                  + KEY_ID + "=" + habit.getID();
    db.rawQuery(sql,null);
    db.close();
}

2.或者你也可以试试这个:

public void deleteHabit(Habit habit) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_HABITS, KEY_ID+ "=" + habit.getID(), null);
    db.close();
}

希望有所帮助!

答案 4 :(得分:0)

我设法弄明白了,当然这是最简单的错误。在我的习惯对象课中,我写了:

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

当我需要做的就是改变它:

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

愚蠢的新秀错误,但幸运的是,由于每个人的反复试验,我终于搞清楚了。感谢任何帮助过的人!