14

Here is what I am passing. pictureFile is a File

Intent intent = new Intent (context, ShowPicActivity.class);
intent.putExtra("picture", pictureFile);

In the next activity which one of the getters do I use to get it?

Intent intent = getIntent(); .....?

dsuma
  • 1,000
  • 2
  • 9
  • 30
  • Do not pass File object. You better pass URI to that file. – Leonidos Oct 16 '13 at 07:17
  • 1
    Have you seen anywhere in android sdk someone passed/returned File object via Intent? URI is the android way to do this. I'll try to find an article why you shouldn't do this. – Leonidos Oct 16 '13 at 07:31
  • Ok thank you, If it's the best way I will do it that way then! I just want to know why! – dsuma Oct 16 '13 at 07:36
  • 3
    because File is more than just a refence to a resource. When you pass object via intent a new copy will be created and I'm not sure that the copy of File will be viable in all use cases. If you need to pass a referense use URI, if you need to share File object inside your app share it some other way without serializing. – Leonidos Oct 16 '13 at 10:26

3 Answers3

14

File implements serializable ( first thing to check to send an object through an intent. ) ( source )

so you can do it, just cast the resulting object to File like this :

File pictureFile = (File)getIntent.getExtras().get("picture");

It should be fine. (it use the getter for 'object' which needs a serializable object and return it. The cast should be enough.)

Guian
  • 4,563
  • 4
  • 34
  • 54
9

Try the following:

YourPictureClass picture = (YourPictureClass)getIntent().getExtras().get("picture");

By calling getExtras() in your Intent you get an instance of Bundle.
With the normal get() in class Bundle you can read every Object you pass to the calling Intent. The only thing you have to do is to parse it back to the class your object is an instance of.  

Obl Tobl
  • 5,604
  • 8
  • 41
  • 65
8

You can send it like this:

intent.putExtra("MY_FILE", myFile);

and retrieve it like this:

File myFile = (File)intent.getSerializableExtra("MY_FILE");

However, it may be better (anyone?) to send the file as a string reference, in which case you could send as:

intent.putExtra("MY_FILE_STRING", myFile.toString());

and retrieve/reconstruct like this:

File myFile = new File(intent.getStringExtra("MY_FILE_STRING"));

ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253