Данные в RecyclerView не обновляются при переключении дня

Есть активити, в котором пользователь может переключить день (предыдущий, следующий), чтобы получить из БД данные о своих доходах и расходах. Почему-то при переключении дня данные в списке не обновляются (т.е. я переключаю день, а в списке старые данные). Если в методе showList каждый пересоздавать адаптер, то все нормально, но это ведь не лучший способ. Подскажите, в чем может быть проблема

Вот Dao:

@Dao
public interface ItemsByCategoryDao {

    @Query("select c.*, sum(i.summ) as summa, i.datetime as timestamp " +
            "from category c " +
            "left outer join item i on c.id = i.categoryid " +
            "where i.type = :type and date(i.datetime, 'unixepoch') BETWEEN date(:dat1, 'unixepoch') AND date(:dat2, 'unixepoch') " +
            "group by c.id " +
            "order by summa desc")
    PagingSource<Integer, ItemsByCategory> getItemsForCategoryForPeriod(long dat1, long dat2, int type);
}

Вот код ViewModel:

public class ItemsByCategoryViewModel extends AndroidViewModel {
    private final ItemsByCategoryDao itemsByCategoryDao;

    public ItemsByCategoryViewModel(@NonNull Application application) {
        super(application);
        AppDatabase db = AppDatabase.getInstance(application);
        itemsByCategoryDao = db.itemsByCategoryDao();
    }

    public Flowable<PagingData<ItemsByCategory>> getItemsForCategoryForPeriod(long dat1, long dat2, int type) {
        Pager<Integer, ItemsByCategory> pager = new Pager<>(new PagingConfig(20, 15, true),
                () -> itemsByCategoryDao.getItemsForCategoryForPeriod(dat1, dat2, type));
        return PagingRx.getFlowable(pager);
    }
}

Код адаптера:

public class ItemsByCategoryAdapter extends PagingDataAdapter<ItemsByCategory, ItemsByCategoryAdapter.ItemsByCategoryViewHolder> {

    private Context context;

    private OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(int id);
    }

    public void setOnItemClickListener(final ItemsByCategoryAdapter.OnItemClickListener mItemClickListener) {
        this.mItemClickListener = mItemClickListener;
    }

    public ItemsByCategoryAdapter(Context context) {
        super(DIFF_CALLBACK);
        this.context = context;
    }

    public ItemsByCategory getItemsByCategoryItem(int position) {
        return getItem(position);
    }

    public class ItemsByCategoryViewHolder extends ViewHolder implements OnClickListener {
        private TextView txtText;
        private TextView txtSumm;

        public ItemsByCategoryViewHolder(@NonNull View itemView) {
            super(itemView);
            txtText = itemView.findViewById(R.id.txtText);
            txtSumm = itemView.findViewById(R.id.txtSumm);
            itemView.setOnClickListener(this);
        }

        public void bind(ItemsByCategory itemsByCategory) {
            txtText.setText(itemsByCategory.getText());
            txtSumm.setText(String.valueOf(itemsByCategory.getSumma()));
        }

        @Override
        public void onClick(View v) {
            int position = getBindingAdapterPosition();
            if (position != RecyclerView.NO_POSITION) {
                ItemsByCategory itemsByCategory = getItem(position);
                if (itemsByCategory != null && mItemClickListener != null) {
                    mItemClickListener.onItemClick(itemsByCategory.getId());
                }
            }
        }
    }

    @NonNull
    @Override
    public ItemsByCategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_items_by_category, parent, false);
        return new ItemsByCategoryViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ItemsByCategoryViewHolder holder, int position) {
        ItemsByCategory itemsByCategory = getItem(position);
        if (itemsByCategory != null) {
            Log.d("ItemsByCategoryAdapter", "Binding category at position: " + position +
                    " with name: " + itemsByCategory.getText() + ", sum: " + itemsByCategory.getSumma() +
                    ", timestamp: " + itemsByCategory.getTimestamp());
            holder.bind(itemsByCategory);
        } else {
            Log.d("ItemsByCategoryAdapter", "Binding null category at position: " + position);
        }
    }
}

Код активити:

public class ShowItemsByCategoryActivity extends AppCompatActivity implements ItemsByCategoryAdapter.OnItemClickListener, AdapterView.OnItemSelectedListener {

    private ActivityShowItemsByCategoryBinding binding;

    private RecyclerView rvList;
    private ItemsByCategoryAdapter itemsByCategoryAdapter;
    private ItemsByCategoryViewModel itemsByCategoryViewModel;
    private ItemViewModel itemViewModel;

    private Calendar calendar = Calendar.getInstance(Locale.getDefault());
    private Calendar calendar2 = Calendar.getInstance(Locale.getDefault());

    private ImageButton btnPrev;
    private ImageButton btnNext;
    private TextView txtPeriod1;
    private TextView txtPeriod2;
    private TextView txtAllSum;
    private LinearLayout btnsLayout;

    private long mills1;
    private long mills2;
    private int type = 0;
    private int spinnerPosition = 0;

    private ArrayList<ItemsByCategory> exportList = new ArrayList<>();

    private CompositeDisposable disposables = new CompositeDisposable();

    private double sum = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityShowItemsByCategoryBinding.inflate(getLayoutInflater());
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        setContentView(binding.getRoot());

        rvList = binding.rvList;
        btnPrev = binding.btnPrev;
        btnNext = binding.btnNext;
        txtPeriod1 = binding.txtPeriod1;
        txtPeriod2 = binding.txtPeriod2;
        txtAllSum = binding.txtAllSum;
        btnsLayout = binding.btnsLayout;

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        rvList.setLayoutManager(layoutManager);
        itemsByCategoryAdapter = new ItemsByCategoryAdapter(this);
        rvList.setAdapter(itemsByCategoryAdapter);

        try {
            Bundle bundle = getIntent().getExtras();
            assert bundle != null;
            type = bundle.getInt("type", 0);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (type == 0) {
            setTitle(getResources().getString(R.string.costs));
        } else if (type == 1) {
            setTitle(getResources().getString(R.string.income));
        }

        itemsByCategoryViewModel = new ViewModelProvider(this).get(ItemsByCategoryViewModel.class);
        itemViewModel = new ViewModelProvider(this).get(ItemViewModel.class);
    }

    //Получение текущего дня
    private void setDayCurrent() {
        calendar.setTimeZone(TimeZone.getDefault()); 
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0); 
        calendar.set(Calendar.MILLISECOND, 0);
        Date date = calendar.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM YYYY", Locale.getDefault());
        txtPeriod1.setText(simpleDateFormat.format(date));
        mills1 = calendar.getTimeInMillis()/1000L;
        mills2 = calendar.getTimeInMillis()/1000L;

        showList();
    }

    //Получение следующего дня
    private void setDayNext() {
        calendar.setTimeZone(TimeZone.getDefault());
        calendar.add(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date date = calendar.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM YYYY", Locale.getDefault());
        //Выводми дату в TextView
        txtPeriod1.setText(simpleDateFormat.format(date));
        mills1 = calendar.getTimeInMillis()/1000L;
        mills2 = calendar.getTimeInMillis()/1000L;

        showList();
    }

    //Получение предыдущего дня
    private void setDayPrev() {
        calendar.setTimeZone(TimeZone.getDefault());
        calendar.add(Calendar.DATE, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date date = calendar.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM YYYY", Locale.getDefault());
        txtPeriod1.setText(simpleDateFormat.format(date));
        mills1 = calendar.getTimeInMillis()/1000L;
        mills2 = calendar.getTimeInMillis()/1000L;

        showList();
    }

    DatePickerDialog.OnDateSetListener selectDay = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            setDayCurrent();
        }
    };

    private void showList() {
        FilterClassForItemsForCategoty t = new FilterClassForItemsForCategoty(mills1, mills2, type); //Создаем фильтр

        disposables.clear();

        Disposable disposable = itemsByCategoryViewModel.getItemsForCategoryForPeriod(t.getDat1(), t.getDat2(), t.getType())
                .subscribe(pagingData -> {
                    itemsByCategoryAdapter.submitData(getLifecycle(), pagingData);
                    itemsByCategoryAdapter.refresh();
                    itemsByCategoryAdapter.getItemCount();
                    setAllSumInTextView();
                }, throwable -> {
                    
                });

        disposables.add(disposable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposables.clear();
    }

    @Override
    protected void onResume() {
        super.onResume();
        showList();
    }

    private void setAllSumInTextView() {
        itemViewModel.getSumItemsForPeriod(mills1, mills2, type)
                .subscribe(new SingleObserver<Double>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onSuccess(Double result) {
                        sum = result;
                        txtAllSum.setText(String.valueOf(sum));
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.show_items_by_category_activity_menu, menu);

        MenuItem item = menu.findItem(R.id.action_spinner);
        Spinner spinner = (Spinner) item.getActionView();

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdowm, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        assert spinner != null;
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);
        return true;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        spinnerPosition = position;

        switch (position) {
            case 0: //День
                btnsLayout.setVisibility(View.VISIBLE);
                btnNext.setVisibility(View.VISIBLE);
                btnPrev.setVisibility(View.VISIBLE);
                txtPeriod2.setVisibility(View.GONE);
                calendar = Calendar.getInstance();

                setDayCurrent(); //Получение текущего дня

                btnNext.setOnClickListener(v -> {
                    setDayNext(); //Получение следующего дня
                });

                btnPrev.setOnClickListener(v -> {
                    setDayPrev(); //Получение предыдущего дня
                });

                txtPeriod1.setOnClickListener(v -> {
                    new DatePickerDialog(this, selectDay,
                            calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH),
                            calendar.get(Calendar.DAY_OF_MONTH))
                            .show();
                });

                break;
            default:
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onItemClick(int id) {
        Toast.makeText(this, "" + id, Toast.LENGTH_SHORT).show();
    }
}

Ответы (0 шт):