如何正确删除CardView? (使用SQLite数据库)

时间:2015-03-14 10:09:04

标签: android sqlite swipe android-recyclerview android-cursoradapter

我正在开发一个Android应用程序,该应用程序显示一系列卡片,其中包含一些存储在本地SQLite数据库中的信息(在主片段中)。

this问题中的Matteo一样,我已经实现了自定义回收器适配器(GitHub link),还有一个用于滑动的自定义侦听器(SwipeableRecyclerView),但面对的是有点不同的问题。当我刷我的carview项目时,它会回到它的''开始位置,可能根本没有删除以前刷过的项目(来自与我的回收器适配器一起使用的数据库和回收站视图)。

我的数据库助手的代码如下:

public class GeekNotesDatabaseHelper {
    static final String DB_NAME = "geeknotes_db";
    static final String TABLE = "notes_table";
    static final int VERSION = 1;
    static final String UID = "_id";
    static final String TITLE = "title";
    static final String CATEGORY = "category";

    private DBHelper dbHelper;
    private SQLiteDatabase database;

    public GeekNotesDatabaseHelper(Context context) {
        dbHelper = new DBHelper(context);
        database = dbHelper.getWritableDatabase();
    }

    public void insertData(String title, String category) {
        ContentValues cv = new ContentValues();
        cv.put(TITLE, title);
        cv.put(CATEGORY, category);
        database.insert(TABLE, null, cv);
    }

    public Cursor getAllData() {
        String buildSQL = "SELECT * FROM " + TABLE + " ORDER BY " + UID + " DESC";
        return database.rawQuery(buildSQL, null);
    }

    public void deleteByID(int position) {
        database.delete(TABLE, UID + " = " + position, null);
    }

    private class DBHelper extends SQLiteOpenHelper {
        public DBHelper(Context context) {
            super(context, DB_NAME, null, VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + TABLE + " (" + UID + " INTEGER " +
                    "PRIMARY KEY AUTOINCREMENT, " + TITLE + " TEXT, " + CATEGORY + " TEXT);");
        }

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

适配器类:

public class GeekNotesAdapter extends CursorRecyclerAdapter<GeekNotesAdapter.ViewHolder> {
    private final Fragment fragment;
    private OnItemClickListener itemClickListener;

    public GeekNotesAdapter(Cursor cursor, Fragment fragment) {
        super(cursor);
        this.fragment = fragment;
    }

    @Override
    public void onBindViewHolderCursor(ViewHolder holder, Cursor cursor) {
        holder.title.setText(
                cursor.getString(cursor.getColumnIndexOrThrow(GeekNotesDatabaseHelper.TITLE)).replaceAll("\\<[^>]*>", ""));

        holder.category.setText(
                cursor.getString((cursor.getColumnIndexOrThrow(GeekNotesDatabaseHelper.CATEGORY))));

        holder.id = cursor.getInt(cursor.getColumnIndexOrThrow(GeekNotesDatabaseHelper.UID));
    }

    @Override
    public GeekNotesAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        final LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
        final View sView = mInflater.inflate(R.layout.note_item, viewGroup, false);
        return new ViewHolder(sView);
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView title;
        TextView category;
        int id;

        public ViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.name);
            category = (TextView) view.findViewById(R.id.category);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (itemClickListener != null) {
                itemClickListener.onItemClick(v, id);
            }
        }
    }

    public interface OnItemClickListener {
        public void onItemClick(View view , int position);
    }

    public void setOnItemClickListener(final OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }
}

我的Fragment代码包含cardview-items:

public class GeekNotesFragment extends Fragment {

    GeekNotesDatabaseHelper dbHelper;
    GeekNotesAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.main_fragment, container, false);

        dbHelper = new GeekNotesDatabaseHelper(getActivity());

        Bundle bundle = getArguments();
        if (bundle != null) {
            // String itemTitle = bundle.getString("tag_item_title");
            // String itemCategory = bundle.getString("tag_item_category");
            Item item = (Item) bundle.getSerializable("note_item");
            dbHelper.insertData(item.getName(), item.getCategory());
        }

        final RecyclerView recyclerList = (RecyclerView) v.findViewById(R.id.itemsInCards);
        recyclerList.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerList.setLayoutManager(llm);

        setTargetFragment(GeekNotesFragment.this, 0);
        adapter = new GeekNotesAdapter(dbHelper.getAllData(), getTargetFragment());

        recyclerList.setAdapter(adapter);

        SwipeableRecyclerViewTouchListener swipeTouchListener =
                new SwipeableRecyclerViewTouchListener(recyclerList, new SwipeableRecyclerViewTouchListener.SwipeListener() {
                    @Override
                    public boolean canSwipe(int position) {
                        return true;
                    }

                    @Override
                    public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
                        for (int position : reverseSortedPositions) {
                            dbHelper.deleteByID(position);
                            adapter.notifyItemRemoved(position);
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
                        for (int position : reverseSortedPositions) {
                            dbHelper.deleteByID(position);
                            adapter.notifyItemRemoved(position);
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
        recyclerList.addOnItemTouchListener(swipeTouchListener);

        FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fab);
        fab.attachToRecyclerView(recyclerList);
        // fab.setBaselineAlignBottom(true);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.container, new NewNoteFragment());
                ft.addToBackStack(null);
                ft.commit();
            }
        });

        return v;
    }
}

将项目添加到我的数据库/ recyclerview很好。但删除 - 不幸的是,并没有。我是开发Android应用程序的新手,所以,请告诉我这里可能有什么问题,哪个问题不允许我正确删除卡片项目&amp;如何解决?

提前致谢。

1 个答案:

答案 0 :(得分:0)

嗯,这是一个很老的帖子。但我想回答,因为它可以帮助别人。

答案 - 尝试使用回收器视图的方法,例如 -

  1. public RecyclerView.ViewHolder findViewHolderForAdapterPosition(int position)
  2. public RecyclerView.ViewHolder findViewHolderForLayoutPosition(int position)
  3. 获取该位置的视图持有者,然后访问该视图的值,以便在数据库中删除。