开发者

Pass array of ANY type from one activity to another

I was testing the putExtras() method and it works perfectly well when I set my array with the appropriate key and get it from the called activity using the get method. However, I noticed that it wasn't possible of other types or at least it didn't gave me an option, in case you were wondering what I was talking about here is the code that I am referring to:

Bundle b =new Bundle();  
b.putStringArray(key, array);
Intent i =new Intent(context, secondActivity);
i.putE开发者_JS百科xtras(b);
StartActivity(i);

and to get the array from another class simply:

Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);

Notice the "key" string variable here, it is the only thing that will identify the array you are requesting so it has to be the same on both sides.

Now this code works perfectly well however I am trying to pass an array of type File and another one of type Option.

Do you know how I can do it in these cases?

Thank you in advance.


You can do it using the overloaded version of Intent.putExtra() method that accepts Serializable. That's possible because File implements Serializable and Java arrays are serializable too. Then you can get this array using Intent.getSerializableExtra() method.

If you want to put File[] to Bundle you can use Bundle.putSerializable() and Bundle.getSerializable() methods.


From my understanding of Android you are only allowed to pass primitive types using bundles. You cannot pass custom objects. So there are many ways of going about this. One quick and messy solution can be to retrieve the file array as a static variable. So you can do something like SomeActivity.fileArray However, I wouldn't recommend this method, just showing a simple example... Or you can serialize your object as some primitive type (json string) then deserialize it in the activity you want to use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜