简体   繁体   中英

Crashing when an Intent is called inside a Recycler View Adapter

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.

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/

There are multiple reasons to this crash since you have not provided the Crash logs/stacktrace.

  1. The context provided is not an Activity context in which case you need to add the Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK to your Intent's flags.

  2. It is possible the crash is in the DetailedView Activity due to probably a NullPointerException or it is not added to AndroidManifest.xml

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM