Java 有意传递文件,我如何检索它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19397165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing File with intent, how do i retrieve it
提问by TooTiredToDrink
Here is what I am passing. pictureFile
is a File
这是我正在传递的内容。pictureFile
是一个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?
在下一个活动中,我使用哪个 getter 来获取它?
Intent intent = getIntent();
.....?
Intent intent = getIntent();
……?
采纳答案by Obl Tobl
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.
通过调用getExtras()
您,Intent
您将获得Bundle
.
使用get()
课堂上的正常内容,Bundle
您可以阅读Object
传递给调用的每一个Intent
. 您唯一要做的就是将其解析回class
您的对象是一个实例。
回答by Guian
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 ,如下所示:
File pictureFile = (File)getIntent.getExtras().get("picture");
It should be fine. (it use the getter for 'object'which needs a serializableobject and return it. The cast should be enough.)
应该没问题。(它使用getter 来获取需要可序列化对象并返回它的“对象”。演员表应该足够了。)
回答by ban-geoengineering
You can send it like this:
你可以这样发送:
intent.putExtra("MY_FILE", myFile);
intent.putExtra("MY_FILE", myFile);
and retrieve it like this:
并像这样检索它:
File myFile = (File)intent.getSerializableExtra("MY_FILE");
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());
intent.putExtra("MY_FILE_STRING", myFile.toString());
and retrieve/reconstruct like this:
并像这样检索/重建:
File myFile = new File(intent.getStringExtra("MY_FILE_STRING"));
File myFile = new File(intent.getStringExtra("MY_FILE_STRING"));