Use Intent Activity in RecyclerView and get position ID - android

I created six of CardView and linked them to RecyclerView , how when press on cardview postion[2]
I want to make every card view and guest a move to another activity
this my code.
public class MyMovieAdapter extends RecyclerView.Adapter<MyMovieAdapter.ViewHolder> {
MyMovieData[] myMovieData;
Context context;
public MyMovieAdapter(MyMovieData[] myMovieData,MainActivity activity) {
this.myMovieData = myMovieData;
this.context = activity;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.movie_item_list,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final MyMovieData myMovieDataList = myMovieData[position];
holder.textViewName.setText(myMovieDataList.getMovieName());
holder.textViewDate.setText(myMovieDataList.getMovieDate());
holder.movieImage.setImageResource(myMovieDataList.getMovieImage());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, myMovieDataList.getMovieName(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), MainActivity2.class);//////////////// //this line //////////////////////// I want to position id
v.getContext().startActivity(intent);
}
});
}

you already have int position, just make it final and then you may use it inside onClick
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
...
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, myMovieDataList.getMovieName(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), MainActivity2.class);
intent.putExtra("position", position);
// would be better to pass item id or name, much better approach
intent.putExtra("itemId", myMovieDataList.getMovieId());
v.getContext().startActivity(intent);
}
});
}

Answer by #snachman is perfectly right. But, it is not preferred by google. Use the method given below.
Create a new interface with name RecyclerViewItemClickListener.java
Add method void onClick(); to it;
Add that to the constructor of the adapter.
After adding the constructor, add it to your activity by implementing the interface
Add it in the activity by new RecyclerViewItemClickListener
Now in the activity, add the code to start the activity.
Hope it helps 😀

Related

item.view on clickListener does not work with my viewholder

I've created an adapter for my Category gridview to show in my Main activity.
Categories are shown inside a CardView.
In order to click on each category, i can only access by the image or the text in the viewholder. that's not ideal, as you have to clicl exactly on the image to open new activity.
I would love to add the "itemview" to be able to click in any point of the cardview. I did it, but it does not work. I can only see the click but nothing happens.
Something like this:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, categoryModel.getCatName(), Toast.LENGTH_SHORT).show();
}
});
My Adapter:
public class categoryCardViewAdpt extends RecyclerView.Adapter<categoryCardViewAdpt.ViewHolder> {
CategoryModel[] categoryModels;
Context context;
public categoryCardViewAdpt (CategoryModel[] categoryModels, MainActivity activity){
this.categoryModels = categoryModels;
this.context = activity;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView catImageView;
public TextView catTv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
catImageView = (ImageView) itemView.findViewById(R.id.category_img2);
catTv = (TextView) itemView.findViewById(R.id.category_name_2);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.card_view_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final CategoryModel categoryModel = categoryModels[position];
holder.catTv.setText(categoryModel.getCatName());
holder.catImageView.setImageResource(categoryModel.getCatImage());
holder.catImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(context, categoryModel.getCatName(), Toast.LENGTH_SHORT).show();
if (categoryModel.getCatName().equals(R.string.farina)){
Intent intent = new Intent(context, FarinaActivity.class);
context.startActivity(intent);
}
else if (categoryModel.getCatName().equals(R.string.farina_inverso)){
Intent intent = new Intent(context, FarinaInversoActivity.class);
context.startActivity(intent);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
else if (categoryModel.getCatName().equals(R.string.alcol)){
Intent intent = new Intent(context, AlcolActivity.class);
context.startActivity(intent);
}
else if (categoryModel.getCatName().equals(R.string.panna)){
Intent intent = new Intent(context, PannaActivity.class);
context.startActivity(intent);
}
else if (categoryModel.getCatName().equals(R.string.chocolate)){
Intent intent = new Intent(context, ChocoActivity.class);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return categoryModels.length;
}
}
your holder.catImageView is in your ItemView. so the click event may intercepted by ItemView.
Do not use holder.catImageView.setOnClickListener
use : holder.itemView.setonClickListener.

Onclick for each button inside RecyclerView items

How to get the position for clicked button inside the RecyclerView items
Here's my onBindViewHolder :
public void onBindViewHolder(MyViewHolder holder, int position) {
Masar masar=masrList.get(position);
holder.masarName.setText(masar.getMasarTitle());
holder.masarDesc.setText(masar.getMasarDescreption());
//How to get the Position
holder.masarImg.setImageResource(masar.getMasarImg());
holder.mapBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
//if you need position, just use recycleViewHolder.getAdapterPosition();
Intent intent = new Intent(v.getContext(), MapsActivity.class);
mContext.startActivity(intent);
}
});
}
If you need in onBindViewHolder only then you can use
holder.getAdapterPosition();
and if you need this position clicked in activity and fragment then you have to use callbacks from holder to activity and fragment and have to pass the same getAdapterPosition();
Edit: Added sample code for listening position click in fragment/activity
step 1: make an interface or callback
public interface RecyclerViewClickListener {
void onClick(View view, int position);
}
step 2: While initializing adapter class in fragment or activity pass the above-created reference as a parameter
public YourAdapter(List<SomeModel> modelList, RecyclerViewClickListener listener){
this.clickListener = listener;
}
step 3: In your ViewHolder or similar Class for view initialization do something like this
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button mapBtn;
ViewHolder(View v, RecyclerViewClickListener listener) {
super(v);
mapBtn = findViewById(R.id.mapBtn);
mListener = listener;
mapBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mListener.onClick(view, getAdapterPosition());
}
}
you will get the position in your fragment or activity where you have passed the callback reference while initializing the adapter.
Use holder.getAdapterPosition();
public void onBindViewHolder(final MyViewHolder holder, int position) {
Masar masar=masrList.get(position);
holder.masarName.setText(masar.getMasarTitle());
holder.masarDesc.setText(masar.getMasarDescreption());
//How to get the Position
holder.masarImg.setImageResource(masar.getMasarImg());
holder.mapBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
Toast.makeText(getContext(), "The position is: "+holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), MapsActivity.class);
mContext.startActivity(intent);
}
});}

Setting data on ViewHolder

I am using a RecyclerView in my project and I am having an issue where my RecyclerView is being populated by the same values as if the values are being overwritten inside the forEach in onBindViewHolder below:
class ProfListAdapter extends RecyclerView.Adapter<ViewHolder>{
private LayoutInflater mLayoutInflater;
public ProfListAdapter(Context context) {
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType){
return new ViewHolder(mLayoutInflater
.inflate(R.layout.recycler_view, viewGroup, false));
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position){
System.out.println(position);
final String profName;
Integer k = 0;
for (Integer key : mData.keySet()) {
viewHolder.setData(mData.get(key));
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent intent = ProfPager.newIntent(getActivity(), position);
startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView;
private ViewHolder(View itemView){
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id._prof); // galleryimage
}
private void setData(String profName){
mTextView.setText(profName);
System.out.println("setData" + profName);
}
}
When I log out to the console I can see that the value in setData() is getting the correct item to display. However, what is being displayed inside the fragment is just the last profName that is comes across in the forEach. What could be causing this behaviour? Here is a link to the entire fragment: https://pastebin.com/xS7CSbbK
If I use the position, it does not always coincide with the key in the Hashmap that stores the SQLite _id.
Setting data on ViewHolder
You may not need the for each loop inside the onBindViewHolder, instead try to set data using the position value available at onBindViewHolder. cheers :)
For RecyclerView , use ArrayList for simplicity
And change your onBindViewHolder like this
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position){
System.out.println(position);
viewHolder.setData(mData.get(position));
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent intent = ProfPager.newIntent(getActivity(), position);
startActivity(intent);
}
});
}
I assume mData as ArrayList

Application is crashing when I start activity from setOnClickListener of RecyclerView's adapter

I've got a RecyclerView which is loading the content of my String Arrays which works fine, however I want to open a new Activity depending on which view they have pressed.
What I have done:
public class WinnersListAdapter extends RecyclerView.Adapter<WinnersListAdapter.WinnersCardViewHolder>
{
Context context;
LayoutInflater inflater;
List<ListLottery> lotteryList;
public WinnersListAdapter(List<ListLottery> loteries,Context context){
this.context = context;
this.lotteryList = loteries;
inflater = LayoutInflater.from(context);
}
#Override
public WinnersListAdapter.WinnersCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.prevlotterycards_layout,parent,false);
// Toast.makeText(context,"Hi",Toast.LENGTH_SHORT).show();
WinnersListAdapter.WinnersCardViewHolder viewHolder = new WinnersListAdapter.WinnersCardViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(WinnersListAdapter.WinnersCardViewHolder holder, int position) {
final ListLottery lottery = lotteryList.get(position);
holder.lottery_date.setText(lottery.getLotteryDate());
holder.lottery_date.setTag(holder);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"clicked--"+lottery.getLotteryId(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,WinnerActivity.class);
intent.putExtra("lotteryId",lottery.getLotteryId());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return lotteryList.size();
}
class WinnersCardViewHolder extends RecyclerView.ViewHolder {
TextView lottery_date;
CardView card_lotteryList;
public WinnersCardViewHolder(View itemView) {
super(itemView);
lottery_date = (TextView) itemView.findViewById(R.id.l_lottery_date);
card_lotteryList = (CardView) itemView.findViewById(R.id.card_lotteryList);
}
}
}
I have read many articles to resolve it and did stuff according that but could not find any solution.
Actually, I can not answer your question because you didn't post your logcat but there are few things you can check :
1 - Check that your activity already declared in AndroidManifest.xml
2 - Check you context is the context of Activity or applicationContext ?
If is't not the context of Activity so you need to add flag
Intent i = new Intent(this, WinnerActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Trouble with intent in RecyclerView

I started in the android programming and and I encountered a problem when i tried to send data from my Adapter to an another activity
.
I want to show the content of "description" in my other activity when I click on an item.
MyAdapter class :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private final List<FakeNews> list = FakeNewsList.all;
#Override
public int getItemCount() {
return list.size();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_cell, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
FakeNews pair = list.get(position);
holder.display(pair);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final TextView description;
private FakeNews currentPair;
public MyViewHolder(final View itemView) {
super(itemView);
name = ((TextView) itemView.findViewById(R.id.name));
description = ((TextView) itemView.findViewById(R.id.description));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MyViewHolder.this ,Affich.class);
intent.putExtra("description", String.valueOf((description)));
startActivity(intent);
}
});
}
public void display(FakeNews pair) {
currentPair = pair;
name.setText(pair.title);
}
}
}
Can someone help me?
I assume that you do not really want to pass the TextView to your next activity, but the content which is shown in it. Also, you need to pass a Context to the Intent and startActivity() is a method of an activity, so you need to call it on the context:
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext() ,Affich.class);
intent.putExtra("description", description.getText().toString());
view.getContext().startActivity(intent);
}
});
Pass the Context or Activity instance into your adapter class.
then while starting new Activity and suppose instance variable is mContext use like this-
Intent intent = new Intent(mContext ,Affich.class);
intent.putExtra("description", String.valueOf((description)));
mContext.startActivity(intent);
To pass value from TextView to your new activity, do this:
intent.putExtra("description", description.getText().toString());
on your new activity, get the description value using:
String descriptionValue = getIntent().getStringExtra("description");

Categories

Resources