Home > Mobile >  Crashing when an Intent is called inside a Recycler View Adapter
Crashing when an Intent is called inside a Recycler View Adapter

Time:09-07

public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

holder.parentCard.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent=new Intent(context,DetailedView.class);
        context.startActivity(intent);
    }
});

The Intent is not passing to the other activity when the cardView is clicked.

CodePudding user response:

Recycler view doesnt have current activity context, so while recycler adapter initial time you need to pass current activity of context. check context is null or not check DetailedView activity registered manifest or not

another war to achieve intent interface concept is there refer this tutorial better https://www.geeksforgeeks.org/android-recyclerview/

CodePudding user response:

Try this in viewHolder If You only need To change Activity:-

itemView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {             
         context.startActivity(context,DetailedView.class);
         }
       });

If you need to transfer data then best Practice to use the interface.

CodePudding user response:

This is not the right way.

  1. First of all crate interface callback

    public interface ItemClick { void onItemClick(int position); }

  2. Then calling this interface method inside adapter class and passing through the constructor and finally

    itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (settingsItemClick!=null) { int pos=getAdapterPosition(); if(pos!=RecyclerView.NO_POSITION) { settingsItemClick.onItemClick(pos); } } } });

3.Then inside activity implements interface method.

CodePudding user response:

Please provide that what crash you get. Make sure that context is not null. and for better practice use interface for any view action in adapter and the action flow in activity/fragment.

  • Related