У меня есть API для поиска продуктов с разбивкой на страницы и список продуктов с разбивкой на страницы. Как реализовать функцию поиска? - PullRequest
0 голосов
/ 27 мая 2020

Ниже мой ProductListAdapter:

    public class ProductListAdapter extends PagedListAdapter<Products, ProductListAdapter.ProductViewHolder> {

        private static final String TAG = "ProductListAdapter";

        // Class member variables for adapter
        private Context mContext;

        private List<Integer> mProductIdList = new ArrayList<>();

        // An instance of bottomSheetBehaviour
        private BottomSheetBehavior mBottomSheetBehavior;

        private int mCompanyId;
        private String mToken;
        private HashMap<String, String> mHeader;

        private View mParentView;

        private ProgressDialog mProgressDialog;

        public ProductListAdapter(Context context) {
            super(DIFF_CALLBACK);
            mContext = context;
            mParentView = ((Activity)mContext).getWindow().getDecorView().getRootView();
        }

        @NonNull
        @Override
        public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(mContext).inflate(R.layout.product_item, parent,false);
            mHeader = new HashMap<>();
            mCompanyId = SharedPrefManager.getInstance(mContext).getUserCompanyId();
            mToken = SharedPrefManager.getInstance(mContext).getUserToken();
            mHeader.put(mContext.getString(R.string.key_authorization), " Bearer "+ mToken);
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setTitle(null);
            mProgressDialog.setMessage(mContext.getString(R.string.text_please_wait));
            mProgressDialog.setCanceledOnTouchOutside(false);
            return new ProductViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull final ProductViewHolder holder, int position) {

            final Products mProduct = getItem(position);

            if(mProduct != null){
                // setting data from db to views
                holder.mBatchNumber.setText("#" + mProduct.getBatch_number());
                holder.mProductName.setText(mProduct.getProduct_name());
                holder.mProductPrice.setText("Price: " + mProduct.getUnit_selling_price());
                holder.mProductQty.setText("Quantity: " + mProduct.getQuantity_available() +"/"+ mProduct.getReference_quantity());
                holder.mProductStatus.setText(mProduct.getProduct_availability().toLowerCase());
                holder.mCategory.setText(mProduct.getCategory());

            }

        }

        private static DiffUtil.ItemCallback<Products> DIFF_CALLBACK =
                new DiffUtil.ItemCallback<Products>() {
                    @Override
                    public boolean areItemsTheSame(@NonNull Products oldItem, @NonNull Products newItem) {
                        return oldItem.getProduct_id() == newItem.getProduct_id();
                    }

                    @Override
                    public boolean areContentsTheSame(@NonNull Products oldItem, @NonNull Products newItem) {
                        return oldItem.equals(newItem);
                    }
                };
        }

    public class ProductViewHolder extends RecyclerView.ViewHolder{


        private AppCompatTextView mBatchNumber,mProductName,mProductQty,mProductPrice,mProductStatus,
                mCategory;

        private ImageButton mMenuButton;

        private ProgressBar mProgressBar;

        public ProductViewHolder(@NonNull View itemView) {
            super(itemView);
            // getting reference to views
            mBatchNumber = itemView.findViewById(R.id.mBatchNumber);
            mProductName = itemView.findViewById(R.id.mProductName);
            mProductPrice = itemView.findViewById(R.id.mProductPrice);
            mProductQty = itemView.findViewById(R.id.mProductQty);
            mProductStatus = itemView.findViewById(R.id.mProductStatus);
            mCategory = itemView.findViewById(R.id.mCategory);
            mMenuButton = itemView.findViewById(R.id.mMenuButton);
            mProgressBar = itemView.findViewById(R.id.mProgressBar);
        }
    }

Это мой ProductDataSource класс:

    public class ProductDataSource extends PageKeyedDataSource<Integer, Products> {

        private static final String TAG = ProductDataSource.class.getSimpleName();

        private Context mContext;
        private static final int FIRST_PAGE = 1;
        public static int PAGE_SIZE = 20;
        private int mCompanyId;
        private String mToken;
        private HashMap<String, String> mHeader;

        private SwipeRefreshLayout mSwipeRefreshLayout;

        private MutableLiveData networkState;
        private MutableLiveData initialLoading;

        public ProductDataSource(Context context, SwipeRefreshLayout swipeRefreshLayout) {
            mContext = context;
            mSwipeRefreshLayout = swipeRefreshLayout;
            mHeader = new HashMap<>();
            mCompanyId = SharedPrefManager.getInstance(mContext).getUserCompanyId();
            mToken = SharedPrefManager.getInstance(mContext).getUserToken();
            mHeader.put(mContext.getString(R.string.key_authorization), " Bearer "+ mToken);

            networkState = new MutableLiveData();
            initialLoading = new MutableLiveData();
        }

        public MutableLiveData getNetworkState() {
            return networkState;
        }

        public MutableLiveData getInitialLoading() {
            return initialLoading;
        }

        @Override
        public void loadInitial(@NonNull final LoadInitialParams<Integer> params, @NonNull final LoadInitialCallback<Integer, Products> callback) {

            mSwipeRefreshLayout.setRefreshing(true);

            // making http call
            RetrofitClient.getInstance()
                    .getApi()
                    .getPaginatedProductsList(mHeader, mCompanyId, FIRST_PAGE)
                    .enqueue(new Callback<ProductListResponse>() {
                @Override
                public void onResponse(Call<ProductListResponse> call, Response<ProductListResponse> response) {
                    if(response.body() != null){
                        // load next page
                        callback.onResult(response.body().getProducts(),null,FIRST_PAGE + 1);
                        Log.d(TAG, "LoadInitial Key: " + FIRST_PAGE);
                    }
                    mSwipeRefreshLayout.setRefreshing(false);
                }

                @Override
                public void onFailure(Call<ProductListResponse> call, Throwable t) {
                    Log.d(TAG, "Error: "+ t.getMessage());
                }
            });

        }

        @Override
        public void loadBefore(@NonNull final LoadParams<Integer> params, @NonNull final LoadCallback<Integer, Products> callback) {

            mSwipeRefreshLayout.setRefreshing(true);
            Log.d(TAG, "loadBefore refresh layout started...");

            // making http call
            RetrofitClient.getInstance()
                    .getApi()
                    .getPaginatedProductsList(mHeader, mCompanyId, params.key)
                    .enqueue(new Callback<ProductListResponse>() {
                        @Override
                        public void onResponse(Call<ProductListResponse> call, Response<ProductListResponse> response) {
                            if(response.body() != null){
                                // get previous page key
                                Integer key = (params.key > 1) ? params.key - 1 : null;
                                // load previous page
                                callback.onResult(response.body().getProducts(), key);
                                Log.d(TAG, "LoadBefore Key: " + key);
                            }
                            mSwipeRefreshLayout.setRefreshing(false);
                            Log.d(TAG, "loadBefore refresh layout stopped...");
                        }

                        @Override
                        public void onFailure(Call<ProductListResponse> call, Throwable t) {
                            Log.d(TAG, "Error: "+ t.getMessage());
                        }
                    });
        }

        @Override
        public void loadAfter(@NonNull final LoadParams<Integer> params, @NonNull final LoadCallback<Integer, Products> callback) {

            // making http call
            RetrofitClient.getInstance()
                    .getApi()
                    .getPaginatedProductsList(mHeader, mCompanyId, params.key)
                    .enqueue(new Callback<ProductListResponse>() {
                        @Override
                        public void onResponse(Call<ProductListResponse> call, Response<ProductListResponse> response) {
                            if(response.body() != null){
                                // if has_more_page is true then increment the key else null
                                Integer key = response.body().isHas_more_pages() ? params.key + 1 : null;
                                // load next page if there are any
                                callback.onResult(response.body().getProducts(), key);
                                Log.d(TAG, "LoadAfter Key: " + key);
                            }
                        }

                        @Override
                        public void onFailure(Call<ProductListResponse> call, Throwable t) {
                            Log.d(TAG, "Error: "+ t.getMessage());
                        }
                    });
        }
    }

Мой ProductDataSourceFactory класс:

    public class ProductDataSourceFactory extends DataSource.Factory {

        //private MutableLiveData<PageKeyedDataSource<Integer, Products>> mProductLiveDataSource = new MutableLiveData<>();
        private MutableLiveData<ProductDataSource> mProductLiveDataSource = new MutableLiveData<>();

        private Context mContext;

        ProductDataSource mProductDataSource;

        private SwipeRefreshLayout mSwipeRefreshLayout;

        public ProductDataSourceFactory(Context context, SwipeRefreshLayout swipeRefreshLayout) {
            mContext = context;
            mSwipeRefreshLayout = swipeRefreshLayout;
        }

        @NonNull
        @Override
        public DataSource create() {
            mProductDataSource = new ProductDataSource(mContext, mSwipeRefreshLayout);
            mProductLiveDataSource.postValue(mProductDataSource);
            return mProductDataSource;
        }

        public MutableLiveData<ProductDataSource> getProductLiveDataSource() {
            return mProductLiveDataSource;
        }
    }

Ниже мой ProductViewModel класс:

    public class ProductViewModel extends ViewModel{

        public LiveData<PagedList<Products>> productPagedList;
        //LiveData<PageKeyedDataSource<Integer, Products>> liveDataSource;
        LiveData<ProductDataSource> liveDataSource;
        public static final int PAGE_SIZE = 20;
        private ProductDataSourceFactory mProductDataSourceFactory;


        private Context mContext;
        private SwipeRefreshLayout mSwipeRefreshLayout;

        ProductDao mProductDao;

        public ProductViewModel() {}

        public void initData(Context mContext, SwipeRefreshLayout swipeRefreshLayout){
            this.mContext = mContext;
            this.mSwipeRefreshLayout = swipeRefreshLayout;
            mProductDataSourceFactory = new ProductDataSourceFactory(mContext, mSwipeRefreshLayout);
            liveDataSource = mProductDataSourceFactory.getProductLiveDataSource();
            PagedList.Config mConfig =
                    (new PagedList.Config.Builder())
                            .setEnablePlaceholders(false)
                            .setPrefetchDistance(5)
                            .setPageSize(ProductDataSource.PAGE_SIZE)
                            .build();
            productPagedList = (new LivePagedListBuilder(mProductDataSourceFactory, mConfig))

                                .build();
        }


        public void refresh() {
            mProductDataSourceFactory.getProductLiveDataSource().getValue().invalidate();
        }

    }

И, наконец, мой ProductListActivity:


    public class ProductListActivity extends AppCompatActivity implements View.OnClickListener{

        private static final String TAG = "ProductListActivity";

        ConnectivityReceiver mReceiver = new ConnectivityReceiver();

        private ActivityProductListBinding bi;

        private Toolbar mToolbar;

        private AppCompatTextView mToolbarTitle;

        private List<Products> mProductsList;

        private MaterialSearchView mSearchView;

        private ProductListAdapter mProductListAdapter;

        // An instance of bottomSheetBehaviour
        private BottomSheetBehavior mSheetBehavior;

        private static int mCompanyId;

        private static HashMap<String, String> mHeader;

        private static String mToken;

        ProductViewModel mProductViewModel;

        private boolean isRefresh = false;

        private CustomSpinnerAdapter mSpinnerAdapter;

        private List<Product_categories> mCategoriesList;

        private ProgressDialog mProgressDialog;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            bi = ActivityProductListBinding.inflate(getLayoutInflater());

            setContentView(bi.getRoot());

            initViews();
        }

        //*** initializing views
        private void initViews() {

            // setting up toolbar
            mToolbar = findViewById(R.id.mToolbar);
            mToolbar.setTitle("");
            mToolbarTitle = findViewById(R.id.mToolbarTitle);
            mToolbarTitle.setText(getString(R.string.title_product_list));
            setSupportActionBar(mToolbar);
            mToolbar.setNavigationIcon(R.drawable.ic_back_white);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    navigateBack();
                }
            });

            mProductsList = new ArrayList<>();

            mCategoriesList = new ArrayList<>();

            // attaching on click listener
            bi.mAddButton.setOnClickListener(this);

            // setting up recycler view
            bi.mRecyclerView.setHasFixedSize(true);
            bi.mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            bi.mRecyclerView.setItemAnimator(new SlideInUpAnimator());

            mProductViewModel = new ViewModelProvider(this).get(ProductViewModel.class);
            //mProductViewModel.initData(this, bi.mRefreshLayout, mProductDatabase.productDao());
            mProductViewModel.initData(this, bi.mRefreshLayout);
            final ProductListAdapter mAdapter = new ProductListAdapter(this);
            mProductViewModel.productPagedList.observe(this, new Observer<PagedList<Products>>() {
                @Override
                public void onChanged(PagedList<Products> product) {
                    //refresh current list
                    mAdapter.submitList(product);
                }
            });
            // setting recycler adapter to recycler view
            bi.mRecyclerView.setAdapter(mAdapter);

            // setting color scheme loading layout
            bi.mRefreshLayout.setColorSchemeResources(
                    R.color.colorPrimary, R.color.niceDark,
                    R.color.dark_yellow, R.color.colorAccent
            );

            // adding refresh listener
            bi.mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    // refresh adapter
                    mProductViewModel.refresh();
                    bi.mRefreshLayout.setRefreshing(false);

                }
            });

            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setTitle(null);
            mProgressDialog.setMessage(getString(R.string.text_please_wait));
            mProgressDialog.setCanceledOnTouchOutside(false);

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            MenuInflater mInflater = getMenuInflater();
            mInflater.inflate(R.menu.menu_filter,menu);
            // find menu item
            MenuItem mItem = menu.findItem(R.id.menu_search);

            // Preparing search view
            mSearchView = findViewById(R.id.mSearchView);
            mSearchView.setMenuItem(mItem);
            mSearchView.setHint(getString(R.string.text_search_product));
            mSearchView.setHintTextColor(getResources().getColor(R.color.colorDarkGray));
            mSearchView.setBackIcon(getResources().getDrawable(R.drawable.ic_back_green));
            mSearchView.setEllipsize(true);
            mSearchView.setSubmitOnClick(true);

            // Query listener to help in searching
            mSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    // implement search here
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                     // implement search here
                    return true;
                }
            });

            return true;
        }
    }
...