Add OnClickListner to CardView and get data - android

I wan to attach an OnClickListener to a CardView, so i can get the ID from the card
I have a RecyclerView that has a custom adapter for displaying the cards. This is how it's implemented.
I tried other examples in stackoverflow but it didn't work .
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ArrayList<Patient> patients;
Context mContext;
String idPatient;
public CardAdapter(ArrayList<Patient> patients) {
this.patients = patients;
}
#Override
public CardAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_card_view, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(CardAdapter.ViewHolder viewHolder, int i) {
viewHolder.first_name.setText(patients.get(i).getFirstName());
viewHolder.last_name.setText(patients.get(i).getLastName());
viewHolder.id_patient.setText(String.valueOf(patients.get(i).getId()));
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//trying to get ID From card
ViewGroup parentView = (ViewGroup)v.getParent();
TextView idpatientview =(TextView)parentView.findViewById(R.id.idViewPatient);
idPatient = idpatientview.getText().toString();
PreferencesHelper.save(mContext, "idPatient", idPatient);
Intent intent = new Intent(mContext, BluetoothActivity.class);
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return patients.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView first_name,last_name,id_patient;
public ViewHolder(View view) {
super(view);
first_name = (TextView)view.findViewById(R.id.textViewName);
last_name = (TextView)view.findViewById(R.id.textViewLastName);
id_patient = (TextView)view.findViewById(R.id.idViewPatient);
}
}
}

If your onClick method is inside your onBindViewHolder, then you can get the current data directly
String first_name = patients.get(i).getFirstName();
String last_name = patients.get(i).getLastName();
String id_patient = String.valueOf(patients.get(i).getId());
in your onClickListener, the id of the patient corresponding to the clicked card is simply id_patient, the first name is first_name and the last name is last_name. You can now pass the data to your activity (with an interface for exemple)

Related

Android: Pass text from Textview when clicking an Image button inside recycler view

So I have a recycler view with 2 texts and 1 image button. I want to click the image button and then open a new activity and transfering the text from the textViewADV1 to the next activity
My items .xml in my recyclerview consist of the following
<ImageButton
android:id="#+id/imageButton1"
android:clickable="true"
android:onClick="openActivity2"/>
<TextView
android:id="#+id/textViewADV1"
android:text="Line 1"/>
<TextView
android:id="#+id/textViewADV2"
android:text="Line 2"/>
My openActivity2() from Main Activity
public void openActivity2(View view)
{
Intent intentLoadNewActivity = new Intent(AdvancedResults.this,OpenSelectedAdvanced.class);
startActivity(intentLoadNewActivity);
}
I tried doing textViewADV1.getText().toString() but it only reads the text from the first item in the recycler view
My recycler adapter
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
public String mImage;
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImagebtn;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView) {
super(itemView);
mImagebtn = itemView.findViewById(R.id.imageButtonADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList) {
mAdvancedList = advancedList;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
Picasso.get().load(mImage).into(holder.mImagebtn);
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
}
First of all pass a context to your adapter when you initialize it:
//in the main activity that you initialize the adapter in
AdvancedAdapter adapter = new AdvancedAdapter(your_list , MainActivity.this);
Now change the constructor of AdvancedAdapter to accept context
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
private Context context;
.............
//constructor
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList,Context context) {
mAdvancedList = advancedList;
this.context = context;
}
Now in onBindViewHolder in the AdvancedAdapter
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
Picasso.get().load(mImage).into(holder.mImagebtn);
//on click image button
hodler.mImagebtn.setOnclickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(context , OpenSelectedAdvanced.class);
intent.putExtra("data" , currentItem.getText1());
context.startActivity(intent);
}
});
}
To get the data from OpenSelectedAdvanced activity:
//in oncreate method:
Intent intent = getIntent();
//this is your text view text that came from the clicked image button
String transferedText = intent.getStringExtra("data");
If you have declared your onBindViewHolder() in your adapter class so why are you starting activity from MainActivity. You should add setOnclicklistenr() in onBindViewHolder() to achieve the desired result that you want that is in following way :
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
//one more thing you have to create Context field so that you can
//you can start the activity from any context (From Any activity)
private Context mContext;
public String mImage;
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImagebtn;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView) {
super(itemView);
mImagebtn = itemView.findViewById(R.id.imageButtonADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList, Context mContext) {
mAdvancedList = advancedList;
this.mContext = mContext;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
holder.mImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here You start your activity
Intent intent = new Intent(mContext, Activity2.class);
//you can putExtras here
mContext.startActivity(intent);
});
Picasso.get().load(mImage).into(holder.mImagebtn);
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
}
Now initialize this adapter in your activity where you implemented recyclerView And Send that arraylist into the parameters of that constructor of your adapter :) if did not understand yet you can try the tutorial on the link given below : https://www.youtube.com/watch?v=bIppSKk9afI

How to implement recyclerview ItemClickListener() in Firebase recycler adapter?

I've followed this tutorial at YouTube.
I manage to search the data but now I want to open the details page of selected data on recycler view. How do I get it done? At which part should I implement the onClickListener for recyclerview? I've tried to put onClickListener, intent put extra ... in method OnBindViewHolder and SetDetails, but both of them have problems to recognize my context.
Here is my current code:
private void firebaseIngredientSearch(String searchIngredient) {
Toast.makeText(SearchActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = databaseReference.orderByChild("ingName").startAt(searchIngredient).endAt(searchIngredient + "\uf8ff");
FirebaseRecyclerOptions<Ingredients> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Ingredients>()
.setQuery(firebaseSearchQuery, Ingredients.class)
.build();
FirebaseRecyclerAdapter<Ingredients, SearchActivity.IngredientsViewHolder> firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<Ingredients, SearchActivity.IngredientsViewHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull IngredientsViewHolder holder, int position, #NonNull final Ingredients model) {
holder.setDetails(model.getIngName(), model.getIngStatus(),model.getIngCategory(),model.getIngCategory());
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goDetail = new Intent(, IngredientSearchDetailsActivity.class);
goDetail.putExtra("ingName", model.getIngName());
goDetail.putExtra("ingStatus", model.getIngStatus());
goDetail.putExtra("ingCategory", model.getIngCategory());
goDetail.putExtra("ingDescription", model.getIngDescription());
mActivity.startActivity(goDetail);
}
});
}
#NonNull
#Override
public IngredientsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_searched_ingredient, parent, false);
return new IngredientsViewHolder(view);
}
};
firebaseRecyclerAdapter.startListening();
rvSearchResult.setAdapter(firebaseRecyclerAdapter);
}
////////////////////////////////////////////////////////////////////////////////
public static class IngredientsViewHolder extends RecyclerView.ViewHolder {
View view;
public IngredientsViewHolder(#androidx.annotation.NonNull View itemView) {
super(itemView);
view = itemView;
}
public void setDetails(String ingName, String ingStatus, String ingCategory, String ingDescription) {
TextView i_Name = view.findViewById(R.id.tvName);
TextView i_Status = view.findViewById(R.id.tvStatus);
TextView i_Category = view.findViewById(R.id.tvCategory);
TextView i_Description = view.findViewById(R.id.tvDescription);
ImageView iv_Status = view.findViewById(R.id.searchStatusIv);
i_Name.setText(ingName);
i_Status.setText(ingStatus);
i_Category.setText(ingCategory);
i_Description.setText(ingDescription);
}
}
User holder.view.setOnClickListener to initiate OnClickListener and use holder.view.getContext() instead of mActivity
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goDetail = new Intent(, IngredientSearchDetailsActivity.class);
goDetail.putExtra("ingName", model.getIngName());
goDetail.putExtra("ingStatus", model.getIngStatus());
goDetail.putExtra("ingCategory", model.getIngCategory());
goDetail.putExtra("ingDescription", model.getIngDescription());
holder.view.getContext().startActivity(goDetail);
}
});

The current post of Recycle View can not transfer correct data to another activity

I use recycle view to show posts of users. I create a button on each post of Recycle view. When user click on this button, every data of this post will be transferred to another activity. My problem is that when I click on the button of a post, the tranferred data is not the data of this post. For example, when I click the button of post 1, the data of post 2 is transferred to new activity instead of the data of post 1. Can anyone help me to solve this problem? Thank you in advance
Below is my Recycle View adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ImageViewHolder> {
private Context context;
private List<Upload> uploads;
Upload uploadCurrent;
private String userEmail, locationName, locationType, locationAddress,
userComment, downloadUrl, userLatitude, userLongitude;
public CustomAdapter(Context context, List<Upload> uploads) {
this.context = context;
this.uploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.custom_view, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
uploadCurrent = this.uploads.get(position);
userEmail = uploadCurrent.getUserEmail();
locationName = uploadCurrent.getLocationName();
locationType = uploadCurrent.getLocationType();
locationAddress = uploadCurrent.getLocationAddress();
userComment = uploadCurrent.getUserComment();
downloadUrl = uploadCurrent.getDownloadUrl();
userLatitude = uploadCurrent.getUserLatitude();
userLongitude = uploadCurrent.getUserLongitude();
holder.emailCustom.setText(userEmail);
holder.nameCustom.setText(locationName);
holder.commentCustom.setText("Review: " + userComment );
holder.typeCustom.setText("Type: "+ locationType );
holder.addressCustom.setText("Address: " + locationAddress);
Picasso.get().load(downloadUrl).fit().centerCrop().into(holder.imageCustom);
//handle button
holder.saveCustomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SaveActivity.class);
intent.putExtra("adap_name", locationName);
intent.putExtra("adap_address", locationAddress);
intent.putExtra("adap_type", locationType);
intent.putExtra("adap_comment", userComment);
intent.putExtra("adap_image", downloadUrl);
intent.putExtra("adap_latitude", userLatitude);
intent.putExtra("adap_longitude", userLongitude);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return this.uploads.size(); //how many items in our uploads list
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView emailCustom;
public TextView nameCustom;
public TextView commentCustom;
public TextView typeCustom;
public TextView addressCustom;
public ImageView imageCustom;
public Button saveCustomButton;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
emailCustom = itemView.findViewById(R.id.emailCustom);
nameCustom = itemView.findViewById(R.id.nameCustom);
typeCustom = itemView.findViewById(R.id.typeCustom);
addressCustom = itemView.findViewById(R.id.addressCustom);
commentCustom = itemView.findViewById(R.id.commentCustom);
imageCustom = itemView.findViewById(R.id.imageCustom);
saveCustomButton = itemView.findViewById(R.id.saveCustomButton);
}
}
}
Just put your clicklistener from onBindViewHolder method to ImageViewHolder class and make use of adapterposition method:
holder.saveCustomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadCurrent = uploads.get(getAdapterPosition());
Intent intent = new Intent(context, SaveActivity.class);
intent.putExtra("adap_name", uploadCurrent.getlocationName());
context.startActivity(intent);
}
});
Repeat same for getting other attributes.
Cool! In your adapter, just do the below things
Kotlin
override fun getItemId(position: Int): Long {
return position.toLong()}
override fun getItemViewType(position: Int): Int {
return position}
Java
#Override
public Long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
Does it crash when you click the button on the last item in the recycler view? If so then it could be that your index is out of bound.
you are initialize string globally so they are taking last value from list initialize them in ImageViewHolder that will work for you
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView emailCustom;
public TextView nameCustom;
public TextView commentCustom;
public TextView typeCustom;
public TextView addressCustom;
String userEmail, locationName, locationType, locationAddress,
userComment, downloadUrl, userLatitude, userLongitude;

Item manages his click or call listener ? (recyclerView)

I have a RecyclerView which contains multiple item types (4 or 5 at least).
Some items can be clicked, sometimes they have two differents clickListener (for example two imageView in one item).
For now, the item manages the clicks himself like this :
item.imageView1.setOnClickListener(....){
startActivity(Activity2);
}
item.imageView2.setOnClickListener(....){
startActivity(Activity1);
}
But I have a problem : I need to put some variables in the activity which will be started, so what is the best way to do this :
1) My item need to know these variables and continues to manage his own click ?
2) My item has a listener which call startActivity with the variables (like the fragment or parent activity or an object dedicated to this) ?
If you need more precisions, ask me.
Thx.
Make an interface for passing those values.
public interface MyRecyclerCallback {
void onItemClicked(Integer o); //insert whatever you want to pass further, possibly translated to form packable to intents
}
Then add it to your adapter from the activity with recycler like you would any listener. Either constructor or by separate method.
Pass it further down to every children upon their creation.
Call it when onClick gets detected with appropriate argument.
The actual argument may be some abstract thing
depending on your logic. It's more of a general idea. That's the way I do it with my recyclers.
In your activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecycler = (RecyclerView) findViewById(R.id.recycler);
MyAdapter adapter = new MyAdapter(this,new MyRecyclerCallback() {
#Override
public void onItemClicked(Integer o) { //any argument you like, might be an abstract
Intent i = new Intent(this,ActivityTwo.class);
i.putExtra(EXTRA_VALUE,o);
startActivity(i);
}
});
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(adapter);
}
Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.Child>{
private final Context mContext;
private final MyRecyclerCallback mCallback;
private List<Integer> mChildren;
public MyAdapter(Context ctx, MyRecyclerCallback myRecyclerCallback) {
mContext = ctx;
mCallback = myRecyclerCallback;
mChildren = new ArrayList<>();
}
public void populateList(List<Integer> list ) { //this can be a network call or whatever you like
mChildren.addAll(list);
}
#Override
public Child onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false);
return new Child(v,mCallback);
}
#Override
public void onBindViewHolder(Child holder, int position) {
holder.setValue1(mChildren.get(position)*3);
holder.setValue2(mChildren.get(position));
}
#Override
public int getItemCount() {
return mChildren.size();
}
public class Child extends RecyclerView.ViewHolder{
View mView1;
View mView2;
private int mValue1;
private int mValue2;
public Child(View itemView, final MyRecyclerCallback mCallback) {
super(itemView);
mView1 = itemView.findViewById(R.id.view1);
mView2 = itemView.findViewById(R.id.view2);
mView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCallback.onItemClicked(mValue1);
}
});
mView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCallback.onItemClicked(mValue2);
}
});
}
public void setValue1(int position) {
mValue1 = position;
}
public void setValue2(int position) {
mValue2=position;
}
}
}
this a good alternative to handle onclick and onlongclick
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/
You can have a single OnClickListener on your ViewHolder class and use it with an interface to determine the type of item which has been clicked.
For example, say you have a model class called Item :
public class Item {
private int itemType;
private String itemDescription;
private String optionalExtra;
public static final int ITEM_TYPE_1 = 1;
public static final int ITEM_TYPE_2 = 2;
public Item(int itemType, String itemDescription) {
this.itemType = itemType;
this.itemDescription = itemDescription;
}
public Item(int itemType, String itemDescription, String optionalExtra) {
this.itemType = itemType;
this.itemDescription = itemDescription;
this.optionalExtra = optionalExtra;
}
}
You have a custom interface defined to intercept click on items in recyclerview :
public interface CustomClickListener {
void onClickOfItemType1( int position );
void onClickOfItemType2( int position );
}
Inside your adapter for recyclerview, in the viewholder class :
//Similar implementation for other ViewHolders too.
public class ViewHolderType1 extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView;
View itemView;
public ViewHolderType1(View view) {
super(view);
this.itemView = view;
//initialize other views here
//Set item click listener on your view
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int itemPosition = getAdapterPosition();
if( itemPosition != RecyclerView.NO_POSITION ) {
customClickListener.onClickOfItemType1(itemPosition);
//You can call onClickOfItemType2(itemPosition) in your other type of view holder class
}
}
}
In your Activity or Fragment :
Pass the customClickListener as a parameter to your adapeter :
CustomAdapter customAdapter = new CustomAdapter(List<Item> itemList, new CustomClickListener {
#Override
void onClickOfItemType1(int position) {
Item item = itemList.get(position);
//This item is of type 1
//You can implement serializable / parcelable in your item class and use it to directly pass across item to your activity
Intent intent = new Intent(Activity.this, CustomActivity1.class);
intent.putExtra("item", item);
startActivity(intent);
}
#Override
void onClickOfItemType2(int position) {
Item item = itemList.get(position);
//This item is of type 2
//You can implement serializable / parcelable in your item class and use it to directly pass across item to your activity
Intent intent = new Intent(Activity.this, CustomActivity2.class);
intent.putExtra("item", item);
startActivity(intent);
}
});
In case you are trying to trigger different activities on click of different views; inside your viewclicklistener implementation check the view id and trigger the corresponding activity.
#Override
public void onClick(View v) {
int itemPosition = getAdapterPosition();
if( itemPosition != RecyclerView.NO_POSITION ) {
switch(v.getId()) {
case R.id.imageView :
customClickListener.onClickOfItemType1(itemPosition);
break;
case R.id.textView :
customClickListener.onClickOfItemType2(itemPosition);
break;
}
}
}
This is a guide for usage of RecyclerView :
https://guides.codepath.com/android/using-the-recyclerview

sending row id when RecyclerView item clicked

I have prepared a Database in my asset folder . I have one recyclerView for showing the title in the database . Now i want show DetailActivity with specificid . my means is show description of post . I think it can be done with intent , but i don't know how .
public class FehrestRecyclerAdapter extends RecyclerView.Adapter<FehrestRecyclerAdapter.ViewHolder> {
private Context ctx;
private List<Post> posts;
//constructor
public FehrestRecyclerAdapter(Context ctx, List<Post> posts) {
this.ctx = ctx;
this.posts= posts;
}
//ViewHodler Pattern
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView txtTitle;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txtTitle= (TextView)itemView.findViewById(R.id.txtTitle);
}
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext() , txtTitle.getText() , Toast.LENGTH_SHORT).show();
Intent intent = new Intent(itemView.getContext() , DetailActivity.class);
intent.putExtra("postId" , "id");
itemView.getContext().startActivity(intent);
}
}
//OncreateViewHolder
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_row , parent , false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
//OnBindViewHolder
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Post current = Post.get(position);
holder.txtTitle.setText(current.getTitle());
}
//getItemCount method
#Override
public int getItemCount() {
return posts.size();
}
}
i have a 3 columns in my database
1.id 2.title 3.desc
and 3 methods in my Post model Class :
getId() 2.getTitle() 3.getDesc()
as you can see i can send intent to DetailActivity . But i don't know how can i achieve to sending specific id to DetailActivity. thanks
Make one Variable id in ViewHolder and assign that in onBindViewHolder() , I updated the code according to that.
public class FehrestRecyclerAdapter extends RecyclerView.Adapter<FehrestRecyclerAdapter.ViewHolder> {
private Context ctx;
private List<Post> posts;
//constructor
public FehrestRecyclerAdapter(Context ctx, List<Post> posts) {
this.ctx = ctx;
this.posts= posts;
}
//ViewHodler Pattern
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView txtTitle;
private int id;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txtTitle= (TextView)itemView.findViewById(R.id.txtTitle);
}
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext() , txtTitle.getText() , Toast.LENGTH_SHORT).show();
Intent intent = new Intent(itemView.getContext() , DetailActivity.class);
// here pass id through intent
intent.putExtra("postId" , id);
itemView.getContext().startActivity(intent);
}
}
//OncreateViewHolder
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_row , parent , false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
//OnBindViewHolder
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Post current = Post.get(position);
holder.txtTitle.setText(current.getTitle());
// add this line
holder.id = Post.get(postion).getId();
}
//getItemCount method
#Override
public int getItemCount() {
return posts.size();
}
}
How can i achieve to sending specific id to DetailActivity
Use setTag method of holder.txtTitle TextView for storing id with TextView and call getTag inside onClick of View Click like:
1. In onBindViewHolder save current using setTag:
holder.txtTitle.setTag(current);
holder.txtTitle.setText(current.getTitle());
2. In onClick of View use getTag as:
#Override
public void onClick(View v) {
txtTitle= (TextView)v.findViewById(R.id.txtTitle);
Post current=(Post)txtTitle.getTag();
intent.putExtra("postId" , current.getId());
intent.putExtra("postTitle" , current.getTitle());
....
}

Categories

Resources