Realm OrderedRealmCollectionChangeListener не работает

Моя текущая версия области: 4.3.3, версия адаптера области: 2.1.1 (последние версии)

Я использовал OrderedRealmCollectionChangeListener в качестве документации Realm: https://realm.io/docs/java/latest/#notifications

Но OrderedRealmCollectionChangeListener не срабатывает, когда к адаптеру добавляется только первый элемент, пока адаптер не обновится. Я не мог найти, где я сделал ошибку.

Помогите пожалуйста мне.

Мой адаптер:

 public class MyAdapter<V extends View & BindableItem>
        extends MyRealmRecyclerViewAdapter<Model, RecyclerView.ViewHolder> {

    private final
    @NonNull
    LayoutInflater inflater;

    public MyAdapter(@Nullable ItemClickListener clickListener,
                               OrderedRealmCollection<Model> data) {

        super(data);

        this.inflater = LayoutInflater.from(context);
        this.realm = MyApplication.getInstance().openRealm(this.getClass().getName());

    }

    public boolean realmControl() {

        if (realm == null || realm.isClosed()) {

            realm = MyApplication.getInstance().openRealm(this.getClass().getName());

            updateData(new ModelQueries().getAllModels(getRealm()));
            notifyView();

            return true;
        } else {
            return false;
        }
    }

MyRealmRecyclerViewAdapter:

abstract class MyRealmRecyclerViewAdapter<T extends Model, VH extends RecyclerView.ViewHolder> extends RealmRecyclerViewAdapter<Model, VH> {

    protected Context context;
    private String TAG = MyRealmRecyclerViewAdapter.class.getSimpleName();

    protected Realm realm;

    private OrderedRealmCollection<T> allModels;
    private int allModelsCount = 0;
    private final OrderedRealmCollectionChangeListener listener;

    MyRealmRecyclerViewAdapter(@Nullable OrderedRealmCollection<T> data) {

        super((OrderedRealmCollection<Model>) data, true, true);

        if (data != null && !data.isManaged())
            throw new IllegalStateException("Only use this adapter with managed RealmCollection, " +
                    "for un-managed lists you can just use the BaseRecyclerViewAdapter");

        this.context = MyApplication.getContext();
        this.allModels = data;
        this.listener = createListener();
    }

    private OrderedRealmCollectionChangeListener createListener() {
        return new OrderedRealmCollectionChangeListener() {
            @Override
            public void onChange(@NonNull Object collection, OrderedCollectionChangeSet changeSet) {

                Mylog.i(TAG, " changeSet : " + changeSet);

                if (changeSet == null) {
                    return;
                }
                OrderedCollectionChangeSet.Range[] insertions = changeSet.getInsertionRanges();

                if (insertions.length > 0) {
                    newModelsControl(getItemCount() - allModelsCount, getItemCount() - 1);
                    refreshAllModelsCount();
                }
            }
        };
    }

    @Override
    public int getItemCount() {

        try {
            if (getData() == null) {
                return 0;
            } else {
                return getData().size();
            }
        } catch (Exception e) {
            restartActivity();
            return 0;
        }

    }

    public void refreshAllModelsCount() {
        allModelsCount = getItemCount();
    }

    public Realm getRealm() {

        if (realm == null || realm.isClosed()) {
            realm = MyApplication.getInstance().openRealm(this.getClass().getName());
        }

        return realm;
    }


    private boolean isDataValid() {
        return getData() != null && getData().size() > 0 && getData().isValid();
    }

    @Override
    public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        if (isDataValid()) {
            //noinspection ConstantConditions
            addListener(allModels);
        }
    }

    @Override
    public void onDetachedFromRecyclerView(final RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        if (isDataValid()) {
            //noinspection ConstantConditions
            removeListener(allModels);
        }
    }

    private void addListener(@NonNull OrderedRealmCollection<T> data) {
        if (data instanceof RealmResults) {
            RealmResults<T> results = (RealmResults<T>) data;
            //noinspection unchecked
            results.addChangeListener(listener);
        } else if (data instanceof RealmList) {
            RealmList<T> list = (RealmList<T>) data;
            //noinspection unchecked
            list.addChangeListener(listener);
        } else {
            throw new IllegalArgumentException("RealmCollection not supported: " + data.getClass());
        }
    }

    private void removeListener(@NonNull OrderedRealmCollection<T> data) {
        if (data instanceof RealmResults) {
            RealmResults<T> results = (RealmResults<T>) data;
            //noinspection unchecked
            results.removeChangeListener(listener);
        } else if (data instanceof RealmList) {
            RealmList<T> list = (RealmList<T>) data;
            //noinspection unchecked
            list.removeChangeListener(listener);
        } else {
            throw new IllegalArgumentException("RealmCollection not supported: " + data.getClass());
        }
    }



    /**
     * Returns the item associated with the specified position.
     * Can return {@code null} if provided Realm instance by {@link OrderedRealmCollection} is closed.
     *
     * @param index index of the item.
     * @return the item at the specified position, {@code null} if adapter data is not valid.
     */
    @SuppressWarnings("WeakerAccess")
    public T getItem(int index) {
        try {

            return isDataValid() ? allModels.get(index) : null;

        } catch (Exception e) {

            Mylog.printStackTrace(" MyRealmRecyclerViewAdapter getItem error ", e);
            return null;
        }
    }
}

person propoLis    schedule 01.03.2018    source источник


Ответы (1)


Использовать это

abstract class MyAdapter<T extends Model, VH extends RecyclerView.ViewHolder> extends RealmRecyclerViewAdapter<Model, VH> {

    protected Context context;
    private String TAG = "MyAdapter";
    protected Realm realm;

    MyAdapter(@Nullable OrderedRealmCollection<T> data, Realm realm) {    
        super((OrderedRealmCollection<Model>) data, true);

        if (data != null && !data.isManaged())
            throw new IllegalStateException("Only use this adapter with managed RealmCollection, " +
                    "for un-managed lists you can just use the BaseRecyclerViewAdapter");

        this.context = MyApp.getContext();
        this.realm = realm;
    }       
}

У вас есть куча логики, которую уже сделал RealmRecyclerViewAdapter.

Замените getAllModels() на getData(), а setAllModels() на updateData() (методы RealmRecyclerViewAdapter).

person EpicPandaForce    schedule 01.03.2018
comment
Я обновил вопрос в соответствии с тем, что вы сказали, но это не сработало :( - person propoLis; 01.03.2018
comment
Вы также удалили методы, которые я удалил, и все такое? - person EpicPandaForce; 01.03.2018
comment
В вашем обновленном коде все еще есть куча ненужных вещей, поэтому мой вопрос: D - person EpicPandaForce; 01.03.2018