androidrealmandroid-arrayadaptercustom-arrayadapter

Delete an item from the listview and realm


I'm trying to delete an item from listview (arrayadapter) when delete button is clicked but it crashes after it's being deleted from the realm database.

 @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;
    }

I'm using this code now to delete the item it's working but I think this code may cause in performance issue :

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

Solution

  • I've used RealmBaseAdapter instead.