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.
Related
I have a From designed in ViewPager with 5 fragments which consists of all type of inputs(radio group, text, date, drop down) in it. I have to save and submit the form data on submit button click on last fragment.
Now I want to how to keep data saved while traversing between pages of view pager and send a post request at end of view pager? because in view pager i can store state of only 3 pages, while when I traverse to 4th page I will loose data of 1st page. Please let me know how to solve this issue.
I think for your problem the best solution is to create a singleton that contains your object
and at each transition from one fragment to another you update the object in the singleton
Singleton class is the answer for answer. Singleton - Only one instance of the class at a time.
Example :
Your singleton will be like this,
public class AddProductSingleton {
private static AddProductSingleton instance = null;
private String Category;
private String Title;
private String SubTitle;
private String Description;
private AddProductSingleton(){ }
public static AddProductSingleton getInstance(){
if (instance == null)
instance = new AddProductSingleton();
return instance;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getSubTitle() {
return SubTitle;
}
public void setSubTitle(String subTitle) {
SubTitle = subTitle;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
And your fragments will be this,
First Fragment
public class Fragment1 extends Fragment {
AddProductSingleton objAddProductDetails = AddProductSingleton.getInstance();
objAddProductDetails.setCategory("Fragment1")
}
Second Fragment,
public class Fragment2 extends Fragment {
ddProductSingleton objAddProductDetails = AddProductSingleton.getInstance();
objAddProductDetails.setTitle("Fragment2")
}
Third Fragment,
public class Fragment3 extends Fragment {
ddProductSingleton objAddProductDetails = AddProductSingleton.getInstance();
objAddProductDetails.setSubTitle("Fragment3")
}
Fourth Fragment,
public class Fragment4 extends Fragment {
ddProductSingleton objAddProductDetails = AddProductSingleton.getInstance();
objAddProductDetails.setDescription("Fragment4")
}
After this your singleton object posses all the values sets in different fragments.
objAddProductDetails.getCategory() // Fragment1
objAddProductDetails.getTitle() // Fragment2
objAddProductDetails.getSubTitle() // Fragment3
objAddProductDetails.getDescription() // Fragment4
I hope this will be best proper solution to your query, Happy coding.
How to pass arraylist value (samplename, samplequote ) to the intent.putExtra.. for sharing the text..
In MainActivity.java
list = new ArrayList<>();
//loading list view item with this function
loadRecyclerViewItem();
}
private void loadRecyclerViewItem() {
list.add(new MyQuote("sample name","sample quote"));
In MyRecyclerViewAdapter.java
public void onBindViewHolder(final MyRecycleViewAdapter.ViewHolder myholder, int position) {
final MyQuote myQuote = myQuoteList.get(position);
myholder.tv_author.setText(myQuote.getAuthor());
myholder.tv_quote.setText(myQuote.getQuotedesc());
myholder.im_favlike.setImageResource(R.drawable.fav_border);
myholder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent (Intent.ACTION_SEND);
intent.setType("text/plain");
view.getContext().startActivity(Intent.createChooser(intent,"send to"));
}
});
}
EDIT
after implementing Parcelable in MyQuote class.. like this when i use intent.putParcelableArrayListExtra("mani" , MyQuote);....
i'm getting "expression expected ...in MyRecyclerViewAdapter.java"
public class MyQuote implements Parcelable{
private String author;
private String quotedesc;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(quotedesc);
parcel.writeString(author);
}
private MyQuote(Parcel parcel){
quotedesc = parcel.readString();
author = parcel.readString();
}
public static final Parcelable.Creator<MyQuote> CREATOR = new Parcelable.Creator<MyQuote>(){
#Override
public MyQuote createFromParcel(Parcel parcel) {
return new MyQuote(parcel);
}
public MyQuote[] newArray(int size){
return new MyQuote[size];
}
};
//constructor initializing values
public MyQuote(String author, String quotedesc) {
this.quotedesc = quotedesc;
this.author = author;
}
//getters
public String getAuthor() {
return author;
}
public String getQuotedesc() {
return quotedesc;
}
}
I have a recycler cardview which contains quotes,and authors.. as textviews..and a sharebutton.. in each card.. when user want to share the quote, author of a particular card.. he can share the quote(string) along with author(string) to apps like messeges, whatsapp ..etc..
how can i solve this ? is implementing parcelable is correct process..for this purpose or not..if it is correct what code should i use in onclick of a sharebutton
#Override
public void onBindViewHolder(final MyRecycleViewAdapter.ViewHolder myholder, int position) {
final MyQuote myQuote = myQuoteList.get(position);
myholder.tv_author.setText(myQuote.getAuthor());
myholder.tv_quote.setText(myQuote.getQuotedesc());
myholder.im_favlike.setImageResource(R.drawable.fav_border);
myholder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent (Intent.ACTION_SEND);
intent.putParcelableArrayListExtra("mani" , MyQuote);
intent.setType("text/plain");
view.getContext().startActivity(Intent.createChooser(intent,"send to"));
}
});
}
You have to implement Parcelable interface in MyQuote Class and then you can send it through intent like this :-
intent.putParcelableArrayListExtra(key_name,your_list);
The class of your array elements should implement Parcelable interface.
After doing so, you can use Intent.putParcelableArrayListExtra(ARRAY_LIST_KEY,fooArrayList) to send the array list and then Intent.getStringArrayListExtra(ARRAY_LIST_KEY) to retrieve the list
Hi check out this plugin Parcelable Code Generator.
It will help you to auto generate parcelable boilerplate for a POJO class and then you can directly use it as suggested by Abhishek
intent.putParcelableArrayListExtra(key_name, list);
I can get images and titles, texts in my post_row layout from my Firebase Server.
I want to click each items in the Recyclerview and I searched on them on google. but I couldn't find suitable codes implementing the click event in FirebaseRecyclerView.
and This is my FirebaseRecycler Adapter code!
thank you ~~!!
mDatabase = FirebaseDatabase.getInstance().getReference().child("post");
#Override
protected void onStart() {
super.onStart();
final Query DBquery = FirebaseDatabase.getInstance().getReference().child("post").orderByChild("count");
FirebaseRecyclerAdapter<Post, PostViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class,
R.layout.post_row,
PostViewHolder.class,
DBquery
mDatabase
) {
#Override
protected void populateViewHolder(PostViewHolder viewHolder, Post model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.setDate(model.getDate());
}
};
mPostList.setAdapter(firebaseRecyclerAdapter);
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
View mView;
public PostViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(Context ctx, String image){
ImageView post_image = mView.findViewById(R.id.post_image);
Picasso.get().load(image).into(post_image);
}
public void setDate(String date){
TextView post_date = mView.findViewById(R.id.post_date);
post_date.setText(date);
}
}
`
Use a listview to show your data, I use it like this and it's working really good.
Just inside populateViewHolder
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
mDatabase = mAdapter.getRef(position);
Intent intent = new Intent(MainActivity.this, UserEdit.class);
intent.putExtra("uid",mDatabase.getKey());
intent.putExtra("name", mAdapter.getItem(position).getNombre());
intent.putExtra("Email", mAdapter.getItem(position).getEmail());
intent.putExtra("paid", mAdapter.getItem(position).getPago());
intent.putExtra("connection", mAdapter.getItem(position).getUConexion());
intent.putExtra("connection2", mAdapter.getItem(position).getPConexion());
startActivity(intent);
}
});
mListView.setAdapter(mAdapter);
This is just an example from my code, it just clicks the list, get the item and pass it to another activity to work with that data.
With this you are setting the adapter data into a listview, and then clicking each item gives you the data of that position and you can manage that data in another activity if you need it.
The getters I'm using at the putExtras are being passed by the POJO class to the FirebaseList.
FirebaseListOptions<Usuarios> options = new FirebaseListOptions.Builder<Usuarios>()
.setQuery(query, Usuarios.class)
.setLayout(R.layout.item_row)
.build();
Here Usuarios is this:
private String Nombre;
private String Dispositivo;
private String sexo;
private String lenguaje;
private String email;
public Usuarios(){}
public Usuarios(String nombre, String dispositivo, String sexo, String lenguaje, String email, String PConexion, String UConexion, String URL_frases, String URL_grupos, String URL_pictos, String edad, String pago) {
Nombre = nombre;
Dispositivo = dispositivo;
this.sexo = sexo;
this.lenguaje = lenguaje;
this.email = email;
....
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public String getDispositivo() {
return Dispositivo;
}
....
Remember, here the variables nombre, email and so one need to be declared exactly as the Firebase database ones, otherwise you will see blank and results won't display, and remember in your onStart to place mAdapter.startListening();.
Add a function in your PostViewHolder say
public void init(int position){
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
//Handle your click here
}
});
}
Now from populateViewHolder call
viewHolder.init(position);
To solve this, in your PostViewHolder class attach a click listener on your view like this:
mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do what you need to do
}
});
If you want to add a click listener on each view, then just find the views inside the mView object and attach the listener on each one of them. That's it!
Make ImageView Object outside the function as you did for mView .
And then in the populateViewHolder just add
viewHolder.imageView.setOnClickListener()
It'll work fine Guaranteed
I have a list with articles taken from an List and want to show the selected article in a PagerActivity so the user can easily flip to the article before and after when finished reading.
In iOS I can just pass the List (or a reference) with article objects to the PagerActivity. In Android however, calling on an Intent does not allow Lists to be passed on. So what would be the best way of doing it? Do I need to reload the array in the next Activity and then pass the position as an argument to the Intent?
(Reloading the List would be expensive, but should work if the DB hasn't changed since loading, otherwise the order might be different and the wrong item might be shown).
In Android
Used ParecleObjectif you have Custom Object ArrayList and if your have simple String ArrayList then pass directly in Intent
If you have Simple String ArrayList then refer below
Passing ArrayList of string arrays from one activity to another in android
and If you have Custom Object ArrayList then refer below
How to pass ArrayList<CustomeObject> from one activity to another?
Passing arraylist of objects between activities
Considering your list of type Department here:
public class Department implements Parcelable {
int department_id;
String title;
public Department() {
this.department_id = 0;
this.title = null;
}
public Department(int department_id, String title) {
this.department_id = department_id;
this.title = title;
}
public int getDepartmentId() {
return department_id;
}
public void setDepartmentId(int department_id) {
this.department_id = department_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flag) {
parcel.writeInt(department_id);
parcel.writeString(title);
}
public static final Creator<Department> CREATOR = new Creator<Department>(){
#Override
public Department createFromParcel(Parcel parcel) {
Department department = new Department();
department.setDepartmentId(parcel.readInt());
department.setTitle(parcel.readString());
return department;
}
#Override
public Department[] newArray(int size) {
return new Department[size];
}
};
}
List<Department> departments = new ArrayList<>();
Now you simply have to put this list in Intent Bundle like this
bundle.putParcelableArrayList("Departments_KEY", departments);
and receive the list in your child activity like this
List<Department> departments = getIntent() or getArguments().getParcelable("Departments_KEY");
I have an Object that I need to pass via the Intent to another Activity via the onclick method.
I was following this answer here How to send an object from one Android Activity to another using Intents?
Which works fine however my Object has within it an Array of objects.
How do I pass this object with its Array of Objects?
Below are the classes before using Parcelable
List (the object to be passed)
public class List {
private String Name;
private ArrayList<ListItem> items;
public List(){
items = new ArrayList<ListItem>();
}
public void addItem(String title, String d, String s, int p){
ListItem i = new ListItem();
i.setDecription(d);
i.setPrice(p);
i.setSite(s);
i.setTitle(title);
items.add(i);
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getCount() {
return items.size();
}
public ArrayList<ListItem> getList(){
return items;
}
}
ListItem
public class ListItem {
private String title;
private String decription;
private String site;
private int price;
public void setTitle(String title) {
this.title = title;
}
public void setDecription(String d){
this.decription = d;
}
public void setSite(String s){
this.site = s;
}
public void setPrice(int i){
this.price = i;
}
public String getTitle(){
return title;
}
public String getDecription(){
return decription;
}
public String getSite(){
return site;
}
public int getPrice(){
return price;
}
}
So how would I use Parcelable on List to send the ArrayList as well.
THank you and if you need any more info please ask!
You're trying to pass around data that shouldn't normally be passed around. A list is an ideal candidate for an SQLite Database. Try that or another way to persist data in android: http://developer.android.com/guide/topics/data/data-storage.html
If you insist on using Parcelable:
How can I make my custom objects Parcelable?
Also don't use List as your own type, it's standard JAVA.