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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:48:21  来源:igfitidea点击:

Passing File with intent, how do i retrieve it

javaandroidandroid-intent

提问by TooTiredToDrink

Here is what I am passing. pictureFileis 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 Intentyou get an instance of Bundle.
With the normal get()in class Bundleyou can read every Objectyou pass to the calling Intent. The only thing you have to do is to parse it back to the classyour 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"));