Realm Recyclerview Adapter显示编辑和删除选项的错误

时间:2017-08-29 13:02:56

标签: android android-recyclerview realm android-cardview realm-mobile-platform

我正在尝试实现一个简单的待办事项列表应用程序。我在这里使用Realm作为本地数据库。在recyclerview中的cardview项目中,我在左侧创建了Taskname,任务日期,在右侧创建了check,delete选项。现在第一个问题是,当我点击检查选项或删除选项时,应用程序崩溃并显示一条错误消息

已编辑的适配器类

public class TaskAdapter extends RealmRecyclerViewAdapter<Task, TaskAdapter.TaskHolder> {
public final static String INTENT_KEY_POSITION = "position";
public final static String DATE_FORMAT = "dd/MMM/yy";

private Realm realm;

public interface TaskListener {

}

private final TaskListener taskListener;
private final Context context;

public TaskAdapter(TaskListener taskListener, RealmResults<Task> realmResults, Context context) {
    super(realmResults, true);
    this.taskListener = taskListener;
    this.context = context;
}

@Override
public TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new TaskHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.row_task_list_layout, parent, false));
}

@Override
public void onBindViewHolder(TaskHolder holder, final int position) {
    final Task task = getData().get(position);
    holder.taskTextView.setText(task.getName());
    holder.doneCheckBox.setChecked(task.isDone());
    final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);

    final Date date = (task.getDate());
    if (sdf.format(date).equals(sdf.format(getDate(0))))
        holder.dateTextView.setText("Today");
    else if (sdf.format(date).equals(sdf.format(getDate(-1))))
        holder.dateTextView.setText("Yesterday");
    else if (sdf.format(date).equals(sdf.format(getDate(1))))
        holder.dateTextView.setText("Tomorrow");
    else if (date.getTime() < getDate(6).getTime()) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        holder.dateTextView.setText(DateFormat.format("EEEE", calendar.getTime()).toString());
    } else
        holder.dateTextView.setText(sdf.format(task.getDate()));
    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, AddTaskActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(INTENT_KEY_POSITION, position);
            context.startActivity(intent);
        }
    });

    holder.doneCheckBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Task task = new Task();
            task.setId(getTask(position).getId());
            task.setDate(getTask(position).getDate());
            task.setName(getTask(position).getName());
            task.setDone(((CheckBox) v).isChecked());
            updateTask(position, task);
        }
    });

    holder.deleteImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getTask(position).isDone()) {
                removeTask(position);
                return;
            }
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
            alertDialog.setTitle("Confirm Delete?");
            alertDialog.setMessage("Do you want to delete the task you created?");
            alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    removeTask(position);
                }
            });
            alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            alertDialog.show();
        }
    });
}

public class TaskHolder extends RecyclerView.ViewHolder {
    public CardView cardView;
    public TextView taskTextView;
    public TextView dateTextView;
    public ImageView deleteImageView;
    public CheckBox doneCheckBox;

    public TaskHolder(View itemView) {
        super(itemView);

        taskTextView = (TextView) itemView.findViewById(R.id.row_task_list_tv_name);
        dateTextView = (TextView) itemView.findViewById(R.id.row_task_list_tv_date);
        deleteImageView = (ImageView) itemView.findViewById(R.id.row_task_list_iv_delete);
        doneCheckBox = (CheckBox) itemView.findViewById(R.id.row_task_list_cb_done);
        cardView = (CardView) itemView.findViewById(R.id.cardView);
    }
}

private Date getDate(int day) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, day);
    return calendar.getTime();
}

protected Task getTask(int position) {
    return getData().get(position);
}

protected void updateTask(int position, Task task) {
    realm.beginTransaction();
    Task newTask = realm.where(Task.class).equalTo("id", task.getId()).findFirst();
    newTask.setDate(task.getDate());
    newTask.setDone(task.isDone());
    newTask.setName(task.getName());
    realm.commitTransaction();
}

protected void removeTask(int position) {
    Task newTask = realm.where(Task.class).equalTo("id", getTask(position).getId()).findFirst();
    realm.beginTransaction();
    newTask.deleteFromRealm();
    realm.commitTransaction();
}

}

已编辑的活动类

    public class TaskActivity extends AppCompatActivity implements TaskAdapter.TaskListener{

    private static final int ADD_TASK_REQUEST_CODE = 1000;
    private static final int EDIT_TASK_REQUEST_CODE = 1001;

    private Realm realm;

    private RecyclerView recyclerView;
    private TaskAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tasks);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("ToDo List");
        setSupportActionBar(toolbar);

        realm = Realm.getDefaultInstance();
        recyclerView =(RecyclerView)findViewById(R.id.activity_tasks_ll_task);

        setUpRecycler();

        // Variables

        realm=Realm.getDefaultInstance();

        // Views
        FloatingActionButton addFloatingActionButton = (FloatingActionButton) findViewById(R.id.activity_tasks_fab_add);
        //Listeners
        addFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getApplicationContext(), AddTaskActivity.class), ADD_TASK_REQUEST_CODE);
            }
        });
    }

    private void setAdapter() {

        adapter = new TaskAdapter(this, realm.where(Task.class).findAllSortedAsync("name"),this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private void setUpRecycler() {

        recyclerView.setHasFixedSize(true);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        setAdapter();
    }
}

已编辑的AddActivity类

public class TodoAddActivity extends AppCompatActivity {

    // Variables
    private Context mContext;

    private Realm realm;
    private TodoModel task;
    private Button button;
    private EditText mTaskNameEditText;
    private EditText mTaskDateEditText;
    private EditText mTaskTimeEditText;

String time;
    //private static List<TodoModel> tasks;

    public final static String INTENT_KEY_POSITION = "position";
    public final static String DATE_FORMAT = "dd/MMM/yy";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.todo_add_layout);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mContext = this;
        realm=Realm.getDefaultInstance();
        setUpUIViews();
        showData();

        final int position = getIntent().getIntExtra(INTENT_KEY_POSITION, -1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TodoModel.ID == -1)
                    addTask();
                else
                    editTask(position);
            }
        });
        mTaskDateEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                datePicker(view);
            }
        });
        mTaskDateEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b)
                    datePicker(view);
            }
        });
        mTaskTimeEditText.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timePicker( view );
            }
        } );
        mTaskTimeEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b)
                    timePicker( view );
            }
        });
        if (position != -1) {
            fillTask(getTask(position)); //how can i modify this line
            button.setText("EDIT");
        }

    }
    private void setUpUIViews() {
        button = (Button) findViewById(R.id.activity_add_task_bt_add);
        mTaskNameEditText = (EditText) findViewById(R.id.activity_add_task_et_name);
        mTaskDateEditText = (EditText) findViewById(R.id.activity_add_task_et_date);
        mTaskTimeEditText = (EditText) findViewById(R.id.activity_add_task_et_time);
    }

    public void showData(){

        RealmResults<TodoModel> tasksResult = realm.where(TodoModel.class).findAll();

    }

    private void fillTask(TodoModel task) {
        mTaskNameEditText.setText(task.getName());
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        mTaskDateEditText.setText(sdf.format(task.getDate()));
        mTaskTimeEditText.setText(task.getTime());
    }

    private void addTask() {
        String taskName = mTaskNameEditText.getText().toString();
        String taskDate = mTaskDateEditText.getText().toString();
        String taskTime = mTaskTimeEditText.getText().toString();
        if (taskName.length() == 0 || taskName.equals("")) {
            mTaskNameEditText.setError("Should be filled");
            return;
        }
        if (taskDate.length() == 0 || taskDate.equals("")) {
            mTaskDateEditText.setError("Should be filled");
            return;
        }
        TodoModel task = getTask(taskName, taskDate,taskTime);
        if (task == null) {
            mTaskDateEditText.setError("Not a correct date");
            return;
        }
        task.setDone(false);
        addTask(task);
        setResult(RESULT_OK);
        finish();
    }

    protected void addTask(TodoModel task) {

        realm.beginTransaction();
        TodoModel newTask = realm.createObject(TodoModel.class, UUID.randomUUID().toString());
        newTask.setName(task.getName());
        newTask.setDate(task.getDate());
        newTask.setTime(task.getTime());
        realm.copyToRealmOrUpdate(newTask);
        realm.commitTransaction();
        realm.close();
    }
    private void editTask(int position) {
        String taskName = mTaskNameEditText.getText().toString();
        String taskDate = mTaskDateEditText.getText().toString();
        String taskTime = mTaskTimeEditText.getText().toString();
        if (taskName.length() == 0 || taskName.equals("")) {
            mTaskNameEditText.setError("Should be filled");
            return;
        }
        if (taskDate.length() == 0 || taskDate.equals("")) {
            mTaskDateEditText.setError("Should be filled");
            return;
        }
        if (taskTime.length() == 0 || taskTime.equals("")) {
            mTaskTimeEditText.setError("Should be filled");
            return;
        }
        TodoModel task = getTask(taskName, taskDate,taskTime);
        if (task == null) {
            mTaskDateEditText.setError("Not a correct date");
            return;
        }
        task.setId(getTask(position).getId());
        updateTask(position, task);
        setResult(RESULT_OK);
        finish();
    }

    protected void updateTask(int position, TodoModel task) {

        realm.beginTransaction();
        TodoModel newTask = realm.where(TodoModel.class).equalTo("id", task.getId()).findFirst();
        newTask.setDate(task.getDate());
        newTask.setDone(task.isDone());
        newTask.setName(task.getName());
        realm.commitTransaction();
    }


    private void datePicker(final View view) {
        Calendar currentTime = Calendar.getInstance();
        int year = currentTime.get(Calendar.YEAR);
        int monthOfYear = currentTime.get(Calendar.MONTH);
        int dayOfMonth = currentTime.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog mDatePickerDialog = new DatePickerDialog(mContext, 0, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, monthOfYear, dayOfMonth);
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
                ((EditText) view).setText(sdf.format(calendar.getTime()));
            }
        }, year, monthOfYear, dayOfMonth);

        mDatePickerDialog.setTitle("Select Time");
        mDatePickerDialog.show();
    }
    private void timePicker(final View view) {
        Calendar mcurrentTime = Calendar.getInstance();
        int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
        int minute = mcurrentTime.get(Calendar.MINUTE);
        TimePickerDialog mTimePicker;
        mTimePicker = new TimePickerDialog(mContext,0, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                mTaskTimeEditText.setText( selectedHour + ":" + selectedMinute);
            }
        }, hour, minute, true);//Yes 24 hour time
        mTimePicker.setTitle("Select Time");
        mTimePicker.show();

    }


    private TodoModel getTask(String name, String dateString,String time) {
        TodoModel task = new TodoModel();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
            task.setName(name);
            task.setDate(sdf.parse(dateString));
            task.setTime(time );
            task.setDone(false);
            return task;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home)
            onBackPressed();
        return super.onOptionsItemSelected(item);
    }
    public class TaskCompare implements Comparator<TodoModel> {
        @Override
        public int compare(TodoModel o1, TodoModel o2) {
            return o1.getDate().compareTo(o2.getDate());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

public class TaskAdapter extends RealmRecyclerViewAdapter<Task, TaskAdapter.TaskHolder> {
    public final static String INTENT_KEY_POSITION = "position";
    public final static String DATE_FORMAT = "dd/MMM/yy";

    private Realm realm;

    public interface TaskListener {

    }

    private final TaskListener taskListener;
    private final Context context;

    public TaskAdapter(TaskListener taskListener, RealmResults<Task> realmResults, Context context, Realm realm) {
        super(realmResults, true);
        this.taskListener = taskListener;
        this.context = context;
        this.realm = realm;
    }

    @Override
    public TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new TaskHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.row_task_list_layout, parent, false));
    }

    @Override
    public void onBindViewHolder(TaskHolder holder, final int position) {
        final Task task = getData().get(position);
        holder.taskTextView.setText(task.getName());
        holder.doneCheckBox.setChecked(task.isDone());
        final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);

        final Date date = (task.getDate());
        if (sdf.format(date).equals(sdf.format(getDate(0))))
            holder.dateTextView.setText("Today");
        else if (sdf.format(date).equals(sdf.format(getDate(-1))))
            holder.dateTextView.setText("Yesterday");
        else if (sdf.format(date).equals(sdf.format(getDate(1))))
            holder.dateTextView.setText("Tomorrow");
        else if (date.getTime() < getDate(6).getTime()) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            holder.dateTextView.setText(DateFormat.format("EEEE", calendar.getTime()).toString());
        } else
            holder.dateTextView.setText(sdf.format(task.getDate()));
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, AddTaskActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(INTENT_KEY_POSITION, position);
                context.startActivity(intent);
            }
        });

        holder.doneCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Task task = new Task();
                task.setId(getTask(position).getId());
                task.setDate(getTask(position).getDate());
                task.setName(getTask(position).getName());
                task.setDone(((CheckBox) v).isChecked());
                updateTask(position, task);
            }
        });

        holder.deleteImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getTask(position).isDone()) {
                    removeTask(position);
                    return;
                }
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                alertDialog.setTitle("Confirm Delete?");
                alertDialog.setMessage("Do you want to delete the task you created?");
                alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        removeTask(position);
                    }
                });
                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                alertDialog.show();
            }
        });
    }

    public class TaskHolder extends RecyclerView.ViewHolder {
        public CardView cardView;
        public TextView taskTextView;
        public TextView dateTextView;
        public ImageView deleteImageView;
        public CheckBox doneCheckBox;

        public TaskHolder(View itemView) {
            super(itemView);

            taskTextView = (TextView) itemView.findViewById(R.id.row_task_list_tv_name);
            dateTextView = (TextView) itemView.findViewById(R.id.row_task_list_tv_date);
            deleteImageView = (ImageView) itemView.findViewById(R.id.row_task_list_iv_delete);
            doneCheckBox = (CheckBox) itemView.findViewById(R.id.row_task_list_cb_done);
            cardView = (CardView) itemView.findViewById(R.id.cardView);
        }
    }

    private Date getDate(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, day);
        return calendar.getTime();
    }

    protected Task getTask(int position) {
        return getData().get(position);
    }

    protected void updateTask(int position, Task task) {
        realm.beginTransaction();
        Task newTask = realm.where(Task.class).equalTo("id", task.getId()).findFirst();
        newTask.setDate(task.getDate());
        newTask.setDone(task.isDone());
        newTask.setName(task.getName());
        realm.commitTransaction();
    }

    protected void removeTask(int position) {
        realm.beginTransaction();
        Task newTask = realm.where(Task.class).equalTo("id", getTask(position).getId()).findFirst();
        newTask.deleteFromRealm();
        realm.commitTransaction();
    }
}

public class TaskActivity extends AppCompatActivity implements TaskAdapter.TaskListener {    
    private static final int ADD_TASK_REQUEST_CODE = 1000;
    private static final int EDIT_TASK_REQUEST_CODE = 1001;

    private Realm realm;

    public final static String INTENT_KEY_POSITION = "position";
    public final static String DATE_FORMAT = "dd/MMM/yy";

    private RecyclerView recyclerView;
    private TaskAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tasks);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("ToDo List");
        setSupportActionBar(toolbar);

        realm = Realm.getDefaultInstance();
        recyclerView =(RecyclerView)findViewById(R.id.activity_tasks_ll_task);

        setUpRecycler();

        // Views
        FloatingActionButton addFloatingActionButton = (FloatingActionButton) findViewById(R.id.activity_tasks_fab_add);
        //Listeners
        addFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getApplicationContext(), AddTaskActivity.class), ADD_TASK_REQUEST_CODE);
            }
        });
    }

    private void setAdapter() {    
        adapter = new TaskAdapter(this, realm.where(Task.class).findAllSortedAsync("date"),this, realm);
        recyclerView.setAdapter(adapter);
    }

    private void setUpRecycler() {
        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        recyclerView.setHasFixedSize(true);
        // use a linear layout manager since the cards are vertically scrollable
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        setAdapter();
    }
}

public class AddTaskActivity extends AppCompatActivity {

// Variables
private Context mContext;

private Realm realm;

private Button button;
private EditText mTaskNameEditText;
private EditText mTaskDateEditText;

public final static String INTENT_KEY_POSITION = "position";
public final static String DATE_FORMAT = "dd/MMM/yy";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_task);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Add Task");

    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mContext = this;
    realm=Realm.getDefaultInstance();
    setUpUIViews();
    showData();

    final int position = getIntent().getIntExtra(INTENT_KEY_POSITION, 0);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (position == -1)
                addTask();
            else
                editTask(position);
        }
    });
    mTaskDateEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            datePicker(view);
        }
    });
    mTaskDateEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (b)
                datePicker(view);
        }
    });
    if (position != -1) {
        fillTask(getTask(position));
        button.setText("EDIT");
    }
}