将任意类型的数组从一个活动传递到另一个活动
我正在测试 putExtras() 方法,当我使用适当的键设置数组并使用 get 方法从被调用的活动获取它时,它工作得非常好。但是,我注意到其他类型是不可能的,或者至少它没有给我一个选择,以防您想知道我在这里谈论的是我所指的代码:
Bundle b =new Bundle();
b.putStringArray(key, array);
Intent i =new Intent(context, secondActivity);
i.putExtras(b);
StartActivity(i);
并获取数组来自另一个类的简单说明:
Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);
请注意此处的“key”字符串变量,它是唯一可以标识您所请求的数组的变量,因此两侧必须相同。
现在这段代码工作得很好,但是我试图传递一个 File 类型的数组和另一个 Option 类型的数组。
你知道在这些情况下我该怎么做吗?
先感谢您。
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.putExtras(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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用接受
Serialized
的Intent.putExtra()
方法的重载版本来完成此操作。这是可能的,因为File
实现了Serializable
并且 Java 数组也是可序列化的。然后您可以使用Intent.getSerializedExtra()
方法获取该数组。如果您想将
File[]
放入Bundle
中,您可以使用Bundle.putSerialized()
和Bundle.getSerialized()方法。
You can do it using the overloaded version of
Intent.putExtra()
method that acceptsSerializable
. That's possible becauseFile
implementsSerializable
and Java arrays are serializable too. Then you can get this array usingIntent.getSerializableExtra()
method.If you want to put
File[]
toBundle
you can useBundle.putSerializable()
andBundle.getSerializable()
methods.根据我对 Android 的理解,只允许使用包传递原始类型。您不能传递自定义对象。所以有很多方法可以解决这个问题。一种快速而混乱的解决方案是将文件数组作为静态变量检索。所以你可以做类似
SomeActivity.fileArray
但是,我不推荐这种方法,只是展示一个简单的例子......或者你可以将你的对象序列化为一些原始类型(json字符串)然后反序列化在您想要使用它的活动中。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.