如何从RecyclerView和数据库中删除项目?

时间:2015-08-29 12:44:46

标签: java android database

在RecyclerView中添加和删除项目是有效的,但我不知道我是否在数据库中编写了一个删除行的好方法,因为只有在添加项目时以及删除项目时我才能保存条件如果我从应用程序离开并回来,但我已经删除了一些项目,我在那里看到它们。所以我需要在数据库中对这个方法有所帮助,以便删除项目并在活动中实现它。

以下是我的代码:

数据库:

    public class DBHelper extends SQLiteOpenHelper  {
    private static final String DATABASE_NAME = "items.db";
    private static final int DATABASE_VERSION = 1;

    private final String TABLE_ITEMS = "items";

    private final String COLUMN_ID = "id";
    private final String COLUMN_ITEM = "item";

    private static DBHelper dbh;

    private DBHelper(Activity activity) {
        super(activity, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static synchronized DBHelper getConnection(Activity activity) {
        if (dbh == null)
            dbh = new DBHelper(activity);
        return dbh;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String upitZaPravljanjeBaze =
                "CREATE TABLE "+TABLE_ITEMS+"("+COLUMN_ID+" INTEGER PRIMARY KEY, "+COLUMN_ITEM+" TEXT);";
        db.execSQL(upitZaPravljanjeBaze);

    }

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

    }

    public ArrayList<String> getAllItems() {
        ArrayList<String> toRet = new ArrayList<String>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.rawQuery("SELECT * FROM " + TABLE_ITEMS, null);
        c.moveToFirst();

        while(c.isAfterLast() == false) {
            toRet.add(c.getString(c.getColumnIndex(COLUMN_ITEM)));
            c.moveToNext();

        }

        return toRet;
    }

    public long saveItem(String item) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_ITEM, item);
        return db.insert(TABLE_ITEMS, null, cv);
    }

    public boolean deleteItem(long rowId) {
        SQLiteDatabase db = getReadableDatabase();
        return db.delete(TABLE_ITEMS, COLUMN_ID + "=" + rowId, null) > 0;
    }

}

ADAPTER:

    public class AdapterRecyclerAnimators extends RecyclerView.Adapter<AdapterRecyclerAnimators.Holder> {
    private ArrayList<String> mListData = new ArrayList<>();
    private LayoutInflater mLayoutInflater;


    public AdapterRecyclerAnimators(Context context) {
        mLayoutInflater = LayoutInflater.from(context);
    }


    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        View row = mLayoutInflater.inflate(R.layout.custom_row_item, parent, false);
        Holder holder = new Holder(row);
        return holder;
    }

    @Override
    public void onBindViewHolder(Holder holder, final int position) {
        String data = mListData.get(position);
        holder.textDataItem.setText(data);
        holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeItem(position);
            }
        });
    }

    public void addItem(String item) {
        mListData.add(item);
        notifyItemInserted(mListData.size());
    }
    public void addAll(ArrayList<String> newList){
        mListData = newList;
        notifyDataSetChanged();
    }

    public void removeItem(String item) {
        int position = mListData.indexOf(item);
        if (position != -1) {
            mListData.remove(item);
            notifyItemRemoved(position);
        }
    }

    public void removeItem(int position) {
        mListData.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public int getItemCount() {
        return mListData.size();
    }

    public static class Holder extends RecyclerView.ViewHolder {
        TextView textDataItem;
        ImageButton buttonDelete;

        public Holder(View itemView) {
            super(itemView);
            textDataItem = (TextView) itemView.findViewById(R.id.text_item);
            buttonDelete = (ImageButton) itemView.findViewById(R.id.button_delete);

        }
    }

}

主要活动:

    public class MainActivity extends BaseActivity {

    //int containing the duration of the animation run when items are added or removed from the RecyclerView
    public static final int ANIMATION_DURATION = 2000;
    //edit text letting the user type item name to be added to the recylcerview
    private EditText mInput;
    //itemcounter for recyclerview
    private TextView mItemCounter;
    //recyclerview showing all items added by the user
    private RecyclerView mRecyclerView;
    private AdapterRecyclerAnimators mAdapter;
    ArrayList<String> mListData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();

        if(savedInstanceState != null){
            ArrayList<String> items = savedInstanceState.getStringArrayList("items");
            mListData.addAll(items);
            mAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putStringArrayList("items", mListData);
    }

    private void initViews(){
        mInput = (EditText) findViewById(R.id.text_input);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerAnimatedItems);
        mItemCounter = (TextView) findViewById(R.id.itemCounter);
        mItemCounter.setText(String.valueOf(mRecyclerView.getChildCount()));
        mAdapter = new AdapterRecyclerAnimators(this);
        //set an animator on the RecyclerView that works only when items are added or removed
        mRecyclerView.setItemAnimator(new SlideInLeftAnimator());
        mRecyclerView.getItemAnimator().setAddDuration(ANIMATION_DURATION);
        mRecyclerView.getItemAnimator().setRemoveDuration(ANIMATION_DURATION);
        mAdapter.addAll(DBHelper.getConnection(MainActivity.this).getAllItems());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    public void addItem(View view) {
        //check if the EditText has valid contents
        if (Util.hasValidContents(mInput)) {
            DBHelper.getConnection(MainActivity.this)
                    .saveItem(mInput.getText().toString());

            ArrayList<String> allItems = DBHelper.getConnection(MainActivity.this).getAllItems();

            mAdapter.addAll(allItems);

            mInput.setText("");
        }
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_main;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:1)

这些是你的删除方法:

public void removeItem(String item) {
    int position = mListData.indexOf(item);
    if (position != -1) {
        mListData.remove(item);
        notifyItemRemoved(position);
    }
}

public void removeItem(int position) {
    mListData.remove(position);
    notifyItemRemoved(position);
}

您从列表中删除了这些项目,但从未将它们从数据库中删除。在这两种方法中调用你的删除方法,看它是否有效。

答案 1 :(得分:1)

不一定认为这会解决你的问题,但我想我会指出它,在你的数据库删除方法中你有:

SQLiteDatabase db = getReadableDatabase();

你可能想切换它:

SQLiteDatabase db = getWritableDatabase();