I have a POJO
class. It holds some Strings and I want to pass values from RecyclerView
to an Activity
. I tried something and failed. How do I do that?
Model
public class DetailModel {
String title;
public DetailModel() {
}
public DetailModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Adapter, onClick
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
detailModel=new DetailModel();
detailModels= new ArrayList<>();
detailModel.setTitle(holder.headerText.getText().toString());
Intent detailIntent = new Intent(context.getApplicationContext(), DetailActivity.class);
context.startActivity(detailIntent);
}
});
Another Activity
DetailModel detailModel=new DetailModel();
detailBody.setText(detailModel.getTitle());
There is several ways to do that, but I will show you simplest one :
In your onBindViewHolder
:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,final int position) {
final MyView myHolder = (MyView) holder;
myHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
detailModel.setTitle(holder.headerText.getText().toString());
Intent detailIntent = new Intent(context, DetailActivity.class);
//To pass your class:
intent.putExtra("mypojo", details.get(position));
context.startActivity(detailIntent);
}
});
}
In this way you must implement Serializable
in your POJO
class :
public class DetailModel implements Serializable{
String title;
public DetailModel() {
}
public DetailModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
And in second Activity
use this code to get class :
getIntent().getExtras().getSerializable("mypojo");
//also you can cast extra
DetailModel detailmodel=(Detailmodel) getIntent().getExtras().getSerializable("mypojo");
//if you implemented Parcelable
DetailModel detailmodel=(Detailmodel) getIntent().getExtras().getParcelable("mypojo");
This is the first way, in another and faster way is using Parcelable
, checkout this answer but you must make some effort in Parcelable
: how-to-send-an-object-from-one-android-activity-to-another-using-intent
I suggest you to use Parcelable
maybe you need some time to learn it but you can feel speed difference in bigger classes.
Also if you have small amounts of Strings in your POJO, try to use intent extras instead of sending class like that :
intent.putExtra("model_name",pojo.getName());
//then get
getIntent().getExtras().getString("model_name");
A recycler view by itself doesn't hold any data. That is the job of your adapter. The recyclerview' a job is to display that data and intercept touch events. So on your click listener get a hold of the data(POJO object) and pass that to your activity.