Passing ArrayList<Object> data using putExtra - android

im newbie on android. I need to send data from ListView with customAdapter to detailActivity that show detail's item from selected item of listView. I have seen a few post about it and i still confuse about it.
Would you help me?
This is my data class :
public class ListData {
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
}
This is my arrayList declaration :
ArrayList<ListData> data = new ArrayList<ListData>();
data.add(new ListData("Sidik Suhendar", "Telkom University"));
I don't have idea, how i can send my arraylist data to another activity. Please help me :) give me some example too :) Thanks

You need to make your base object, ListData parcelable:
public class ListData implements Parcelable {
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
#Override
public int describeContents() {
return 0;
}
public ListData(Parcel source) {
title = source.readString();
desc = source.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(desc);
}
public static final Creator<ListData> CREATOR = new Creator<ListData>(){
#Override
public ListData createFromParcel(Parcel source) {
return new ListData(source);
}
#Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
Once it is parcelable you can simply do in the first activity:
ArrayList<ListData> data = new ArrayList<ListData>();
data.add(new ListData("Sidik Suhendar", "Telkom University"));
intent.putParcelableArrayListExtra("ARRAY_LIST", data);
And you can read it in the other activity as:
ArrayList<ListData> data = (ArrayList<ListData>) getIntent().getExtras().getParcelableArrayList("ARRAY_LIST");
EDIT:
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ListData item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,DetailActivity.class);
intent.putExtra("ARRAY_ITEM", item);
startActivity(intent);
}
});
Then in the destination activity:
ListData data = (ListData) getIntent().getExtras().getParcelable("ARRAY_ITEM");

First step: ListData implements Parcelable:
public class ListData implements Parcelable {
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeString(this.desc);
}
protected ListData(Parcel in) {
this.title = in.readString();
this.desc = in.readString();
}
public static final Parcelable.Creator<ListData> CREATOR = new Parcelable.Creator<ListData>() {
#Override
public ListData createFromParcel(Parcel source) {
return new ListData(source);
}
#Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
Second step:send data:
ArrayList<ListData> data = new ArrayList<ListData>();
data.add(new ListData("Sidik Suhendar", "Telkom University"));
Intent intent = new Intent(this, TargetActivity.class);
intent.putParcelableArrayListExtra("data",data);
Third step:receive data
ArrayList<ListData> data = intent.getParcelableArrayListExtra("data");

Related

how to send list object with list in it through parcelable

I'm not able to get list object which has another list in it through parcelable to another activity. Below is my code.
SnipDataEvents.java
public class SnipDataEvents implements Parcelable {
private String title,image,language,bookingUrl,infoUrl,genre;
private List<Venues> venuesList;
public SnipDataEvents(String title,String image,String language,String genre,String bookingUrl,String infoUrl,List<Venues> list){
venuesList = new ArrayList<>();
venuesList.addAll(list);
this.title = title;
this.image = image;
this.language = language;
this.genre = genre;
this.bookingUrl = bookingUrl;
this.infoUrl = infoUrl;
this.venuesList = list;
}
protected SnipDataEvents(Parcel in) {
title = in.readString();
image = in.readString();
language = in.readString();
bookingUrl = in.readString();
infoUrl = in.readString();
genre = in.readString();
in.readTypedList(getVenuesList(),Venues.CREATOR);
}
public static final Creator<SnipDataEvents> CREATOR = new Creator<SnipDataEvents>() {
#Override
public SnipDataEvents createFromParcel(Parcel in) {
return new SnipDataEvents(in);
}
#Override
public SnipDataEvents[] newArray(int size) {
return new SnipDataEvents[size];
}
};
public String getImage() {
return image;
}
public String getTitle() {
return title;
}
public List<Venues> getVenuesList() {
return venuesList;
}
public String getBookingUrl() {
return bookingUrl;
}
public String getGenre() {
return genre;
}
public String getInfoUrl() {
return infoUrl;
}
public String getLanguage() {
return language;
}
public void setVenuesList(List<Venues> venuesList) {
this.venuesList = venuesList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
parcel.writeString(image);
parcel.writeString(language);
parcel.writeString(bookingUrl);
parcel.writeString(infoUrl);
parcel.writeString(genre);
parcel.writeTypedList(venuesList);
}
}
Venues.java
public class Venues implements Parcelable {
private String name;
//private List<String> showTimes;
public Venues(String name, List<String> showTimes) {
//showTimes = new ArrayList<>();
this.name = name;
//this.showTimes = showTimes;
}
protected Venues(Parcel in) {
name = in.readString();
//showTimes = in.createStringArrayList();
}
public static final Creator<Venues> CREATOR = new Creator<Venues>() {
#Override
public Venues createFromParcel(Parcel in) {
return new Venues(in);
}
#Override
public Venues[] newArray(int size) {
return new Venues[size];
}
};
public String getName() {
return name;
}
//public List<String> getShowTimes() {
// return showTimes;
// }
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
}
}
MainActivity.java
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("snipdataevents",(ArrayList<SnipDataEvents>)snipDataEvents);
intent.putExtras(bundle);
startActivity(intent);
DetailActivity.java
Bundle bundle = getIntent().getExtras();
snipDataEvents = bundle.getParcelableArrayList("snipdataevents");
when I run the code ,in DetailActivity.java bundle.getParcelableArrayList("snipdataevents") returns null
when I removed this
in.readTypedList(getVenuesList(),Venues.CREATOR);
and
parcel.writeTypedList(venuesList);
aboves lines in SnipDataEvents.java
then run, bundle.getParcelableArrayList("snipdataevents") returns list.
I don't know whats wrong with the code...
Can anyone please help??
You can done this one by Passing ArrayList in form of String.
Add implementation 'com.google.code.gson:gson:2.8.4' in dependencies block build.gradle.
Click on Sync Project with Gradle Files
SnipDataEvents.java
public class SnipDataEvents {
private String title, image, language, bookingUrl, infoUrl, genre;
private List<Venues> venuesList;
public SnipDataEvents(String title, String image, String language, String genre, String bookingUrl, String infoUrl, List<Venues> list) {
venuesList = new ArrayList<>();
venuesList.addAll(list);
this.title = title;
this.image = image;
this.language = language;
this.genre = genre;
this.bookingUrl = bookingUrl;
this.infoUrl = infoUrl;
this.venuesList = list;
}
public String getImage() {
return image;
}
public String getTitle() {
return title;
}
public List<Venues> getVenuesList() {
return venuesList;
}
public void setVenuesList(List<Venues> venuesList) {
this.venuesList = venuesList;
}
public String getBookingUrl() {
return bookingUrl;
}
public String getGenre() {
return genre;
}
public String getInfoUrl() {
return infoUrl;
}
public String getLanguage() {
return language;
}
}
Venues.java
public class Venues {
private String name;
public Venues(String name, List<String> showTimes) {
this.name = name;
}
public String getName() {
return name;
}
}
MainActivity.java
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putExtra("snipdataevents", new Gson().toJson(snipDataEvents));
intent.putExtras(bundle);
startActivity(intent);
DetailActivity.java
String json = getIntent().getStringExtra("snipdataevents");
snipDataEvents = Arrays.asList(new Gson().fromJson(json, SnipDataEvents[].class))

Put serializable into intent not working

I put in intent my object with following code (while putting list does exists, I checked in debugger)
Intent intent = new Intent(getApplicationContext(), ProductActivity.class);
intent.putExtra("product", CategoryActivity.this.list.get(position));
startActivity(intent);
And then retrive
Intent intent = getIntent();
product = (Product) intent.getSerializableExtra("product");
But it is null
Model class is following
public class Product implements Serializable {
Integer pk;
String name;
String description;
Integer price;
String image_url;
List<Option> options;
public Product(Integer pk, String name, String description, Integer price, String image_url, List<Option> options) {
this.pk = pk;
this.name = name;
this.description = description;
this.price = price;
this.image_url = image_url;
this.options = options;
}
public Integer getPk() {
return pk;
}
public void setPk(Integer pk) {
this.pk = pk;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
}
What am I doing wrong ?
You have to add more code to use your class inside intent data.
import android.os.Parcel;
import android.os.Parcelable;
public class Yourclass implements Parcelable {
//your code
#Override
public void writeToParcel(Parcel out, int flags) {
//e.g.
out.writeInt(this.getWhat());
//similar code
}
#Override
public int describeContents() {
return 0;
}
private YourClass(Parcel in) {
//e.g.
this.setWhat(in.readInt());
}
public static final Parcelable.Creator<YourClass> CREATOR
= new Parcelable.Creator<YourClass>() {
public YourClass createFromParcel(Parcel in) {
return new YourClass(in);
}
public YourClass[] newArray(int size) {
return new YourClass[size];
}
};
}
to store use intent.putExtra(EXTRANAME, obj); to retrieve use YourClass myObj = (YourClass) getIntent().getParcelableExtra(EXTRANAME);

Android use Intent to send a list of Parcelable objects which contain a list of another Parcelable objects

In my Android app, I want to use Intent to pass a list of SingleGroup to another Activity where each SingleGroup object contains a list of SingleImage, here are class for SingleImage and SingleGroup:
public class SingleImage implements Parcelable{
public String name;
public int drawableId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDrawableId() {
return drawableId;
}
public void setDrawableId(int drawableId) {
this.drawableId = drawableId;
}
public SingleImage(String name, int drawableId)
{
this.name = name;
this.drawableId = drawableId;
}
public static final Parcelable.Creator<SingleImage> CREATOR
= new Parcelable.Creator<SingleImage>()
{
public SingleImage createFromParcel(Parcel in)
{
return new SingleImage(in);
}
public SingleImage[] newArray(int size)
{
return new SingleImage[size];
}
};
private SingleImage(Parcel in)
{
name = in.readString();
drawableId = in.readInt();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(drawableId);
}
}
Here is SingleGroup class:
public class SingleGroup implements Parcelable{
private static final String TAG = "SINGLEGROUP";
private ArrayList<SingleImage> images = new ArrayList<SingleImage>(0);
private String myTitle;
private String groupDesc;
public SingleGroup(String mTitle, String desc, ArrayList<SingleImage> imagesList) {
this.myTitle = mTitle;
this.groupDesc = desc;
this.images = imagesList;
}
public String getGroupDesc() {
return groupDesc;
}
public String getMyTitle() {
return myTitle;
}
public void setMyTitle(String myTitle) {
this.myTitle = myTitle;
}
public ArrayList<SingleImage> getImages() {
return images;
}
public void setImages(ArrayList<SingleImage> images) {
this.images = images;
}
public static final Parcelable.Creator<SingleGroup> CREATOR
= new Parcelable.Creator<SingleGroup>()
{
public SingleGroup createFromParcel(Parcel in)
{
return new SingleGroup(in);
}
public SingleGroup[] newArray(int size)
{
return new SingleGroup[size];
}
};
private SingleGroup(Parcel in)
{
myTitle = in.readString();
groupDesc = in.readString();
//problem maybe here
in.readTypedList(images,SingleImage.CREATOR);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(myTitle);
dest.writeString(groupDesc);
//problem maybe here
dest.writeTypedList(images);
}
#Override
public String toString() {
String result = "myTitle "+myTitle+" desc "+ groupDesc + " imagesize "+images.size();
return result;
}
}
It works ok when calling to pass ArrayList<SingleImage> through Intent,
while when I called to pass ArrayLlist<SingleGroup> through Intent I got error:
Parcel android.os.Parcel#3c4c6743: Unmarshalling unknown type code
3211379 at offset 224
Any idea? Thanks in advance
---------------- Update ----------------
I have changed in.readTypedList(images, null); to in.readTypedList(images, SingleImage.CREATOR); but it still not working. same unmarshalling error
---------------- Problem Solved --------------
Thanks to Keita. The real problem is not actually listed in my code. When I passing the parcelable object, I should also include some other attributes which I missed.
Strongly recommend AS plugin Android Parcelable code generator
You must be pass SingleImage.CREATOR into method readTypedList instead of "null" value
private SingleGroup(Parcel in)
{
myTitle = in.readString();
groupDesc = in.readString();
//problem maybe here
in.readTypedList(images, SingleImage.CREATOR);
}
Try this one. That is what i always do and it work:
private SingleGroup(Parcel in)
{
myTitle = in.readString();
groupDesc = in.readString();
//problem maybe here
in.createTypedArrayList(SingleImage.CREATOR);
}
ArrayList is serialize. So try to this
public class SingleImage implements Serializable{
....
}
Refer this: ArrayList Android Documentation

What is the correct way of creating a parcelable?

I have created the following parcelable object:
public class ViewModel implements Parcelable {
private String image, price, credit, title, description, id;
public ViewModel(String image, String price, String credit, String title, String description, String id) {
this.image = image;
this.price = price;
this.credit = credit;
this.title = title;
this.description = description;
this.id = id;
}
public String getPrice() {
return price;
}
public String getCredit() {
return credit;
}
public String getDescription() {
return description;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getImage() {
return image;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {
this.image,
this.price,
this.credit,
this.title,
this.description,
this.id
});
}
/** Static field used to regenerate object, individually or as arrays */
public static final Parcelable.Creator<ViewModel> CREATOR = new Parcelable.Creator<ViewModel>() {
public ViewModel createFromParcel(Parcel pc) {
return new ViewModel(pc);
}
public ViewModel[] newArray(int size) {
return new ViewModel[size];
}
};
/**Creator from Parcel, reads back fields IN THE ORDER they were written */
public ViewModel(Parcel pc){
image = pc.readString();
price = pc.readString();
credit = pc.readString();
title = pc.readString();
description = pc.readString();
id = pc.readString();
}
}
Now I am sending an ArrayList of ViewModel through bundle:
bundle.putParcelableArrayList("products", viewModels);
Is there anything wrong I am doing? Because I get null Bundle Arguments, but if I send a simple string, everything works.
make this change:
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.image);
dest.writeString(this.price);
dest.writeString(this.credit);
dest.writeString(this.title);
dest.writeString(this.description);
dest.writeString(this.id);
}
getIntent().getParcelableArrayListExtra("product"); // get the list
You are trying to retrieve a parcelable ArrayList. You need to retrive a parcelable ViewModel object that you created. Change:
bundle.putParcelableArrayList("product", viewModels);
and
getIntent().getParcelableArrayList("product");
to:
bundle.putParcelable("product", viewModels);
and
getIntent().getParcelable("product");

Casting Object[] to custom Item[]

I have my ArrayList
ArrayList<Item> itemList = new ArrayList<Item>();
It is then populated with Items.
Later on, I want to access the items attributes in a loop to get data but
Item[] itemArr = (Item[]) itemList.toArray();
This gives me error:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to com.raynemartin.SAAndroidAppCompetition.Item[]
If this is destined to fail, how else can I access attributes of Items?
The Items are in an ArrayList so they can populate and android ListView. Now I want to sort the ArrayList, but need to access the .getRating() method of my Item class.
Item[] itemArr= (Item[])itemList.toArray();
for(int i =0;i<itemArr.length;i++){
for(int j=i;i<itemArr.length;j++){
if(itemArr[j].getRating()>itemArr[i].getRating()){
Item temp = itemArr[j];
itemArr[j] = itemArr[i];
itemArr[i] = temp;
}
}
}
}
EDIT - here is item class code
public class Item {
private String title;
private String category;
private String downloads;
private double rating;
private Bitmap icon;
public Item(String title, String category, String downloads,double rating,Bitmap icon) {
this.title = title;
this.category = category;
this.downloads = downloads;
this.icon = icon;
this.rating = rating;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDownloads() {
return downloads;
}
public void setDownloads(String downloads) {
this.downloads = downloads;
}
public Bitmap getIcon() {
return icon;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}
To sort you can try the below.
In your Item class implement toString
public String toString()
{
return String.valueOf(rating);
}
Implement a Comparator
class SortingRating implements Comparator<Item>
{
#Override
public int compare(Item arg0, Item arg1) {
if (arg0.getRating() < arg1.getRating()) return -1;
if (arg0.getRating() > arg1.getRating()) return 1;
return 0;
}
}
Then sort your list
Collections.sort(itemList, new SortingRating());
Example : Correct me if i am wrong.
public class MainClass {
static ArrayList<Item> aa = new ArrayList<Item>();
public static void main(String[] args) {
Item i1 = new Item("soap","sales","yes",4.0);
aa.add(i1);
Item i2 = new Item("soap","sales","yes",5.2);
aa.add(i2);
Item i3 = new Item("soap","sales","yes",3.8);
aa.add(i3);
Item i4 = new Item("soap","sales","yes",5.1);
aa.add(i4);
Collections.sort(aa, new SortingRating());
for(int i=0;i<aa.size();i++)
{
System.out.println("Title : " +aa.get(i).getTitle()+"--"+"Category : "+aa.get(i).getCategory()+"--"+"Downlaods : "+aa.get(i).getDownloads()+"--"+"Rating : "+aa.get(i).getRating());
}
}
}
class SortingRating implements Comparator<Item>
{
#Override
public int compare(Item arg0, Item arg1) {
if (arg0.getRating() < arg1.getRating()) return -1;
if (arg0.getRating() > arg1.getRating()) return 1;
return 0;
}
}
Item class. Left out Bitmap icon
public class Item {
private String title;
private String category;
private String downloads;
private double rating;
public Item(String title, String category, String downloads,double rating) {
this.title = title;
this.category = category;
this.downloads = downloads;
this.rating = rating;
}
public String toString()
{
return String.valueOf(rating);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDownloads() {
return downloads;
}
public void setDownloads(String downloads) {
this.downloads = downloads;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}
Output
Title : soap--Category : sales--Downlaods : yes--Rating : 3.8
Title : soap--Category : sales--Downlaods : yes--Rating : 4.0
Title : soap--Category : sales--Downlaods : yes--Rating : 5.1
Title : soap--Category : sales--Downlaods : yes--Rating : 5.2
Let the class Item implement the interface Comparable and use
Collections.sort(itemList);
to sort your collection. So you don't have to construct an array and sort it yourself.
If you really need to access the elements as an array you would be better using
itemList.toArray(new Item[0]);
or
itemList.toArray(new Item[itemList.size()]);
as this will give you an array of type Item rather than an array of object. There is lots of discussion on this issue else where on the web.

Categories

Resources