Simple Tutorial: Passing ArrayList across activities

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Simple Tutorial: Passing ArrayList across activities

Postby rciovati » Mon Jan 04, 2010 2:11 am

Hi guys, this is my first tutorial, I hope is not equal to an existing one.
It is quite simple but can save time to a novice.
As described in the subject code below allows you to pass an ArrayList between two activities.

First we must write the class that interests us. I wrote a simple class that represents a customer (fancy that!)

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. public class Customer {
  3.  
  4.  
  5.  
  6.         private String name;
  7.  
  8.         private String phoneNumber;
  9.  
  10.  
  11.  
  12.         public Customer(){
  13.  
  14.                
  15.  
  16.         }
  17.  
  18.        
  19.  
  20.         public Customer(String name, String phoneNumber){
  21.  
  22.                 this.name = name;
  23.  
  24.                 this.phoneNumber = phoneNumber;
  25.  
  26.         }
  27.  
  28.        
  29.  
  30.         public void setName(String name) {
  31.  
  32.                 this.name = name;
  33.  
  34.         }
  35.  
  36.  
  37.  
  38.         public String getName() {
  39.  
  40.                 return name;
  41.  
  42.         }
  43.  
  44.  
  45.  
  46.         public void setPhoneNumber(String phoneNumber) {
  47.  
  48.                 this.phoneNumber = phoneNumber;
  49.  
  50.         }
  51.  
  52.  
  53.  
  54.         public String getPhoneNumber() {
  55.  
  56.                 return phoneNumber;
  57.  
  58.         }
  59.  
  60. }
  61.  
  62.  
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


And then I wrote the class that represents the list of my clients. It inherits from ArrayList and implements the interface Parcelable. Believe that the code is quite clear, there are basically two methods, one that writes the contents of the ArrayList into a parcel and the other from a given Parcel creates the ArrayList. It was also declared an object of type Parcelable.Creator, which is called automatically when the list is "deserialized".

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package simple.test;
  3.  
  4.  
  5.  
  6. import java.util.ArrayList;
  7.  
  8.  
  9.  
  10. import android.os.Parcel;
  11.  
  12. import android.os.Parcelable;
  13.  
  14.  
  15.  
  16. public class CustomersList extends ArrayList<Customer> implements Parcelable{
  17.  
  18.  
  19.  
  20.         private static final long serialVersionUID = 663585476779879096L;
  21.  
  22.  
  23.  
  24.         public CustomersList(){
  25.  
  26.                
  27.  
  28.         }
  29.  
  30.        
  31.  
  32.         public CustomersList(Parcel in){
  33.  
  34.                 readFromParcel(in);
  35.  
  36.         }
  37.  
  38.        
  39.  
  40.         @SuppressWarnings("unchecked")
  41.  
  42.         public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
  43.  
  44.                 public CustomersList createFromParcel(Parcel in) {
  45.  
  46.                         return new CustomersList(in);
  47.  
  48.                 }
  49.  
  50.  
  51.  
  52.                 public Object[] newArray(int arg0) {
  53.  
  54.                         return null;
  55.  
  56.                 }
  57.  
  58.  
  59.  
  60.         };
  61.  
  62.        
  63.  
  64.         private void readFromParcel(Parcel in) {
  65.  
  66.                 this.clear();
  67.  
  68.  
  69.  
  70.                 //First we have to read the list size
  71.  
  72.                 int size = in.readInt();
  73.  
  74.  
  75.  
  76.                 //Reading remember that we wrote first the Name and later the Phone Number.
  77.  
  78.                 //Order is fundamental
  79.  
  80.                
  81.  
  82.                 for (int i = 0; i < size; i++) {
  83.  
  84.                         Customer c = new Customer();
  85.  
  86.                         c.setName(in.readString());
  87.  
  88.                         c.setPhoneNumber(in.readString());
  89.  
  90.                         this.add(c);
  91.  
  92.                 }
  93.  
  94.                
  95.  
  96.         }
  97.  
  98.  
  99.  
  100.         public int describeContents() {
  101.  
  102.                 return 0;
  103.  
  104.         }
  105.  
  106.  
  107.  
  108.         public void writeToParcel(Parcel dest, int flags) {
  109.  
  110.                 int size = this.size();
  111.  
  112.                 //We have to write the list size, we need him recreating the list
  113.  
  114.                 dest.writeInt(size);
  115.  
  116.                 //We decided arbitrarily to write first the Name and later the Phone Number.
  117.  
  118.                 for (int i = 0; i < size; i++) {
  119.  
  120.                         Customer c = this.get(i);
  121.  
  122.                         dest.writeString(c.getName());
  123.  
  124.                         dest.writeString(c.getPhoneNumber());
  125.  
  126.                 }
  127.  
  128.         }
  129.  
  130.        
  131.  
  132.  
  133.  
  134. }
  135.  
  136.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


and then i show you how to write the CallerActivity:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package simple.test;
  3.  
  4.  
  5.  
  6. import android.app.Activity;
  7.  
  8. import android.content.Intent;
  9.  
  10. import android.os.Bundle;
  11.  
  12.  
  13.  
  14. public class CallerActivity extends Activity {
  15.  
  16.        
  17.  
  18.     @Override
  19.  
  20.     public void onCreate(Bundle savedInstanceState) {
  21.  
  22.         super.onCreate(savedInstanceState);
  23.  
  24.         setContentView(R.layout.caller);
  25.  
  26.        
  27.  
  28.         //Create and populate the list
  29.  
  30.         CustomersList customers = new CustomersList();
  31.  
  32.         Customer c1 = new Customer("First Customer", "123456");
  33.  
  34.         Customer c2 = new Customer("Second Custimer", "7891011");
  35.  
  36.         customers.add(c1);
  37.  
  38.         customers.add(c2);
  39.  
  40.        
  41.  
  42.         Bundle b = new Bundle();
  43.  
  44.         b.putParcelable("customers", customers); //Insert list in a Bundle object
  45.  
  46.         Intent i = new Intent(this, CalledActivity.class);
  47.  
  48.         i.putExtras(b); //Insert the Bundle object in the Intent' Extras
  49.  
  50.        
  51.  
  52.         startActivity(i); //Start Activity
  53.  
  54.        
  55.  
  56.     }
  57.  
  58. }
  59.  
  60.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


and the called:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package simple.test;
  3.  
  4.  
  5.  
  6. import android.app.Activity;
  7.  
  8. import android.os.Bundle;
  9.  
  10. import android.widget.Toast;
  11.  
  12.  
  13.  
  14. public class CalledActivity extends Activity {
  15.  
  16.  
  17.  
  18.         private CustomersList customers;
  19.  
  20.        
  21.  
  22.         @Override
  23.  
  24.         protected void onCreate(Bundle savedInstanceState) {
  25.  
  26.                 super.onCreate(savedInstanceState);
  27.  
  28.                 setContentView(R.layout.called);
  29.  
  30.                
  31.  
  32.                 Bundle b = getIntent().getExtras(); //Get the intent's extras
  33.  
  34.                 customers = b.getParcelable("customers"); //get our list
  35.  
  36.                
  37.  
  38.                 Toast.makeText(this, String.valueOf(customers.size()), Toast.LENGTH_SHORT).show();
  39.  
  40.         }
  41.  
  42.  
  43.  
  44. }
  45.  
  46.  
  47.  
  48.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4


hope will be useful to someone.

Regards.
rciovati
Developer
Developer
 
Posts: 25
Joined: Mon Jan 04, 2010 12:52 am
Location: Milano (Italy)

Top

Parcel of objects

Postby rayman » Tue Jan 12, 2010 12:03 pm

This is very nice tutorial,
but what should when the object which i`am trying to parce, contains object?
here you knew you going to pass strings:
private String name;
private String phoneNumber;

if i tould you that i have objects instead, class like this:

public class Pair<A,B>
{
A first;
B second;
...
}
now i need to use the parcel to read and write those objects(A,B)
wont be able to do it this way.
this is what i tried, but no success, mybe you could help..

my PairsLists class:

public class PairsLists<A,B> extends ArrayList<Pair> implements Parcelable
{
private static final long serialVersionUID = 663585476779879096L;

public PairsLists()
{
super();
// TODO Auto-generated constructor stub
}

public PairsLists(Parcel in)
{
readFromParcel(in);

}

@SuppressWarnings("unchecked")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
{
public PairsLists createFromParcel(Parcel in)
{
return new PairsLists(in);
}

public Object[] newArray(int arg0)
{
return null;
}

};

private void readFromParcel(Parcel in)
{
this.clear();

// First we have to read the list size
int size = in.readInt();

// Reading remember that we wrote the first double and later the second
// double
// Order is fundamental

for (int i = 0; i < size; i++)
{
Pair<A,B> p = new Pair<A, B>();
p.setFirst((A) in.readString());
p.setSecond((B) in.readString());
this.add(p);
}

}

@Override
public void writeToParcel(Parcel dest, int flags)
{
int size = this.size();
dest.writeInt(size);
for (int i = 0; i < size; i++)
{
Pair<A, B> p = this.get(i);
A z1=(A) p.getFirst();
B z2=(B) p.getFirst();
dest.writeValue(p.getFirst());
dest.writeValue(p.getSecond());
}
}

@Override
public int describeContents()
{
// TODO Auto-generated method stub
return 0;
}

}

and this is my Pair<A,B> class (which supposed to be passed):
package com.idan.ParceAbleClasses;

public class Pair<A,B>
{
A first;
B second;

public Pair(A first, B second)
{
this.first=first;
this.second=second;


}

public Pair()
{
super();
// TODO Auto-generated constructor stub
}

public A getFirst()
{
return this.first;
}

public void setFirst(A first)
{
this.first = first;
}

public B getSecond()
{
return this.second;
}

public void setSecond(B second)
{
this.second = second;
}


}


Thanks,

rayman.
rayman
Junior Developer
Junior Developer
 
Posts: 12
Joined: Mon Jan 11, 2010 11:26 pm

FIXED

Postby rayman » Tue Jan 12, 2010 12:47 pm

just need to channge the in.readString();
to in.readValue(null);

:)
rayman
Junior Developer
Junior Developer
 
Posts: 12
Joined: Mon Jan 11, 2010 11:26 pm

Re: Simple Tutorial: Passing ArrayList across activities

Postby jurriens » Wed Jul 07, 2010 6:05 pm

Dear rciovati,

How should you use the in.read.... if it comes to a an array of drawables, or integers.

Thank you!
jurriens
Freshman
Freshman
 
Posts: 4
Joined: Thu Mar 04, 2010 8:33 pm

Re: Simple Tutorial: Passing ArrayList across activities

Postby asimmittal » Wed Jan 19, 2011 8:42 am

Hey,

In your example you showed a Customer class. This class consisted of data members which were essentially primitive types.

So writing them into the parcel is easy "out.writeInt" and "out.writeFloat" etc... I have a slightly different scenario. I have created an activity which downloads a bunch of images from Flickr using a Flickr RSS feed.

There is an arrayList that holds all the feed items (each item contains Strings and Bitmap objects). I'd like to pass this array list into another activity by parceling it. How do I go about doing that??

I have thought of creating a new class : class SOMECLASS extends ArrayList<FeedItem> implements Parcelable{ ... }

But in this case, how do I write the Bitmap objects using the parcel object?? If anyone has a better appraoch, i'd like to know about it
asimmittal
Developer
Developer
 
Posts: 45
Joined: Wed Jan 19, 2011 8:35 am

Re: Simple Tutorial: Passing ArrayList across activities

Postby asimmittal » Wed Jan 19, 2011 12:37 pm

[Solved]

All i had to do was:
- make my FeedItem class implement Parcelable
- Since Bitmap implements parcelable, i was able to use Bitmap.writeToParce(parcel,int)

Here is the code of feed item class after implementing parcel:
Code: Select all
package com.asim.learning;

import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;

/*
* This class constitutes a single feed item (RSS v2.0) as delivered by the
* flickr APIs.
*/
public class FeedItem implements Parcelable{
   
   public String title;         //item title
   public String pubDate;         //publishing date
   public String link;            //link to the user's page
   public String content;         //content is the link to the item's primary image
   public String thumbnail;      //link to the thumbnail image of the iteme
   public Bitmap thumbImage;      //this is the bitmap that stores the thumbnail image (may be used later)   
   
   /*
    * Class constructor - initialises all the data members
    */
   public FeedItem(){
      
      title = ""; pubDate = ""; content=""; link = "";
      thumbnail = "";
      thumbImage = null;
   }
   
   /*
    * Returns a string representation of the attributes for the object
    */
   public String getString(){
      try
      {
         String thumbContentStatus = "";
         if(thumbImage == null) thumbContentStatus = "NULL"; else thumbContentStatus = "Conent present";
         return ("\ntitle:"+title+"\nlink:"+link+"\ndate:"+pubDate+"\ncontent:"+content+"\nthumbnail:"+ thumbnail+"\nthumbImage:"+thumbContentStatus);
      }
      catch (NullPointerException e){return "NULL";}
   }

   @Override
   public int describeContents() {
      return 0;
   }
   
   //----------------------------------- Parcelable Interface ---------------------------------------
   
   public FeedItem(Parcel source){
      title = source.readString();
      pubDate = source.readString();
      link = source.readString();
      content = source.readString();
      thumbnail = source.readString();
      thumbImage = Bitmap.CREATOR.createFromParcel(source);
   }
   
   public static final Parcelable.Creator<FeedItem> CREATOR = new Parcelable.Creator<FeedItem>() {
      
      @Override
      public FeedItem createFromParcel(Parcel source) {
         return new FeedItem(source);
      }

      @Override
      public FeedItem[] newArray(int size) {
         return new FeedItem[size];
      }
   };
   
   @Override
   public void writeToParcel(Parcel dest, int flags) {
      
      dest.writeString(title);
      dest.writeString(pubDate);
      dest.writeString(link);
      dest.writeString(content);
      dest.writeString(thumbnail);
      thumbImage.writeToParcel(dest, 0);
   }   
   
   
}



After that all i had to do was create a Bundle and use the putParcelableArrayList(ArrayList<T>) method. Once the bundle was created, push it onto an intent using putExtra and start a new activity using this intent

Code: Select all
Bundle toSend = new Bundle();
      
      toSend.putParcelableArrayList("list", myAdapter.items);
      Intent launchGallery = new Intent(this,GalleryView.class);
      launchGallery.putExtras(toSend);
      startActivity(launchGallery);


On the other end, in the activity which received this intent, we should reverse the process. Use getExtra():Bundle method to get the bundle from the intent, and use the getParcelableArrayList() : ArrayList<T> method to pull out the array list of objects.
Code: Select all
Intent intent = this.getIntent();
      Bundle packet = intent.getExtras();
      ArrayList<FeedItem> items = packet.getParcelableArrayList("list");
asimmittal
Developer
Developer
 
Posts: 45
Joined: Wed Jan 19, 2011 8:35 am

Top

Re: Simple Tutorial: Passing ArrayList across activities

Postby rciovati » Thu Jan 20, 2011 7:06 pm

Thanks for sharing your solution. :)
rciovati
Developer
Developer
 
Posts: 25
Joined: Mon Jan 04, 2010 12:52 am
Location: Milano (Italy)

Re: Simple Tutorial: Passing ArrayList across activities

Postby eugenevdm » Sun Feb 27, 2011 9:30 pm

Thank you very much for posting this example.

Activities, Intents, bundles and extras are all hard concepts for me, and then when you have to suddenly transport data from one activity to the next AND you have to wrap a custom object, it becomes really complicated.

I looked high and low and couldn't find a good example where I could pass my ArrayList. Your example was perfect for me. The only difference is I don't extend ArrayList but I have a dedicated class for my collection.

Thank you!
eugenevdm
Freshman
Freshman
 
Posts: 2
Joined: Sun Feb 27, 2011 8:57 pm

Re: Simple Tutorial: Passing ArrayList across activities

Postby clivesgt » Thu Apr 14, 2011 6:42 pm

hi
just want to say that i spent 2 days trying pass an ArrayList between 2 activities. being a novice, i just could not figure it out, even after reviewing many code examples on the web. your tutorial was exactly what i was looking for! you won't understand the relief i felt after i created a project using your code and watched the arraylist data appear in the 2nd activity! THANKS A MILLION!!!
clivesgt
Freshman
Freshman
 
Posts: 2
Joined: Thu Apr 14, 2011 6:35 pm

Re: Simple Tutorial: Passing ArrayList across activities

Postby vandzi » Sat Dec 31, 2011 4:56 pm

This is way how I do it: http://vandzi.wordpress.com/2011/12/24/android-passing-objects-between-activities/
You can pass whatever kind of object
vandzi
Junior Developer
Junior Developer
 
Posts: 20
Joined: Fri Jun 11, 2010 11:31 am
Location: Slovakia

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 4 guests