Searchview with Recyclerview in Android using Volley per pagin How to add search filters to the last page in a recycler view that consumes ten page?

I am doing a search filter by identity document in a Recyclerview that is per page, the problem is that at the time of making the filter it only looks for the first diez that is the current page. How would I filter the search from the current page until last page?

RecyclerActasAdapter.java

  @Override
    public int getItemCount() {
        return this.itemsMostrados.size();
    }

    public void filtrar(String query) {
        this.itemsMostrados = new ArrayList<>();

        if (query.length() == 0) {
            itemsMostrados = listaActas;
            layoutResultados.setVisibility(View.GONE);
        } else {
            ActasActivity actas= new ActasActivity();
            for (Datum data: listaActas) {
                if (data.getBeneficiario().getNumDocumento().contains(query)
                    //|| (data.getBeneficiario().getNombre().toLowerCase() + " " + data.getBeneficiario().getApellido().toLowerCase()).contains(text.toLowerCase())
                    || (data.getBeneficiario() != null ? data.getBeneficiario().getNombre() : "No registra" + " " + data.getBeneficiario() != null ? data.getBeneficiario().getApellido() : "No registra").contains(query)
                    //|| data.getPoblacion().getNombre().toLowerCase().contains(text.toLowerCase())
                    //|| data.getMunicipio().getMunicipio().toLowerCase().contains(text.toLowerCase())
                    ) {
                    itemsMostrados.add(data);

                }
            }

            layoutResultados.setVisibility(View.VISIBLE);
            txtResults.setText(itemsMostrados.size() + "");

        }

        notifyDataSetChanged();
    }

    public void actualizar() {
        itemsMostrados = listaActas;
        notifyDataSetChanged();
    }


ActasActivity.java

In this activity I try to create the condition to filter search to the last page but still continue to filter only the first 10 of the current page

  public void obtenerActas(boolean inicializar) {

        if (inicializar) {
            current_page = 1;
            last_page = 1;
            last_size_pages = 0;
        }

        final Promise<RespuestaActasDTO, BusinessException, RespuestaActasDTO> mPromise = actasService.obtenerActas(current_page);
        mPromise.done(result -> {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            actualizarListadoActas(result, inicializar);

            if (progressBar.getVisibility() == View.VISIBLE) {
                progressBar.setVisibility(View.GONE);
            }

        });
        mPromise.fail(error -> {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            if (progressBar.getVisibility() == View.VISIBLE) {
                progressBar.setVisibility(View.GONE);
            }

            Toast.makeText(mContexto, "Ocurrió un error consultando las actas", Toast.LENGTH_SHORT).show();
        });
    }

    public void actualizarListadoActas(RespuestaActasDTO respuestaActasDTO, boolean inicializar) {

        // logica para controlar la pagina a consumir y saber cual es la ultima pagina
        last_page = respuestaActasDTO.getLastPage();

        //SI PAGINA ACTUAL ES MENOR QUE ULTIMA PAGINA
        if (current_page < last_page) {
            current_page++;//ENUMEREME DESDE LA PAGINA ACTUAL

        }

        if (actasAdapter == null || inicializar) {
            listaActas = new ArrayList<>();
            listaActas = respuestaActasDTO.getData();

            actasAdapter = new RecyclerActasAdapter(mContexto, listaActas, layoutResultados, txtResults);
            recyclerViewActas.setAdapter(actasAdapter);
            scrollListener.resetState();
        } else {
            //página actual <   última página
            if (current_page < last_page) {
                listaActas.addAll(respuestaActasDTO.getData());
                actasAdapter.actualizar();

                agregarUltimaConsulta = true;
            } else if (current_page == last_page) {
                if (agregarUltimaConsulta) {
                    agregarUltimaConsulta = false;
                    last_size_pages = respuestaActasDTO.getData().size();
                    ultimaLista = respuestaActasDTO.getData();

                    listaActas.addAll(ultimaLista);
                    actasAdapter.actualizar();
                } else if (last_size_pages != respuestaActasDTO.getData().size()) {
                    // limpiar ultimos registros para volverlos a agregar

                    ultimaLista = respuestaActasDTO.getData();
                    last_size_pages = respuestaActasDTO.getData().size();

                    listaActas.addAll(ultimaLista);
                    actasAdapter.actualizar();
                }
            }
        }
        // Logical END to control the page to consume and know which is the last page ------>>>>


        if (agregarEventoBuscar) {
            agregarEventoBuscar = false;
            // buscador
            inputBuscar.setOnQueryTextListener( new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    actasAdapter.filtrar(inputBuscar.getQuery().toString() );
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            } );

        }


Observation: I only filter the query if I scroll to the last page, Thanks for your support

android – I am not deleting the item from my RecyclerView

I have a RecyclerView that returns an ArrayList to me. The problem is that the item that I select using the "Delete" button is not deleted. No mistake is thrown at me. I am only removed from the service, but it is not deleted.

Thanks in advance for your help.

This is my adapter on which I am going to do the element removal method

 public ViewHolderCarrito onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_carro_compras,null,false);

                eliminar_servicio = (ImageView) view.findViewById(R.id.delete_server);
                eliminar_servicio.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View view) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                        builder.setMessage("Está seguro que desea eliminar el servicio ?");
                        builder.setTitle("Te Informa: ");
                        builder.setIcon(R.drawable.iconrasel);
                        builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                onLongClick(view); //Método delete item
                                Toast t=Toast.makeText(view.getContext(),"El Servicio ha sido eliminado...", Toast.LENGTH_SHORT);
                                t.show();
                            }
                        });
                        builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });

                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                });



                return (new ViewHolderCarrito(view));
            }

    @Override
    public boolean onLongClick(View view) {
        final  ViewHolderCarrito holderCarrito = new ViewHolderCarrito(view);
        int position = holderCarrito.getAdapterPosition();
        if(position!=-1) {

            carroCompra.remove(position);
            notifyItemRangeChanged(position, carroCompra.size());
            notifyItemRemoved(position);
            holderCarrito.itemView.setVisibility(View.GONE);

        }
        return true;
    }


    @Override
    public void onBindViewHolder(@NonNull ViewHolderCarrito holder, int position) {
        holder.nombre_servicio.setText(carroCompra.get(position).getNombre_servicio());
        holder.precio_servicio.setText(""+carroCompra.get(position).getPrecio_servicio());
        holder.imagen_servicio.setImageResource(carroCompra.get(position).getImagen_servicio());

Note: The recycler's ArrayList was created with sharedPreferences

android – Click Enter in Recyclerview

I have stuck to a code, at the moment it works fine when I use my fingers on the phone, but I do it for TV compatibility reasons and can therefore use the buttons on the remote control to operate it, but I cannot use the button select an action in the recycler view, I hope you can help me, thank you

RecyclerTouchListener.class

public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

private GestureDetector gestureDetector;
private ClickListener clickListener;

public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
    this.clickListener = clickListener;
    gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null) {
                clickListener.onLongClick(child, recyclerView.getChildPosition(child));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

    View child = rv.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
        clickListener.onClick(child, rv.getChildPosition(child));
    }
    return false;
}

@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {

}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}

public interface ClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
}

}

CategoryFragment.class

public class CategoryFragment extends Fragment {

ArrayList mListItem;
public RecyclerView recyclerView;
CategoryAdapter adapter;
private ProgressBar progressBar;
private LinearLayout lyt_not_found;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.row_recyclerview, container, false);
    mListItem = new ArrayList<>();
    TextView txt_refencia = rootView.findViewById(R.id.tv_reference_ChanCat);
    int grillacant = 2;
    if(txt_refencia.isEnabled()){
        grillacant = 5;
    }
    lyt_not_found = rootView.findViewById(R.id.lyt_not_found);
    progressBar = rootView.findViewById(R.id.progressBar);
    recyclerView = rootView.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), grillacant));
    ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(requireActivity(), R.dimen.item_offset);
    recyclerView.addItemDecoration(itemDecoration);
    if (NetworkUtils.isConnected(getActivity())) {
        getCategory();
    } else {
        Toast.makeText(getActivity(), getString(R.string.conne_msg1), Toast.LENGTH_SHORT).show();
    }

    recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
        @Override
        public void onClick(View view, int position) {
            String categoryName = mListItem.get(position).getCategoryName();
            Bundle bundle = new Bundle();
            bundle.putString("name", categoryName);
            bundle.putString("Id", mListItem.get(position).getCategoryId());

            FragmentManager fm = getFragmentManager();
            CategoryItemFragment categoryItemFragment = new CategoryItemFragment();
            categoryItemFragment.setArguments(bundle);
            assert fm != null;
            FragmentTransaction ft = fm.beginTransaction();
            ft.hide(CategoryFragment.this);
            ft.add(R.id.Container, categoryItemFragment, categoryName);
            ft.addToBackStack(categoryName);
            ft.commit();
            ((MainActivity) requireActivity()).setToolbarTitle(categoryName);
        }

        @Override
        public void onLongClick(View view, int position) {

        }
    }));
    return rootView;
}

private void getCategory() {
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(Constant.CATEGORY_URL, new AsyncHttpResponseHandler() {

        @Override
        public void onStart() {
            super.onStart();
            showProgress(true);
        }

        @Override
        public void onSuccess(int statusCode, Header() headers, byte() responseBody) {
            showProgress(false);
            String result = new String(responseBody);
            try {
                JSONObject mainJson = new JSONObject(result);
                JSONArray jsonArray = mainJson.getJSONArray(Constant.ARRAY_NAME);
                JSONObject objJson;
                for (int i = 0; i < jsonArray.length(); i++) {
                    objJson = jsonArray.getJSONObject(i);
                    ItemCategory objItem = new ItemCategory();
                    objItem.setCategoryId(objJson.getString(Constant.CATEGORY_CID));
                    objItem.setCategoryName(objJson.getString(Constant.CATEGORY_NAME));
                    objItem.setCategoryImage(objJson.getString(Constant.CATEGORY_IMAGE));
                    mListItem.add(objItem);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            displayData();
        }

        @Override
        public void onFailure(int statusCode, Header() headers, byte() responseBody, Throwable error) {
            showProgress(false);
            lyt_not_found.setVisibility(View.VISIBLE);
        }

    });
}

private void displayData() {
    adapter = new CategoryAdapter(getActivity(), mListItem, R.layout.row_category_item);
    recyclerView.setAdapter(adapter);
    if (adapter.getItemCount() == 0) {
        lyt_not_found.setVisibility(View.VISIBLE);
    } else {
        lyt_not_found.setVisibility(View.GONE);
    }
    //#animacion en focus
    if(!getActivity().getResources().getBoolean(R.bool.portrait_only)) {
        recyclerView.requestFocusFromTouch();
    }
}


private void showProgress(boolean show) {
    if (show) {
        progressBar.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
        lyt_not_found.setVisibility(View.GONE);
    } else {
        progressBar.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
    }
}

}

The part that invokes the click is this and the one that I want to adjust, so I remember that it works well with your fingers but not with the controls when you press the navigation key to run the fragment.

recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener()

Applications – Recyclerview Search Filter does not work Android

My title comes from retrofit; if I enter something in the search view, no results / suggestions are displayed when I enter it. here is the ss —> enter picture description here

I refer to this blog -> https://velmm.com/android-recyclerview-search-filter-example/

Help is appreciated … Thanks in advance

Search activity:

public class Search extends AppCompatActivity {
 SearchView searchView;
 RecyclerView recyclerView;
SearchAdapter slAdapter;
 List movieList;

@Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
searchView=findViewById(R.id.searchView);
if (getSupportActionBar() != null) {
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
}
searchView.onActionViewExpanded();
searchView.setIconified(true);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
slAdapter = new SearchAdapter();
recyclerView.setAdapter(slAdapter);

movieList = new ArrayList<>();

SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
retrofit2.Call> call = service.getMySlmodel();

call.enqueue(new Callback>() {
    @Override
    public void onResponse(retrofit2.Call> call, Response> response) {
        movieList = response.body();
        Log.d("TAG","Response = "+movieList);
        slAdapter.setMovieList(getApplicationContext(),movieList);

    }

    @Override
    public void onFailure(retrofit2.Call> call, Throwable t) {
        Log.d("TAG","Response = "+t.toString());



    }
});}

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

SearchManager searchManager = (SearchManager)   getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
        .getActionView();
searchView.setSearchableInfo(searchManager
        .getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
     @Override
    public boolean onQueryTextSubmit(String query) {
        slAdapter.getFilter().filter(query);
        return false;
    }

    @Override
    public boolean onQueryTextChange(String query) {
        slAdapter.getFilter().filter(query);
        return false;
    }
});
return true;}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() ==android.R.id.home) {
    finish();
}
   return super.onOptionsItemSelected(item);}

   @Override
   public void onBackPressed() {
  super.onBackPressed();}}

Search adapter

public class SearchAdapter extends RecyclerView.Adapter implements Filterable {

List Slmdel;
 List Slmdel1;

 Context context;

 public SearchAdapter() {
}

  public void setMovieList(Context context, final List movieList){
this.context = context;
if(this.Slmdel == null){
    this.Slmdel = movieList;
    this.Slmdel1 = movieList;
    notifyItemChanged(0, Slmdel1.size());
} else {
    final DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
        @Override
        public int getOldListSize() {
            return SearchAdapter.this.Slmdel.size();
        }

        @Override
        public int getNewListSize() {
            return movieList.size();
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return SearchAdapter.this.Slmdel.get(oldItemPosition).getTitle() == movieList.get(newItemPosition).getTitle();}

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {

            StartLearning.SlModel newMovie = SearchAdapter.this.Slmdel.get(oldItemPosition);

            StartLearning.SlModel oldMovie = movieList.get(newItemPosition);

            return newMovie.getTitle() == oldMovie.getTitle() ;}
    });
    this.Slmdel = movieList;
    this.Slmdel1 = movieList;
    result.dispatchUpdatesTo(this);
}}

     public SearchAdapter(Context context,List employees) {
this.Slmdel = employees;
this.context=context;}

   @Override
   public SearchAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.startlearning_item, parent, false);

return new SearchAdapter.CustomViewHolder(itemView);}

   @Override
    public void onBindViewHolder(SearchAdapter.CustomViewHolder holder, int position) {

holder.textView.setText(String.valueOf(position+1)+". ");
holder.employeeName.setText(Slmdel.get(position).getTitle());}

   @Override
  public int getItemCount() {
if(Slmdel != null){
    return Slmdel1.size();
} else {
    return 0;
}}
 @Override
 public Filter getFilter() {
return new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {
        String charString = charSequence.toString();
        if (charString.isEmpty()) {
            Slmdel1 = Slmdel;
        } else {
            List filteredList = new ArrayList<>();
            for (StartLearning.SlModel movie : Slmdel) {
                if (movie.getTitle().toLowerCase().contains(charString.toLowerCase())) {
                    filteredList.add(movie);
                }
            }
            Slmdel1 = filteredList;
        }

        FilterResults filterResults = new FilterResults();
        filterResults.values = Slmdel1;
        return filterResults;
    }

    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
        Slmdel1 = (ArrayList) filterResults.values;

        notifyDataSetChanged();
    }};}



 public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView employeeName;
TextView textView;

public CustomViewHolder(View view) {
    super(view);
    employeeName = (TextView) view.findViewById(R.id.Sl2);
    textView=view.findViewById(R.id.Sl1);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent =  new Intent(context, NextSLactivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("title", Slmdel.get(getAdapterPosition()).getTitle());
            intent.putExtra("idSLnext", Slmdel.get(getAdapterPosition()).getId());
            //Log.e("ashwini",WAmdel.get(getAdapterPosition()).getId());
            context.startActivity(intent);

        }
    });


}

}

Update java – RecyclerView

I have a problem with the recycling overview. I have a screen with two recycling guides, one with groups and one with products. The product is displayed after selecting a group and the groups are displayed on the screen. When clicking on the group, it does not display the products on the screen, I create a log to see if I have pulled the products and he does not just show up on the screen.
Below are the codes.

For sale

package com.example.gabriel.agilmobile;

import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridLayout;
import android.widget.LinearLayout;

import com.example.gabriel.agilmobiel.R;
import com.example.gabriel.agilmobile.Banco.BancoController;
import com.example.gabriel.agilmobile.RecyclerView.GrupoRecycler;
import com.example.gabriel.agilmobile.RecyclerView.ProdutoRecycler;

import java.util.ArrayList;

public class venda extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_venda);
        RecyclerView rv;
        RecyclerView.LayoutManager mRv;
        Cursor cursor = new BancoController(venda.this).consultaGrupo();
        cursor.moveToFirst();
        ArrayList grupos = new ArrayList<>();
        do {
            grupos.add(cursor.getString(2));

        }while (cursor.moveToNext());
        GrupoRecycler adapter = new GrupoRecycler(venda.this, grupos);
        rv = findViewById(R.id.recyclerGrupo);
        mRv = new GridLayoutManager(venda.this,1, GridLayout.HORIZONTAL, false);
        rv.setAdapter(adapter);
        rv.setLayoutManager(mRv);
    }
}

Recycler Group

package com.example.gabriel.agilmobile.RecyclerView;

import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gabriel.agilmobiel.R;
import com.example.gabriel.agilmobile.Banco.BancoController;
import com.example.gabriel.agilmobile.GlobalVariable;
import com.example.gabriel.agilmobile.funcoes;

import java.util.ArrayList;

public class GrupoRecycler extends RecyclerView.Adapter {
    private ArrayList nomeGrupo = new ArrayList<>();
    private Context context;
    public GrupoRecycler(Context context, ArrayList nomeGrupo) {
        this.context = context;
        this.nomeGrupo = nomeGrupo;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LinearLayout ll = (LinearLayout) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.grupo_recycle, viewGroup, false);
        GrupoRecycler.MyViewHolder myViewHolder = new GrupoRecycler.MyViewHolder(ll);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        myViewHolder.textView.setText(nomeGrupo.get(i));
        myViewHolder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new funcoes(context).produtosTela(new BancoController(context).consultaProdutosByGrupo(nomeGrupo.get(i)),context);
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return nomeGrupo.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        CardView cardView;
        TextView textView;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.cardGrupo);
            textView = itemView.findViewById(R.id.grupoText);
        }
    }
}

Features.ProductsScreen ()

public void produtosTela(Cursor cursor, Context context){
        RecyclerView rv;
        RecyclerView.LayoutManager mRv;
        cursor.moveToFirst();
        View view = LayoutInflater.from(context).inflate(R.layout.activity_venda,null, false);
        ArrayList produtos = new ArrayList<>();
        ArrayList preco = new ArrayList<>();
        do {
            Log.i("Produto", cursor.getString(4));
            produtos.add(cursor.getString(4));
            preco.add(cursor.getString(11));

        }while (cursor.moveToNext());

        ProdutoRecycler adapter = new ProdutoRecycler(context, produtos,preco);
        rv = view.findViewById(R.id.recyclerProduto);
        mRv = new GridLayoutManager(context,1, GridLayout.HORIZONTAL, false);
        rv.setAdapter(adapter);
        rv.setLayoutManager(mRv);
        adapter.notifyDataSetChanged();
    }

products recycler

package com.example.gabriel.agilmobile.RecyclerView;

import android.arch.lifecycle.ViewModel;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gabriel.agilmobiel.R;

import java.util.ArrayList;

public class ProdutoRecycler extends RecyclerView.Adapter {
    Context context;
    ArrayList nomeProdutos = new ArrayList<>();
    ArrayList precoProdutos = new ArrayList<>();

    public ProdutoRecycler(Context context, ArrayList nomeProdutos, ArrayList precoProdutos) {
        this.context = context;
        this.nomeProdutos = nomeProdutos;
        this.precoProdutos = precoProdutos;
    }

    @NonNull
    @Override
    public ProdutoRecycler.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LinearLayout ll = (LinearLayout) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.produto_recycle, viewGroup, false);
        ProdutoRecycler.MyViewHolder myViewHolder = new ProdutoRecycler.MyViewHolder(ll);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ProdutoRecycler.MyViewHolder myViewHolder, int i) {
        myViewHolder.nomeProduto.setText(nomeProdutos.get(i));
        myViewHolder.precoProduto.setText(precoProdutos.get(i));
        notifyItemInserted(i);
        myViewHolder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, nomeProdutos.get(i), Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return nomeProdutos.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        CardView cardView;
        TextView nomeProduto;
        TextView precoProduto;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.recyclerProduto);
            nomeProduto = itemView.findViewById(R.id.nomeProduto);
            precoProduto = itemView.findViewById(R.id.precoProduto);
        }
    }
}

kotlin – Retrieve data from the realm database and search and view in recyclerView

Attached to my data class, the data is not retrieved while filtering in the realm database performFiltering Method:

Worker.kt

package com.oyespace.guards.models

import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.RealmClass

@RealmClass
open class Worker:RealmObject(){
    @PrimaryKey
    var wkWorkID:Int = 0
    var wkfName:String = ""
    var wklName:String = ""
    var wkMobile:String = ""
    var wkEntryImg:String = ""
    var wkWrkType:String = ""
    var wkDesgn:String = ""
    var wkdob:String = ""
    var wkidCrdNo:String =""
    var vnVendorID:Long = 0
    var blBlockID:Long = 0
    var unUnitID:String = ""
    var asAssnID:Long = 0
    var wkIsActive:Boolean = false
    var unUniName:String = ""

}
data class GetWorkersResponse(
    val apiVersion: String,
    val `data`: WorkersList,
    val success: Boolean
)
data class WorkersList(
    val worker: RealmList
)

data class GetGuardsListResponse(
    val apiVersion: String,
    val `data`: GuardsList,
    val success: Boolean
)

data class GuardsList(
    val workers: RealmList
)


I want to fetch data from realm database and perform searching and view in recyclerview


 override fun performFiltering(charSequence: CharSequence?): FilterResults {



                    val filteredList = ArrayList()
                   // Toast.makeText(mcontext,items.get(0).wkfName,Toast.LENGTH_LONG).show()

                    for (row in items) {


                      //  Log.d("Inside for loop",row.wkfName)
                        // if (row.wkfName!!.toLowerCase().contains(charString.toLowerCase()) || row.age!!.contains(charSequence)) {
                        if (row.wkfName.toLowerCase().contains(charString.toLowerCase().trim())) {

                            filteredList.add(row)


                        }
                    }
                    searchList = filteredList
                }
                val filterResults = Filter.FilterResults()
                filterResults.values = searchList


                return filterResults
            }

            override fun publishResults(constraint: CharSequence?, results: FilterResults?) {


                searchList = results?.values as? ArrayList

                notifyDataSetChanged()
            }


        }

    }

Java – Use Stick Headers in Reversed RecyclerView in Chat Room

Excuse my English 🙂
I use recyclerview in my chatroom and with this code

layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);

make it down the top
Now I use stickHeader as an article decoration

recyclerView.addItemDecoration(new StickHeaderItemDecoration(_1_ChatRoom_Activity.this));

and

public class StickHeaderItemDecoration extends RecyclerView.ItemDecoration {

private StickyHeaderInterface mListener;
private int mStickyHeaderHeight;
private int layout;

public StickHeaderItemDecoration(@NonNull StickyHeaderInterface listener) {
    this.layout = R.layout.item_chat_date;
    this.mListener = listener;
}

@Override
public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
    super.onDrawOver(c, parent, state);
    View topChild = parent.getChildAt(0);
    if (topChild == null) return;

    int topChildPosition = parent.getChildAdapterPosition(topChild);
    if (topChildPosition == RecyclerView.NO_POSITION) {
        return;
    }

    int headerPos = mListener.getHeaderPositionForItem(topChildPosition);
    final View currentHeader = getHeaderViewForItem(headerPos, parent);

    fixLayoutSize(parent, currentHeader);
    int contactPoint = currentHeader.getBottom();
    View childInContact = getChildInContact(parent, contactPoint, headerPos);
    if (childInContact != null && mListener.isHeader(parent.getChildAdapterPosition(childInContact))) {
        moveHeader(c, currentHeader, childInContact);
        return;
    }

    drawHeader(c, currentHeader);
}

private View getHeaderViewForItem(int headerPosition, RecyclerView parent) {
    View header = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
    mListener.bindHeaderData(header, headerPosition);
    return header;
}

private void drawHeader(final Canvas c, final View header) {
    c.save();
    c.translate(0, 0);
    header.draw(c);
    c.restore();
}

private void moveHeader(final Canvas c, final View currentHeader, final View nextHeader) {
    c.save();
    c.translate(0, nextHeader.getTop() - currentHeader.getHeight());
    currentHeader.draw(c);
    c.restore();
}

private View getChildInContact(RecyclerView parent, int contactPoint, int currentHeaderPos) {
    View childInContact = null;
    for (int i = 0; i < parent.getChildCount(); i++) {
        int heightTolerance = 0;
        View child = parent.getChildAt(i);
        if (currentHeaderPos != i) {
            boolean isChildHeader = mListener.isHeader(parent.getChildAdapterPosition(child));
            if (isChildHeader) {
                heightTolerance = mStickyHeaderHeight - child.getHeight();
            }
        }

        //add heightTolerance if child top be in display area
        int childBottomPosition;
        if (child.getTop() > 0) {
            childBottomPosition = child.getBottom() + heightTolerance;
        } else {
            childBottomPosition = child.getBottom();
        }

        if (childBottomPosition > contactPoint) {
            if (child.getTop() <= contactPoint) {
                // This child overlaps the contactPoint
                childInContact = child;
                break;
            }
        }
    }
    return childInContact;
}

private void fixLayoutSize(ViewGroup parent, View view) {
    int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY);
    int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(), View.MeasureSpec.UNSPECIFIED);
    // Specs for children (headers)
    int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, parent.getPaddingLeft() + parent.getPaddingRight(), view.getLayoutParams().width);
    int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, parent.getPaddingTop() + parent.getPaddingBottom(), view.getLayoutParams().height);

    view.measure(childWidthSpec, childHeightSpec);
    view.layout(0, 0, view.getMeasuredWidth(), mStickyHeaderHeight = view.getMeasuredHeight());
}

}

I have a UI that is implemented in chatroom activities:

@Override
public boolean isHeader(int itemPosition) {
    return models.get(itemPosition).getType() .equals("header");
}

@Override
public int getHeaderPositionForItem(int itemPosition) {
    int headerPosition = 0;
    do {
        if (this.isHeader(itemPosition)) {
            headerPosition = itemPosition;
            break;
        }
        itemPosition ++;
    }
    while (itemPosition 

and the problem is: my first header at the end of the list is repeated when scrolling the list.
means: other headers are in the right position, but between each header my first header is displayed !!!
again sorry for mistakes :))))
Thank you .