我尝试从recyclerview和slqlite数据库中删除一个项目。 这些是活动:
1。数据库
DatabaseHandler.java
public void deleteTask(long position){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TASKS, KEY_TASK_ID + "=" + position, null);
db.close();
}
TaskAdapter.java
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
final Task stringTask = tasksList.get(position);
holder.taskText.setText(stringTask.getTaskName());
holder.dateText.setText(stringTask.getTaskDate());
holder.id = stringTask.getID();
holder.deleteButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
tasksList.remove(position);
notifyItemRemoved(position);
dth.deleteTask(stringTask.getID());
}
});
}
这是错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.android.todolistapp.DatabaseHandler.deleteTask(long)' on a null object reference
at com.example.android.todolistapp.TaskAdapter$1.onClick(TaskAdapter.java:51)
at android.view.View.performClick(View.java:6935)
at android.widget.TextView.performClick(TextView.java:12738)
at android.view.View$PerformClick.run(View.java:26211)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
答案 0 :(得分:0)
dth.deleteTask(stringTask.getID()); dth未实例化。创建DatabaseHandler对象并分配给dth。