从列表视图和领域中删除项目

时间:2018-05-19 22:21:02

标签: android realm android-arrayadapter custom-arrayadapter

当我点击删除按钮时,我试图从listview(arrayadapter)中删除一个项目,但是在从realm数据库中删除它之后它会崩溃。

 @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        realm = Realm.getDefaultInstance();

        View listItemView = convertView;

        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.meditations_list_item, parent, false);
        }

        Reminder reminder = getItem(position);

        TextView reminderHour = listItemView.findViewById(R.id.hour_tv);
        final ImageView deleteBtn = listItemView.findViewById(R.id.delete_btn);
        deleteBtn.setTag(position);
        final View finalListItemView = listItemView;
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Integer index = (Integer) deleteBtn.getTag();
                Reminder deletedReminder = getItem(index);
                if (deletedReminder == null) {
                    Toast.makeText(getContext(), "Error in deleting!", Toast.LENGTH_SHORT).show();
                    return;
                }

                String id = deletedReminder.getId();
                realm.beginTransaction();
                RealmResults<Reminder> reminderObjs = realm.where(Reminder.class)
                        .equalTo("id", id)
                        .findAll();
                boolean isDeleted = reminderObjs.deleteAllFromRealm();
                realm.commitTransaction();
                notifyDataSetChanged();
                Log.d(TAG, "execute: " + isDeleted);


            }
        });


        reminderHour.setText(reminder.getHours());

        return listItemView;
    }

我现在正在使用此代码删除它正在运行的项目,但我认为此代码可能会导致性能问题:

        clear();
        addAll(new ArrayList<Reminder>(realm.where(Reminder.class).findAll()));
        notifyDataSetChanged();

1 个答案:

答案 0 :(得分:1)

我已使用RealmBaseAdapter代替。