我需要你的幫助。我想通過RecyclerView中的SwipeToDelete從我的數據庫中刪除數據。從RecycleView裏面的數據庫中刪除數據
我已經有一個Swipe類從RecycleView刪除項目,我可以從列表中刪除項目,但不能從數據庫中刪除項目。
我已經試着撥打NoteAdapater(回收站適配器)的內部數據庫和刪除(INT位置),這樣,我想用的方法RemoveItem項目:
public void removeItem(int position){
db.deleteNote(position);
noteList.remove(position);
notifyItemRemoved(position);
}
這裏是在MainActivity代碼:
從數據庫public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
NoteAdapter adapter;
List<Note> myList;
FloatingActionButton fab;
DBHelper db = new DBHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initializeViews();
myList = db.getAllNotes();
adapter = new NoteAdapter(this,myList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addNewNote();
}
});
ItemTouchHelper.Callback callback = new Swipe(adapter);
ItemTouchHelper helper = new ItemTouchHelper(callback);
helper.attachToRecyclerView(recyclerView);
}
代碼,刪除數據:
public void deleteNote(int note){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",new String[] {String.valueOf(note)});
}
您在移除時遇到任何錯誤或什麼? –
@AlexanderPerfilyev我得到一個NullPointeException。我認爲我沒有初始化我的DatabaseHelper正確... –
是的,只是通過'db'作爲構造參數到您的適配器,它應該工作。 –