RecyclerView中的Swipe-To-Dismiss产生错误

时间:2016-04-19 11:32:21

标签: android database sqlite android-recyclerview android-cardview

我有一个RecyclerView,其中我已经夸大了CardView。我有一个名为AlarmDBHelper的数据库助手。在我的一个片段中,我使用一个按钮添加警报,这些警报会添加到RecyclerViewDatabase。使用数据库查看器,我可以看到条目已正确添加。

问题是我使用Swipe-To-Dismiss添加了ItemTouchHelper。但是当我滑动删除卡片视图时,删除不是永久性的。 cardview已删除,但数据库中的条目未删除。当我移动到另一个片段然后回到前一个片段时,我可以看到所有的cardview再次出现。有趣的是,这次删除是永久性的,即如果我现在滑动,它们将被永久删除。

我的AlarmDBHelper

package com.aniket.digitalapprentice;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
  import java.util.ArrayList;
import java.util.List;

/**
   * Created by Aniket on 4/18/2016.
 */
public class AlarmDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="alarmsManager";
public static final int DATABASE_VERSION=1;
public static final String TABLE_ALARMS="alarms";
public static final String KEY_ID="id";
public static final String KEY_LABEL="label";
public static final String KEY_TIME="time";
public static final String KEY_DATE="date";
public SimpleDateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
public SimpleDateFormat timeFormat=new SimpleDateFormat("HH:mm");
public AlarmDBHelper(Context context)
{
    super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_ALARM_TABLE="CREATE TABLE " + TABLE_ALARMS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_LABEL + " TEXT," + KEY_DATE+" TEXT," + KEY_TIME + " TEXT" + ")";
    db.execSQL(CREATE_ALARM_TABLE);
}

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

}
public void addAlarm(Alarm alarm)
{
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues values=new ContentValues();
    values.put(KEY_LABEL,alarm.getLabel());
    values.put(KEY_DATE,dateFormat.format(alarm.getDate()));
    values.put(KEY_TIME,timeFormat.format(alarm.getTime()));
    db.insert(TABLE_ALARMS,null,values);
    db.close();
}
public Alarm getAlarm(int id) throws ParseException {
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor=db.query(TABLE_ALARMS, new String[]{KEY_ID,KEY_LABEL,KEY_DATE,KEY_TIME},KEY_ID+"=?",new String[]{String.valueOf(id)},null,null,null,null);
    if(cursor!=null) cursor.moveToFirst();
    Alarm alarm=new Alarm(Integer.parseInt(cursor.getString(0)),cursor.getString(1),dateFormat.parse(cursor.getString(2)),timeFormat.parse(cursor.getString(3)));
    return alarm;
}
public ArrayList<Alarm> getAllAlarms() throws ParseException {
    ArrayList<Alarm> alarmList=new ArrayList<Alarm>();
    String selectQuery = "SELECT  * FROM " + TABLE_ALARMS;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if(cursor.moveToFirst())
    {
        do {
                Alarm alarm=new Alarm(cursor.getInt(0),cursor.getString(1),dateFormat.parse(cursor.getString(2)),timeFormat.parse(cursor.getString(3)));
                alarmList.add(alarm);


        }while (cursor.moveToNext());
    }
    cursor.close();
    return alarmList;
}
public int getAlarmCount()
{
    String countQuery = "SELECT  * FROM " + TABLE_ALARMS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}
public int updateAlarm(Alarm alarm)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_LABEL,alarm.getLabel());
    values.put(KEY_TIME,timeFormat.format(alarm.getTime()));
    values.put(KEY_DATE,dateFormat.format(alarm.getDate()));
    return db.update(TABLE_ALARMS,values,KEY_ID+"=?",new String[]{String.valueOf(alarm.getId())});

}
public void deleteAlarm(Alarm alarm)
{
    SQLiteDatabase db=this.getWritableDatabase();
    db.delete(TABLE_ALARMS,KEY_ID+" =? ",new String[]{String.valueOf(alarm.getId())});
    db.close();
}

}

我的ItemTouchHelper

 ItemTouchHelper.SimpleCallback simpleCallback=new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            int index=viewHolder.getAdapterPosition();
            db.deleteAlarm(alarmList1.get(index));
            Toast.makeText(getContext(),"deleted "+(index),Toast.LENGTH_SHORT).show();
            alarmList1.remove(index);
            alarmAdapter.notifyItemRemoved(index);
        }

    };
    ItemTouchHelper itemTouchHelper=new ItemTouchHelper(simpleCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);

2 个答案:

答案 0 :(得分:0)

我想帮助你,但是你能发布一个简单的动画gif来解释更多并展示你的情况吗? 如果可能,请告诉我您应用内的所有步骤和操作(确切的活动和/或片段发生在您的问题中)。 例如,您可以使用Android Studio创建Android应用的动画gif(Android&gt; Monitor&gt; Screen Recorder&gt; Start Recording)。 我希望我能以某种方式帮助你。

答案 1 :(得分:0)

将数据库的删除功能设为:

public boolean deleteAlarm(int id){
  int result=db.delete(TABLE_ALARMS, KEY_ID + "=?", new String[]     {String.valueof(id)});
  if(result>0)
    return true;
  return false;
}

然后在适配器类中执行remove函数:

public void remove(int pos){
  // The name of the class which is used as a helper for database to get
  // and set value suppose DatabaseHelper

  DatabaseHelper dbHelper = alarmlist.get(pos);
  int id = dbHelper.getId();

  AlarmDBHelper alarmHelper = new AlarmDBHelper(context);
  if(alarmHelper.deleteAlarm(id)){
    alarmlist.remove(pos);
  } else
    Toast.makeText(context,"Unable to delete",Toast.LENGTH_SHORT).show();
    this.notifyItemRemoved(pos);

  // Now simply call the remove function in onSwiped function as:  
    onSwiped(RecyclerView.ViewHolder viewHolder, int direction){
      adapter.remove(viewHolder.getAdapterPosition);
      // Here adapter is the object of the adapter class made for recyclerview
    }
}