如何使用 Intent 将对象从一个 Android Activity 发送到另一个?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2139134/
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-20 04:42:19  来源:igfitidea点击:

How to send an object from one Android Activity to another using Intents?

androidandroid-intentandroid-activity

提问by UMAR

How can I pass an object of a custom type from one Activityto another using the putExtra()method of the class Intent?

如何使用类Intent的方法将自定义类型的对象从一个Activity传递到另一个ActivityputExtra()

采纳答案by UMAR

the most easiest solution i found is.. to create a class with static data members with getters setters.

我发现的最简单的解决方案是.. 使用 getter setter 创建一个带有静态数据成员的类。

set from one activity and get from another activity that object.

从一个活动设置并从另一个活动获取该对象。

activity A

活动A

mytestclass.staticfunctionSet("","",""..etc.);

activity b

活动b

mytestclass obj= mytestclass.staticfunctionGet();

回答by Jeremy Logan

If you're just passing objects around then Parcelablewas designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAYfaster).

如果您只是传递对象,那么Parcelable就是为此而设计的。它需要多一点努力,使用比使用Java的本机序列,但它的方式更快(我的意思是这样,WAY更快)。

From the docs, a simple example for how to implement is:

从文档中,如何实现的一个简单示例是:

// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
    private int mData;

    /* everything below here is for implementing Parcelable */

    // 99.9% of the time you can just ignore this
    @Override
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };

    // example constructor that takes a Parcel and gives you an object populated with it's values
    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).

请注意,如果您有多个字段要从给定的 Parcel 中检索,您必须按照放入它们的相同顺序执行此操作(即采用 FIFO 方法)。

Once you have your objects implement Parcelableit's just a matter of putting them into your Intentswith putExtra():

一旦您实现Parcelable了对象,只需使用putExtra()将它们放入您的Intent即可

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

Then you can pull them back out with getParcelableExtra():

然后你可以用getParcelableExtra()把它们拉回来:

Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");

If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:

如果您的对象类实现了 Parcelable 和 Serializable,那么请确保您强制转换为以下之一:

i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);

回答by dxh

You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.

您需要将对象序列化为某种字符串表示形式。一种可能的字符串表示形式是 JSON,如果你问我,在 android 中与 JSON 进行序列化的最简单方法之一是通过Google GSON

In that case you just put the string return value from (new Gson()).toJson(myObject);and retrieve the string value and use fromJsonto turn it back into your object.

在这种情况下,您只需将字符串返回值放入(new Gson()).toJson(myObject);并检索字符串值并用于fromJson将其转换回您的对象。

If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.

但是,如果您的对象不是很复杂,那么开销可能不值得,您可以考虑传递对象的单独值。

回答by Sridhar

You can send serializable object through intent

您可以通过意图发送可序列化对象

// send where details is object
ClassName details = new ClassName();
Intent i = new Intent(context, EditActivity.class);
i.putExtra("Editing", details);
startActivity(i);


//receive
ClassName model = (ClassName) getIntent().getSerializableExtra("Editing");

And 

Class ClassName implements Serializable {
} 

回答by Peter Ajtai

For situations where you know you will be passing data within an application, use "globals" (like static Classes)

对于您知道将在应用程序中传递数据的情况,请使用“全局变量”(如静态类)

Hereis what Dianne Hackborn(hackbod - a Google Android Software Engineer) had to say on the matter:

以下DianneHackborn(hackbod - Google Android 软件工程师)对此事的看法:

For situations where you know the activities are running in the same process, you can just share data through globals. For example, you could have a global HashMap<String, WeakReference<MyInterpreterState>>and when you make a new MyInterpreterState come up with a unique name for it and put it in the hash map; to send that state to another activity, simply put the unique name into the hash map and when the second activity is started it can retrieve the MyInterpreterState from the hash map with the name it receives.

对于您知道活动在同一进程中运行的情况,您可以通过全局变量共享数据。例如,您可以有一个全局HashMap<String, WeakReference<MyInterpreterState>>变量,当您创建一个新的 MyInterpreterState 时,会为它提供一个唯一的名称并将其放入哈希映射中;要将该状态发送到另一个活动,只需将唯一名称放入哈希映射中,当第二个活动启动时,它可以使用它收到的名称从哈希映射中检索 MyInterpreterState。

回答by Pedro Rom?o

Your class should implements Serializable or Parcelable.

你的类应该实现 Serializable 或 Parcelable。

public class MY_CLASS implements Serializable

Once done you can send an object on putExtra

完成后,您可以在 putExtra 上发送一个对象

intent.putExtra("KEY", MY_CLASS_instance);

startActivity(intent);

To get extras you only have to do

要获得额外服务,您只需要做

Intent intent = getIntent();
MY_CLASS class = (MY_CLASS) intent.getExtras().getSerializable("KEY");

If your class implements Parcelable use next

如果您的类实现 Parcelable 使用下一步

MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");

I hope it helps :D

我希望它有帮助:D

回答by Sam

Short answer for fast need

快速需求的简短回答

1. Implement your Class to Serializable.

1. 将您的类实现为可序列化。

If you have any inner Classes don't forget to implement them to Serializable too!!

如果您有任何内部类,请不要忘记将它们也实现为 Serializable !!

public class SportsData implements  Serializable
public class Sport implements  Serializable

List<Sport> clickedObj;

2. Put your object into Intent

2. 将你的对象放入 Intent

 Intent intent = new Intent(SportsAct.this, SportSubAct.class);
            intent.putExtra("sport", clickedObj);
            startActivity(intent);

3. And receive your object in the other Activity Class

3.并在另一个活动类中接收您的对象

Intent intent = getIntent();
    Sport cust = (Sport) intent.getSerializableExtra("sport");

回答by Vlad

if your object class implements Serializable, you don't need to do anything else, you can pass a serializable object.
that's what i use.

如果你的对象类实现了Serializable,你不需要做任何其他事情,你可以传递一个可序列化的对象。
这就是我使用的。

回答by Ishan Fernando

implement serializable in your class

在你的类中实现可序列化

public class Place implements Serializable{
        private int id;
        private String name;

        public void setId(int id) {
           this.id = id;
        }
        public int getId() {
           return id;
        }
        public String getName() {
           return name;
        }

        public void setName(String name) {
           this.name = name;
        }
}

Then you can pass this object in intent

然后你可以在意图中传递这个对象

     Intent intent = new Intent(this, SecondAct.class);
     intent.putExtra("PLACE", Place);
     startActivity(intent);

int the second activity you can get data like this

在第二个活动中,您可以获得这样的数据

     Place place= (Place) getIntent().getSerializableExtra("PLACE");

But when the data become large,this method will be slow.

但是当数据变大时,这种方法会很慢。

回答by Nikhil Agrawal

There are couple of ways by which you can access variables or object in other classes or Activity.

您可以通过多种方式访问​​其他类或活动中的变量或对象。

A. Database

A. 数据库

B. shared preferences.

B. 共享偏好。

C. Object serialization.

C. 对象序列化。

D. A class which can hold common data can be named as Common Utilities it depends on you.

D. 可以保存公共数据的类可以命名为公共实用程序,这取决于您。

E. Passing data through Intents and Parcelable Interface.

E. 通过 Intents 和 Parcelable 接口传递数据。

It depend upon your project needs.

这取决于您的项目需求。

A. Database

A.数据库

SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.

SQLite 是一个嵌入到 Android 中的开源数据库。SQLite 支持标准的关系数据库功能,如 SQL 语法、事务和准备好的语句。

Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html

教程 -- http://www.vogella.com/articles/AndroidSQLite/article.html

B. Shared Preferences

B.共享偏好

Suppose you want to store username. So there will be now two thing a KeyUsername, ValueValue.

假设您要存储用户名。所以现在会有两个东西,一个关键用户名,一个值。

How to store

如何储存

 // Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
 //now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();
 //put your value
 editor.putString("userName", "stackoverlow");

 //commits your edits
 editor.commit();

Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.

使用 putString(),putBoolean(),putInt(),putFloat(),putLong() 你可以保存你想要的数据类型。

How to fetch

如何获取

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

http://developer.android.com/reference/android/content/SharedPreferences.html

http://developer.android.com/reference/android/content/SharedPreferences.html

C. Object Serialization

C.对象序列化

Object serlization is used if we want to save an object state to send it over network or you can use it for your purpose also.

如果我们想保存对象状态以通过网络发送它,或者您也可以将其用于您的目的,则使用对象序列化。

Use java beans and store in it as one of his fields and use getters and setter for that

使用 java bean 并将其作为他的字段之一存储在其中,并为此使用 getter 和 setter

JavaBeans are Java classes that have properties. Think of properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

JavaBean 是具有属性的 Java 类。将属性视为私有实例变量。由于它们是私有的,因此可以从类外部访问它们的唯一方法是通过类中的方法。更改属性值的方法称为 setter 方法,检索属性值的方法称为 getter 方法。

public class VariableStorage implements Serializable  {

    private String inString ;

    public String getInString() {
        return inString;
    }

    public void setInString(String inString) {
        this.inString = inString;
    }


}

Set the variable in you mail method by using

通过使用在您的邮件方法中设置变量

VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);

Then use object Serialzation to serialize this object and in your other class deserialize this object.

然后使用对象序列化来序列化这个对象,并在你的其他类中反序列化这个对象。

In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

在序列化中,对象可以表示为字节序列,其中包括对象的数据以及有关对象类型和存储在对象中的数据类型的信息。

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

序列化对象写入文件后,可以从文件中读取并反序列化,即表示对象及其数据的类型信息和字节可用于在内存中重新创建对象。

If you want tutorial for this refer this link

如果您需要此教程,请参阅此链接

http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html

http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html

Get variable in other classes

获取其他类中的变量

D. CommonUtilities

D.公用事业

You can make a class by your self which can contain common data which you frequently need in your project.

您可以自己创建一个类,其中包含您在项目中经常需要的常用数据。

Sample

样本

public class CommonUtilities {

    public static String className = "CommonUtilities";

}

E. Passing Data through Intents

E.通过 Intent 传递数据

Please refer this tutorial for this option of passing data.

有关传递数据的选项,请参阅本教程。

http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/

http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/

回答by om252345

You can use android BUNDLE to do this.

您可以使用 android BUNDLE 来执行此操作。

Create a Bundle from your class like:

从您的班级创建一个 Bundle,例如:

public Bundle toBundle() {
    Bundle b = new Bundle();
    b.putString("SomeKey", "SomeValue");

    return b;
}

Then pass this bundle with INTENT. Now you can recreate your class object by passing bundle like

然后用 INTENT 传递这个包。现在您可以通过传递 bundle 来重新创建您的类对象

public CustomClass(Context _context, Bundle b) {
    context = _context;
    classMember = b.getString("SomeKey");
}

Declare this in your Custom class and use.

在您的自定义类中声明并使用。