How can I pass an object of a custom type from one Activity to another using the putExtra()
method of the class Intent?
如何使用类意图的putExtra()方法将自定义类型的对象从一个活动传递到另一个活动?
31 个解决方案
#1
669
If you're just passing objects around then Parcelable was 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, WAY faster).
如果你只是传递对象,那么Parcelable就是为这个设计的。它比使用Java的本地序列化需要更多的努力,但是它的速度更快(而且我的意思是更快)。
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).
注意,如果您有多个字段从一个给定的包中检索,那么您必须按照您将它们放入(即,在FIFO方法中)的顺序来执行。
Once you have your objects implement Parcelable
it's just a matter of putting them into your Intents with putExtra():
一旦你让你的对象实现了Parcelable,它只是将它们放入你的意图和putExtra():
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);
#2
152
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进行序列化的最简单方法之一是通过谷歌GSON。
In that case you juse put the string return value from (new Gson()).toJson(myObject);
and retrieve the string value and use fromJson
to turn it back into your object.
在这种情况下,juse将字符串返回值(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.
但是,如果对象不是很复杂,那么它可能不值得开销,您可以考虑将对象的单独值传递给它。
#3
139
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 {
}
#4
62
For situations where you know you will be passing data within an application, use "globals" (like static Classes)
对于您知道将在应用程序中传递数据的情况,可以使用“全局变量”(比如静态类)
Here is what Dianne Hackborn (hackbod - a Google Android Software Engineer) had to say on the matter:
下面是Dianne Hackborn (hackbod,一个谷歌的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
>,当您创建一个新的myexplain terstate时,为它创建一个惟一的名称并将其放入散列映射中;要将该状态发送到另一个活动,只需将唯一的名称放入散列映射中,当第二个活动启动时,它可以从哈希映射中获取其接收的名称的my解释器状态。 ,>
#5
46
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使用next。
MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");
I hope it helps :D
我希望它有帮助:D。
#6
27
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,您不需要做任何其他事情,您可以传递一个可序列化的对象。这就是我使用。
#7
17
Short answer for fast need
简短的回答,快速的需要。
1. Implement your Class to implements Serializable.
1。实现您的类来实现Serializable。
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 to Intent
2。把你的目标放在目的上。
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");
#8
16
You can use android BUNDLE to do this.
你可以用android BUNDLE做这个。
Create a Bundle from your class like:
从您的类中创建一个包,例如:
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
然后将这个捆绑包与意图一起传递。现在您可以通过传递类似的包来重新创建类对象。
public CustomClass(Context _context, Bundle b) {
context = _context;
classMember = b.getString("SomeKey");
}
Declare this in your Custom class and use.
在您的自定义类中声明这个并使用。
#9
15
Thanks for parcelable help but i found one more optional solution
感谢parcelable的帮助,但我找到了一个可选的解决方案。
public class getsetclass implements Serializable {
private int dt = 10;
//pass any object, drwabale
public int getDt() {
return dt;
}
public void setDt(int dt) {
this.dt = dt;
}
}
In Activity One
在活动
getsetclass d = new getsetclass ();
d.setDt(50);
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("hashmapkey", d);
Intent inew = new Intent(SgParceLableSampelActivity.this,
ActivityNext.class);
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
inew.putExtras(b);
startActivity(inew);
Get Data In Activity 2
获取活动2中的数据。
try { setContentView(R.layout.main);
Bundle bn = new Bundle();
bn = getIntent().getExtras();
HashMap<String, Object> getobj = new HashMap<String, Object>();
getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
getsetclass d = (getsetclass) getobj.get("hashmapkey");
} catch (Exception e) {
Log.e("Err", e.getMessage());
}
#10
14
There are couple of ways by which you can access variables or object in other classes or Activity.
有几种方法可以在其他类或活动中访问变量或对象。
A. Database
答:数据库
B. shared preferences.
共同的喜好。
C. Object serialization.
对象序列化。
D. A class which can hold common data can be named as Common Utilities it depends on you.
可以保存公共数据的类可以被命名为它依赖于您的公共实用程序。
E. Passing data through Intents and Parcelable Interface.
E.通过Intents和Parcelable接口传递数据。
It depend upon your project needs.
这取决于您的项目需求。
A. Database
答:数据库
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 Key Username, Value Value.
假设你想存储用户名。这里有两个关键用户名,Value值。
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()可以保存所需的dtatype。
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.
如果我们想要保存一个对象状态,以便通过网络发送它,或者您也可以使用它来实现目标,那么就可以使用Object seralize。
Use java beans and store in it as one of his fields and use getters and setter for that
使用java bean并将其存储为其字段之一,并使用getters和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.
JavaBeans是具有属性的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
在其他类中获取变量。
D. CommonUtilities
d . CommonUtilities
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
通过意图传递数据。
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/
#11
14
implement serializable in your class
在您的类中实现serializable。
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 intent = new Intent(this, SecondAct.class);
intent.putExtra("PLACE", Place);
startActivity();
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.
但是当数据变大时,这个方法就会变慢。
#12
11
I use Gson with its so powerful and simple api to send objects between activities,
我使用Gson的强大和简单的api在活动之间发送对象,
Example
例子
// This is the object to be sent, can be any object
public class AndroidPacket {
public String CustomerName;
//constructor
public AndroidPacket(String cName){
CustomerName = cName;
}
// other fields ....
// You can add those functions as LiveTemplate !
public String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
}
public static AndroidPacket fromJson(String json) {
Gson gson = new Gson();
return gson.fromJson(json, AndroidPacket.class);
}
}
2 functions you add them to the objects that you want to send
将它们添加到想要发送的对象中。
Usage
使用
Send Object From A to B
将对象从A发送到B。
// Convert the object to string using Gson
AndroidPacket androidPacket = new AndroidPacket("Ahmad");
String objAsJson = androidPacket.toJson();
Intent intent = new Intent(A.this, B.class);
intent.putExtra("my_obj", objAsJson);
startActivity(intent);
Receive In B
收到B
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
String objAsJson = bundle.getString("my_obj");
AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);
// Here you can use your Object
Log.d("Gson", androidPacket.CustomerName);
}
I use it almost in every project i do and I have no performance issues.
我几乎在每一个项目中都使用它,而且我没有性能问题。
#13
9
I struggled with the same problem. I solved it by using a static class, storing any data I want in a HashMap. On top I use an extension of the standard Activity class where I have overriden the methods onCreate an onDestroy to do the data transport and data clearing hidden. Some ridiculous settings have to be changed e.g. orientation-handling.
我也遇到了同样的问题。我通过使用静态类来解决它,在HashMap中存储我想要的任何数据。在上面,我使用了一个标准活动类的扩展,在这里,我已经把方法onCreate onDestroy创建了一个onDestroy来完成数据传输和数据清理。一些可笑的设置必须改变,例如:定向处理。
Annotation: Not providing general objects to be passed to another Activity is pain in the ass. It's like shooting oneself in the knee and hoping to win a 100 metres. "Parcable" is not a sufficient substitute. It makes me laugh... I don't want to implement this interface to my technology-free API, as less I want to introduce a new Layer... How could it be, that we are in mobile programming so far away from modern paradigm...
注释:不提供一般的物品给另一个活动是痛苦的屁股。这就像射击自己的膝盖,希望赢得100米。“Parcable”并不是一个充分的替代品。它让我笑……我不想在我的技术*API中实现这个接口,因为我不想引入一个新的层…怎么可能呢,我们在移动编程中,远离了现代范式……
#14
9
In your first Activity:
在你的第一个活动:
intent.putExtra("myTag", yourObject);
And in your second one:
在你的第二篇文章中:
myCustomObject myObject = (myCustomObject) getIntent().getSerializableExtra("myTag");
Don't forget to make your custom object Serializable:
不要忘记让您的自定义对象序列化:
public class myCustomObject implements Serializable {
...
}
#15
7
Another way to do this is to use the Application
object (android.app.Application). You define this in you AndroidManifest.xml
file as:
另一种方法是使用应用程序对象(android.app.Application)。你在AndroidManifest中定义这个。xml文件为:
<application
android:name=".MyApplication"
...
You can then call this from any activity and save the object to the Application
class.
然后,可以从任何活动调用它,并将对象保存到应用程序类。
In the FirstActivity:
FirstActivity:
MyObject myObject = new MyObject();
MyApplication app = (MyApplication) getApplication();
app.setMyObject(myObject);
In the SecondActivity, do :
在第二项活动中,do:
MyApplication app = (MyApplication) getApplication();
MyObject retrievedObject = app.getMyObject(myObject);
This is handy if you have objects that have application level scope i.e. they have to be used throughout the application. The Parcelable
method is still better if you want explicit control over the object scope or if the scope is limited.
如果您有具有应用程序级别范围的对象,即它们必须在整个应用程序中使用,这很方便。如果您想要显式地控制对象范围,或者范围是有限的,那么Parcelable方法仍然更好。
This avoid the use of Intents
altogether, though. I don't know if they suits you. Another way I used this is to have int
identifiers of objects send through intents and retrieve objects that I have in Maps in the Application
object.
不过,这完全避免了意图的使用。我不知道他们是否适合你。另一种方法是使用int标识符,通过intents发送和检索应用程序对象中映射的对象。
#16
6
in your class model (Object) implement Serializable, for Example:
在类模型(对象)中实现Serializable,例如:
public class MensajesProveedor implements Serializable {
private int idProveedor;
public MensajesProveedor() {
}
public int getIdProveedor() {
return idProveedor;
}
public void setIdProveedor(int idProveedor) {
this.idProveedor = idProveedor;
}
}
and your first Activity
和你的第一个活动
MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("mensajes",mp);
startActivity(i);
and your second Activity (NewActivity)
你的第二项活动(新活动)
MensajesProveedor mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");
good luck!!
祝你好运! !
#17
6
public class SharedBooking implements Parcelable{
public int account_id;
public Double betrag;
public Double betrag_effected;
public int taxType;
public int tax;
public String postingText;
public SharedBooking() {
account_id = 0;
betrag = 0.0;
betrag_effected = 0.0;
taxType = 0;
tax = 0;
postingText = "";
}
public SharedBooking(Parcel in) {
account_id = in.readInt();
betrag = in.readDouble();
betrag_effected = in.readDouble();
taxType = in.readInt();
tax = in.readInt();
postingText = in.readString();
}
public int getAccount_id() {
return account_id;
}
public void setAccount_id(int account_id) {
this.account_id = account_id;
}
public Double getBetrag() {
return betrag;
}
public void setBetrag(Double betrag) {
this.betrag = betrag;
}
public Double getBetrag_effected() {
return betrag_effected;
}
public void setBetrag_effected(Double betrag_effected) {
this.betrag_effected = betrag_effected;
}
public int getTaxType() {
return taxType;
}
public void setTaxType(int taxType) {
this.taxType = taxType;
}
public int getTax() {
return tax;
}
public void setTax(int tax) {
this.tax = tax;
}
public String getPostingText() {
return postingText;
}
public void setPostingText(String postingText) {
this.postingText = postingText;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(account_id);
dest.writeDouble(betrag);
dest.writeDouble(betrag_effected);
dest.writeInt(taxType);
dest.writeInt(tax);
dest.writeString(postingText);
}
public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>()
{
public SharedBooking createFromParcel(Parcel in)
{
return new SharedBooking(in);
}
public SharedBooking[] newArray(int size)
{
return new SharedBooking[size];
}
};
}
Passing the data:
通过数据:
Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
i.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataList);
intent.putExtras(bundle);
startActivity(intent);
Retrieving the data:
检索数据:
Bundle bundle = getIntent().getExtras();
dataList2 = getIntent().getExtras().getParcelableArrayList("data");
#18
4
you can use putExtra(Serializable..) and getSerializableExtra() methods to pass and retrieve objects of your class type; you will have to mark your class Serializable and make sure that all your member variables are serializable too...
您可以使用putExtra(Serializable.)和getSerializableExtra()方法来传递和检索类类型的对象;您必须标记您的类可序列化,并确保所有成员变量都是可序列化的。
#19
3
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
活动
mytestclass.staticfunctionSet("","",""..etc.);
activity b
活动b
mytestclass obj= mytestclass.staticfunctionGet();
#20
3
Create Android Application
创建Android应用程序
File >> New >> Android Application
>>新>> Android应用程序。
Enter Project name: android-pass-object-to-activity
输入项目名称:android-pass-object-to-activity
Pakcage: com.hmkcode.android
Pakcage:com.hmkcode.android
Keep other defualt selections, go Next till you reach Finish
保持其他的脱色选择,下一步,直到你完成。
Before start creating the App we need to create POJO class “Person” which we will use to send object from one activity to another. Notice that the class is implementing Serializable interface.
在开始创建应用程序之前,我们需要创建POJO类“Person”,用于将对象从一个活动发送到另一个活动。请注意,该类正在实现Serializable接口。
Person.java
将位于
package com.hmkcode.android;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
// getters & setters....
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Two Layouts for Two Activities
两个活动的两个布局。
activity_main.xml
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name" />
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvAge"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Age" />
<EditText
android:id="@+id/etAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</LinearLayout>
<Button
android:id="@+id/btnPassObject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Pass Object to Another Activity" />
</LinearLayout>
activity_another.xml
activity_another.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/tvPerson"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:gravity="center_horizontal"
/>
</LinearLayout>
Two Activity Classes
两类活动
1)ActivityMain.java
1)ActivityMain.java
package com.hmkcode.android;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
Button btnPassObject;
EditText etName, etAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPassObject = (Button) findViewById(R.id.btnPassObject);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
btnPassObject.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// 1. create an intent pass class name or intnet action name
Intent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");
// 2. create person object
Person person = new Person();
person.setName(etName.getText().toString());
person.setAge(Integer.parseInt(etAge.getText().toString()));
// 3. put person in intent data
intent.putExtra("person", person);
// 4. start the activity
startActivity(intent);
}
}
2)AnotherActivity.java
2)AnotherActivity.java
package com.hmkcode.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class AnotherActivity extends Activity {
TextView tvPerson;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
// 1. get passed intent
Intent intent = getIntent();
// 2. get person object from intent
Person person = (Person) intent.getSerializableExtra("person");
// 3. get reference to person textView
tvPerson = (TextView) findViewById(R.id.tvPerson);
// 4. display name & age on textView
tvPerson.setText(person.toString());
}
}
#21
3
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);
#22
3
I know this is late but it is very simple.All you have do is let your class implement Serializable like
我知道这很晚,但很简单。您所做的只是让您的类实现Serializable。
public class MyClass implements Serializable{
}
then you can pass to an intent like
然后你可以传递一个意图。
Intent intent=......
MyClass obje=new MyClass();
intent.putExtra("someStringHere",obje);
To get it you simpley call
为了得到它你简单的呼叫。
MyClass objec=(MyClass)intent.getExtra("theString");
#23
3
Using google's Gson library you can pass object to another activities.Actually we will convert object in the form of json string and after passing to other activity we will again re-convert to object like this
使用谷歌的Gson库,您可以将对象传递给其他活动。实际上,我们将以json字符串的形式转换对象,在传递到其他活动之后,我们将再次转换为这样的对象。
Consider a bean class like this
考虑这样的一个bean类。
public class Example {
private int id;
private String name;
public Example(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
We need to pass object of Example class
我们需要传递示例类的对象。
Example exampleObject=new Example(1,"hello");
String jsonString = new Gson().toJson(exampleObject);
Intent nextIntent=new Intent(this,NextActivity.class);
nextIntent.putExtra("example",jsonString );
startActivity(nextIntent);
For reading we need to do the reverse operation in NextActivity
为了阅读,我们需要在NextActivity中做反向操作。
Example defObject=new Example(-1,null);
//default value to return when example is not available
String defValue= new Gson().toJson(defObject);
String jsonString=getIntent().getExtras().getString("example",defValue);
//passed example object
Example exampleObject=new Gson().fromJson(jsonString,Example .class);
Add this dependancy in gradle
在gradle中添加这个从属关系。
compile 'com.google.code.gson:gson:2.6.2'
#24
2
The simplest would be to just use the following where the item is a string:
最简单的方法就是使用以下的字符串:
intent.putextra("selected_item",item)
For receiving:
接收:
String name = data.getStringExtra("selected_item");
#25
2
If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.
如果您有一个单独的类(fx服务)作为您的模型层的网关,那么它可以通过在该类中使用getter和setter来解决。
In Activity 1:
活动1:
Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);
In Activity 2:
活动2:
private Service service;
private Order order;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quality);
service = Service.getInstance();
order = service.getSavedOrder();
service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
}
In Service:
在服务:
private static Service instance;
private Service()
{
//Constructor content
}
public static Service getInstance()
{
if(instance == null)
{
instance = new Service();
}
return instance;
}
private Order savedOrder;
public Order getSavedOrder()
{
return savedOrder;
}
public void setSavedOrder(Order order)
{
this.savedOrder = order;
}
This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.
此解决方案不需要任何序列化或其他“打包”对象的问题。但是,如果您使用的是这种架构,这将是有益的。
#26
2
By far the easiest way IMHO to parcel objects. You just add an annotation tag above the object you wish to make parcelable.
到目前为止,最简单的方法是将物体包裹起来。您只需在您想要进行parcelable的对象之上添加一个注释标记。
An example from the library is below https://github.com/johncarl81/parceler
该库的一个示例如下:https://github.com/johncarl81/parceler。
@Parcel
public class Example {
String name;
int age;
public Example(){ /*Required empty bean constructor*/ }
public Example(int age, String name) {
this.age = age;
this.name = name;
}
public String getName() { return name; }
public int getAge() { return age; }
}
#27
2
First implement Parcelable in your class. Then pass object like this.
首先在类中实现Parcelable。然后像这样传递对象。
SendActivity.java
SendActivity.java
ObjectA obj = new ObjectA();
// Set values etc.
Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.ObjectA", obj);
startActivity(i);
ReceiveActivity.java
ReceiveActivity.java
Bundle b = getIntent().getExtras();
ObjectA obj = b.getParcelable("com.package.ObjectA");
The package string isn't necessary, just the string needs to be the same in both Activities
包字符串不是必需的,只是字符串需要在两个活动中都是相同的。
参考
#28
2
Start another activity from this activity pass parameters via Bundle Object
从这个活动开始另一个活动通过Bundle对象传递参数。
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
Retrieve on another activity (YourActivity)
检索另一个活动(YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
This is ok for simple kind data type. But if u want to pass complex data in between activity u need to serialize it first.
对于简单类型的数据类型,这是可以的。但是,如果要在活动之间传递复杂数据,则需要先序列化它。
Here we have Employee Model
这里我们有员工模型。
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
You can use Gson lib provided by google to serialize the complex data like this
您可以使用谷歌提供的Gson lib来序列化这样的复杂数据。
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
#29
1
If you are not very particular about using the putExtra feature and just want to launch another activity with objects, you can check out the GNLauncher (https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher) library I wrote in an attempt to make this process more straight forward.
如果您不是很特别地使用putExtra特性,只是想要用对象启动另一个活动,那么您可以查看GNLauncher (https://github.com/virouswinter/gnlib_android/wiki # GNLauncher)库,这是为了使这个过程更加直接。
GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in the Activity with the required data as parameters. It introduces type safety and removes all the hassles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.
GNLauncher使将对象/数据发送到另一个活动中的活动,如在活动中以所需的数据作为参数调用函数。它引入了类型安全性,并消除了必须串行化的所有麻烦,并使用字符串键附加到意图,并在另一端取消了相同的操作。
#30
0
POJO class "Post" (Note that it is implemented Serializable)
POJO类“Post”(注意它是可序列化的)
package com.example.booklib;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;
public class Post implements Serializable{
public String message;
public String bitmap;
List<Comment> commentList = new ArrayList<Comment>();
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getBitmap() {
return bitmap;
}
public void setBitmap(String bitmap) {
this.bitmap = bitmap;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
}
POJO class "Comment"(Since being a member of Post class,it is also needed to implement the Serializable)
POJO类“注释”(由于是Post类的成员,所以还需要实现Serializable)
package com.example.booklib;
import java.io.Serializable;
public class Comment implements Serializable{
public String message;
public String fromName;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
}
Then in your activity class, you can do as following to pass the object to another activity.
然后在activity类中,可以按照以下方式将对象传递给另一个活动。
ListView listview = (ListView) findViewById(R.id.post_list);
listview.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Post item = (Post)parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this,CommentsActivity.class);
intent.putExtra("post",item);
startActivity(intent);
}
});
In your recipient class "CommentsActivity" you can get the data as the following
在您的接收类“CommentsActivity”中,您可以获得如下的数据。
Post post =(Post)getIntent().getSerializableExtra("post");
#1
669
If you're just passing objects around then Parcelable was 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, WAY faster).
如果你只是传递对象,那么Parcelable就是为这个设计的。它比使用Java的本地序列化需要更多的努力,但是它的速度更快(而且我的意思是更快)。
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).
注意,如果您有多个字段从一个给定的包中检索,那么您必须按照您将它们放入(即,在FIFO方法中)的顺序来执行。
Once you have your objects implement Parcelable
it's just a matter of putting them into your Intents with putExtra():
一旦你让你的对象实现了Parcelable,它只是将它们放入你的意图和putExtra():
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);
#2
152
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进行序列化的最简单方法之一是通过谷歌GSON。
In that case you juse put the string return value from (new Gson()).toJson(myObject);
and retrieve the string value and use fromJson
to turn it back into your object.
在这种情况下,juse将字符串返回值(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.
但是,如果对象不是很复杂,那么它可能不值得开销,您可以考虑将对象的单独值传递给它。
#3
139
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 {
}
#4
62
For situations where you know you will be passing data within an application, use "globals" (like static Classes)
对于您知道将在应用程序中传递数据的情况,可以使用“全局变量”(比如静态类)
Here is what Dianne Hackborn (hackbod - a Google Android Software Engineer) had to say on the matter:
下面是Dianne Hackborn (hackbod,一个谷歌的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
>,当您创建一个新的myexplain terstate时,为它创建一个惟一的名称并将其放入散列映射中;要将该状态发送到另一个活动,只需将唯一的名称放入散列映射中,当第二个活动启动时,它可以从哈希映射中获取其接收的名称的my解释器状态。 ,>
#5
46
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使用next。
MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");
I hope it helps :D
我希望它有帮助:D。
#6
27
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,您不需要做任何其他事情,您可以传递一个可序列化的对象。这就是我使用。
#7
17
Short answer for fast need
简短的回答,快速的需要。
1. Implement your Class to implements Serializable.
1。实现您的类来实现Serializable。
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 to Intent
2。把你的目标放在目的上。
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");
#8
16
You can use android BUNDLE to do this.
你可以用android BUNDLE做这个。
Create a Bundle from your class like:
从您的类中创建一个包,例如:
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
然后将这个捆绑包与意图一起传递。现在您可以通过传递类似的包来重新创建类对象。
public CustomClass(Context _context, Bundle b) {
context = _context;
classMember = b.getString("SomeKey");
}
Declare this in your Custom class and use.
在您的自定义类中声明这个并使用。
#9
15
Thanks for parcelable help but i found one more optional solution
感谢parcelable的帮助,但我找到了一个可选的解决方案。
public class getsetclass implements Serializable {
private int dt = 10;
//pass any object, drwabale
public int getDt() {
return dt;
}
public void setDt(int dt) {
this.dt = dt;
}
}
In Activity One
在活动
getsetclass d = new getsetclass ();
d.setDt(50);
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("hashmapkey", d);
Intent inew = new Intent(SgParceLableSampelActivity.this,
ActivityNext.class);
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
inew.putExtras(b);
startActivity(inew);
Get Data In Activity 2
获取活动2中的数据。
try { setContentView(R.layout.main);
Bundle bn = new Bundle();
bn = getIntent().getExtras();
HashMap<String, Object> getobj = new HashMap<String, Object>();
getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
getsetclass d = (getsetclass) getobj.get("hashmapkey");
} catch (Exception e) {
Log.e("Err", e.getMessage());
}
#10
14
There are couple of ways by which you can access variables or object in other classes or Activity.
有几种方法可以在其他类或活动中访问变量或对象。
A. Database
答:数据库
B. shared preferences.
共同的喜好。
C. Object serialization.
对象序列化。
D. A class which can hold common data can be named as Common Utilities it depends on you.
可以保存公共数据的类可以被命名为它依赖于您的公共实用程序。
E. Passing data through Intents and Parcelable Interface.
E.通过Intents和Parcelable接口传递数据。
It depend upon your project needs.
这取决于您的项目需求。
A. Database
答:数据库
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 Key Username, Value Value.
假设你想存储用户名。这里有两个关键用户名,Value值。
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()可以保存所需的dtatype。
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.
如果我们想要保存一个对象状态,以便通过网络发送它,或者您也可以使用它来实现目标,那么就可以使用Object seralize。
Use java beans and store in it as one of his fields and use getters and setter for that
使用java bean并将其存储为其字段之一,并使用getters和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.
JavaBeans是具有属性的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
在其他类中获取变量。
D. CommonUtilities
d . CommonUtilities
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
通过意图传递数据。
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/
#11
14
implement serializable in your class
在您的类中实现serializable。
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 intent = new Intent(this, SecondAct.class);
intent.putExtra("PLACE", Place);
startActivity();
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.
但是当数据变大时,这个方法就会变慢。
#12
11
I use Gson with its so powerful and simple api to send objects between activities,
我使用Gson的强大和简单的api在活动之间发送对象,
Example
例子
// This is the object to be sent, can be any object
public class AndroidPacket {
public String CustomerName;
//constructor
public AndroidPacket(String cName){
CustomerName = cName;
}
// other fields ....
// You can add those functions as LiveTemplate !
public String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
}
public static AndroidPacket fromJson(String json) {
Gson gson = new Gson();
return gson.fromJson(json, AndroidPacket.class);
}
}
2 functions you add them to the objects that you want to send
将它们添加到想要发送的对象中。
Usage
使用
Send Object From A to B
将对象从A发送到B。
// Convert the object to string using Gson
AndroidPacket androidPacket = new AndroidPacket("Ahmad");
String objAsJson = androidPacket.toJson();
Intent intent = new Intent(A.this, B.class);
intent.putExtra("my_obj", objAsJson);
startActivity(intent);
Receive In B
收到B
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
String objAsJson = bundle.getString("my_obj");
AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);
// Here you can use your Object
Log.d("Gson", androidPacket.CustomerName);
}
I use it almost in every project i do and I have no performance issues.
我几乎在每一个项目中都使用它,而且我没有性能问题。
#13
9
I struggled with the same problem. I solved it by using a static class, storing any data I want in a HashMap. On top I use an extension of the standard Activity class where I have overriden the methods onCreate an onDestroy to do the data transport and data clearing hidden. Some ridiculous settings have to be changed e.g. orientation-handling.
我也遇到了同样的问题。我通过使用静态类来解决它,在HashMap中存储我想要的任何数据。在上面,我使用了一个标准活动类的扩展,在这里,我已经把方法onCreate onDestroy创建了一个onDestroy来完成数据传输和数据清理。一些可笑的设置必须改变,例如:定向处理。
Annotation: Not providing general objects to be passed to another Activity is pain in the ass. It's like shooting oneself in the knee and hoping to win a 100 metres. "Parcable" is not a sufficient substitute. It makes me laugh... I don't want to implement this interface to my technology-free API, as less I want to introduce a new Layer... How could it be, that we are in mobile programming so far away from modern paradigm...
注释:不提供一般的物品给另一个活动是痛苦的屁股。这就像射击自己的膝盖,希望赢得100米。“Parcable”并不是一个充分的替代品。它让我笑……我不想在我的技术*API中实现这个接口,因为我不想引入一个新的层…怎么可能呢,我们在移动编程中,远离了现代范式……
#14
9
In your first Activity:
在你的第一个活动:
intent.putExtra("myTag", yourObject);
And in your second one:
在你的第二篇文章中:
myCustomObject myObject = (myCustomObject) getIntent().getSerializableExtra("myTag");
Don't forget to make your custom object Serializable:
不要忘记让您的自定义对象序列化:
public class myCustomObject implements Serializable {
...
}
#15
7
Another way to do this is to use the Application
object (android.app.Application). You define this in you AndroidManifest.xml
file as:
另一种方法是使用应用程序对象(android.app.Application)。你在AndroidManifest中定义这个。xml文件为:
<application
android:name=".MyApplication"
...
You can then call this from any activity and save the object to the Application
class.
然后,可以从任何活动调用它,并将对象保存到应用程序类。
In the FirstActivity:
FirstActivity:
MyObject myObject = new MyObject();
MyApplication app = (MyApplication) getApplication();
app.setMyObject(myObject);
In the SecondActivity, do :
在第二项活动中,do:
MyApplication app = (MyApplication) getApplication();
MyObject retrievedObject = app.getMyObject(myObject);
This is handy if you have objects that have application level scope i.e. they have to be used throughout the application. The Parcelable
method is still better if you want explicit control over the object scope or if the scope is limited.
如果您有具有应用程序级别范围的对象,即它们必须在整个应用程序中使用,这很方便。如果您想要显式地控制对象范围,或者范围是有限的,那么Parcelable方法仍然更好。
This avoid the use of Intents
altogether, though. I don't know if they suits you. Another way I used this is to have int
identifiers of objects send through intents and retrieve objects that I have in Maps in the Application
object.
不过,这完全避免了意图的使用。我不知道他们是否适合你。另一种方法是使用int标识符,通过intents发送和检索应用程序对象中映射的对象。
#16
6
in your class model (Object) implement Serializable, for Example:
在类模型(对象)中实现Serializable,例如:
public class MensajesProveedor implements Serializable {
private int idProveedor;
public MensajesProveedor() {
}
public int getIdProveedor() {
return idProveedor;
}
public void setIdProveedor(int idProveedor) {
this.idProveedor = idProveedor;
}
}
and your first Activity
和你的第一个活动
MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("mensajes",mp);
startActivity(i);
and your second Activity (NewActivity)
你的第二项活动(新活动)
MensajesProveedor mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");
good luck!!
祝你好运! !
#17
6
public class SharedBooking implements Parcelable{
public int account_id;
public Double betrag;
public Double betrag_effected;
public int taxType;
public int tax;
public String postingText;
public SharedBooking() {
account_id = 0;
betrag = 0.0;
betrag_effected = 0.0;
taxType = 0;
tax = 0;
postingText = "";
}
public SharedBooking(Parcel in) {
account_id = in.readInt();
betrag = in.readDouble();
betrag_effected = in.readDouble();
taxType = in.readInt();
tax = in.readInt();
postingText = in.readString();
}
public int getAccount_id() {
return account_id;
}
public void setAccount_id(int account_id) {
this.account_id = account_id;
}
public Double getBetrag() {
return betrag;
}
public void setBetrag(Double betrag) {
this.betrag = betrag;
}
public Double getBetrag_effected() {
return betrag_effected;
}
public void setBetrag_effected(Double betrag_effected) {
this.betrag_effected = betrag_effected;
}
public int getTaxType() {
return taxType;
}
public void setTaxType(int taxType) {
this.taxType = taxType;
}
public int getTax() {
return tax;
}
public void setTax(int tax) {
this.tax = tax;
}
public String getPostingText() {
return postingText;
}
public void setPostingText(String postingText) {
this.postingText = postingText;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(account_id);
dest.writeDouble(betrag);
dest.writeDouble(betrag_effected);
dest.writeInt(taxType);
dest.writeInt(tax);
dest.writeString(postingText);
}
public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>()
{
public SharedBooking createFromParcel(Parcel in)
{
return new SharedBooking(in);
}
public SharedBooking[] newArray(int size)
{
return new SharedBooking[size];
}
};
}
Passing the data:
通过数据:
Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
i.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataList);
intent.putExtras(bundle);
startActivity(intent);
Retrieving the data:
检索数据:
Bundle bundle = getIntent().getExtras();
dataList2 = getIntent().getExtras().getParcelableArrayList("data");
#18
4
you can use putExtra(Serializable..) and getSerializableExtra() methods to pass and retrieve objects of your class type; you will have to mark your class Serializable and make sure that all your member variables are serializable too...
您可以使用putExtra(Serializable.)和getSerializableExtra()方法来传递和检索类类型的对象;您必须标记您的类可序列化,并确保所有成员变量都是可序列化的。
#19
3
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
活动
mytestclass.staticfunctionSet("","",""..etc.);
activity b
活动b
mytestclass obj= mytestclass.staticfunctionGet();
#20
3
Create Android Application
创建Android应用程序
File >> New >> Android Application
>>新>> Android应用程序。
Enter Project name: android-pass-object-to-activity
输入项目名称:android-pass-object-to-activity
Pakcage: com.hmkcode.android
Pakcage:com.hmkcode.android
Keep other defualt selections, go Next till you reach Finish
保持其他的脱色选择,下一步,直到你完成。
Before start creating the App we need to create POJO class “Person” which we will use to send object from one activity to another. Notice that the class is implementing Serializable interface.
在开始创建应用程序之前,我们需要创建POJO类“Person”,用于将对象从一个活动发送到另一个活动。请注意,该类正在实现Serializable接口。
Person.java
将位于
package com.hmkcode.android;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
// getters & setters....
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Two Layouts for Two Activities
两个活动的两个布局。
activity_main.xml
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name" />
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvAge"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Age" />
<EditText
android:id="@+id/etAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</LinearLayout>
<Button
android:id="@+id/btnPassObject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Pass Object to Another Activity" />
</LinearLayout>
activity_another.xml
activity_another.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/tvPerson"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:gravity="center_horizontal"
/>
</LinearLayout>
Two Activity Classes
两类活动
1)ActivityMain.java
1)ActivityMain.java
package com.hmkcode.android;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
Button btnPassObject;
EditText etName, etAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPassObject = (Button) findViewById(R.id.btnPassObject);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
btnPassObject.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// 1. create an intent pass class name or intnet action name
Intent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");
// 2. create person object
Person person = new Person();
person.setName(etName.getText().toString());
person.setAge(Integer.parseInt(etAge.getText().toString()));
// 3. put person in intent data
intent.putExtra("person", person);
// 4. start the activity
startActivity(intent);
}
}
2)AnotherActivity.java
2)AnotherActivity.java
package com.hmkcode.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class AnotherActivity extends Activity {
TextView tvPerson;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
// 1. get passed intent
Intent intent = getIntent();
// 2. get person object from intent
Person person = (Person) intent.getSerializableExtra("person");
// 3. get reference to person textView
tvPerson = (TextView) findViewById(R.id.tvPerson);
// 4. display name & age on textView
tvPerson.setText(person.toString());
}
}
#21
3
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);
#22
3
I know this is late but it is very simple.All you have do is let your class implement Serializable like
我知道这很晚,但很简单。您所做的只是让您的类实现Serializable。
public class MyClass implements Serializable{
}
then you can pass to an intent like
然后你可以传递一个意图。
Intent intent=......
MyClass obje=new MyClass();
intent.putExtra("someStringHere",obje);
To get it you simpley call
为了得到它你简单的呼叫。
MyClass objec=(MyClass)intent.getExtra("theString");
#23
3
Using google's Gson library you can pass object to another activities.Actually we will convert object in the form of json string and after passing to other activity we will again re-convert to object like this
使用谷歌的Gson库,您可以将对象传递给其他活动。实际上,我们将以json字符串的形式转换对象,在传递到其他活动之后,我们将再次转换为这样的对象。
Consider a bean class like this
考虑这样的一个bean类。
public class Example {
private int id;
private String name;
public Example(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
We need to pass object of Example class
我们需要传递示例类的对象。
Example exampleObject=new Example(1,"hello");
String jsonString = new Gson().toJson(exampleObject);
Intent nextIntent=new Intent(this,NextActivity.class);
nextIntent.putExtra("example",jsonString );
startActivity(nextIntent);
For reading we need to do the reverse operation in NextActivity
为了阅读,我们需要在NextActivity中做反向操作。
Example defObject=new Example(-1,null);
//default value to return when example is not available
String defValue= new Gson().toJson(defObject);
String jsonString=getIntent().getExtras().getString("example",defValue);
//passed example object
Example exampleObject=new Gson().fromJson(jsonString,Example .class);
Add this dependancy in gradle
在gradle中添加这个从属关系。
compile 'com.google.code.gson:gson:2.6.2'
#24
2
The simplest would be to just use the following where the item is a string:
最简单的方法就是使用以下的字符串:
intent.putextra("selected_item",item)
For receiving:
接收:
String name = data.getStringExtra("selected_item");
#25
2
If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.
如果您有一个单独的类(fx服务)作为您的模型层的网关,那么它可以通过在该类中使用getter和setter来解决。
In Activity 1:
活动1:
Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);
In Activity 2:
活动2:
private Service service;
private Order order;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quality);
service = Service.getInstance();
order = service.getSavedOrder();
service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
}
In Service:
在服务:
private static Service instance;
private Service()
{
//Constructor content
}
public static Service getInstance()
{
if(instance == null)
{
instance = new Service();
}
return instance;
}
private Order savedOrder;
public Order getSavedOrder()
{
return savedOrder;
}
public void setSavedOrder(Order order)
{
this.savedOrder = order;
}
This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.
此解决方案不需要任何序列化或其他“打包”对象的问题。但是,如果您使用的是这种架构,这将是有益的。
#26
2
By far the easiest way IMHO to parcel objects. You just add an annotation tag above the object you wish to make parcelable.
到目前为止,最简单的方法是将物体包裹起来。您只需在您想要进行parcelable的对象之上添加一个注释标记。
An example from the library is below https://github.com/johncarl81/parceler
该库的一个示例如下:https://github.com/johncarl81/parceler。
@Parcel
public class Example {
String name;
int age;
public Example(){ /*Required empty bean constructor*/ }
public Example(int age, String name) {
this.age = age;
this.name = name;
}
public String getName() { return name; }
public int getAge() { return age; }
}
#27
2
First implement Parcelable in your class. Then pass object like this.
首先在类中实现Parcelable。然后像这样传递对象。
SendActivity.java
SendActivity.java
ObjectA obj = new ObjectA();
// Set values etc.
Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.ObjectA", obj);
startActivity(i);
ReceiveActivity.java
ReceiveActivity.java
Bundle b = getIntent().getExtras();
ObjectA obj = b.getParcelable("com.package.ObjectA");
The package string isn't necessary, just the string needs to be the same in both Activities
包字符串不是必需的,只是字符串需要在两个活动中都是相同的。
参考
#28
2
Start another activity from this activity pass parameters via Bundle Object
从这个活动开始另一个活动通过Bundle对象传递参数。
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
Retrieve on another activity (YourActivity)
检索另一个活动(YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
This is ok for simple kind data type. But if u want to pass complex data in between activity u need to serialize it first.
对于简单类型的数据类型,这是可以的。但是,如果要在活动之间传递复杂数据,则需要先序列化它。
Here we have Employee Model
这里我们有员工模型。
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
You can use Gson lib provided by google to serialize the complex data like this
您可以使用谷歌提供的Gson lib来序列化这样的复杂数据。
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
#29
1
If you are not very particular about using the putExtra feature and just want to launch another activity with objects, you can check out the GNLauncher (https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher) library I wrote in an attempt to make this process more straight forward.
如果您不是很特别地使用putExtra特性,只是想要用对象启动另一个活动,那么您可以查看GNLauncher (https://github.com/virouswinter/gnlib_android/wiki # GNLauncher)库,这是为了使这个过程更加直接。
GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in the Activity with the required data as parameters. It introduces type safety and removes all the hassles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.
GNLauncher使将对象/数据发送到另一个活动中的活动,如在活动中以所需的数据作为参数调用函数。它引入了类型安全性,并消除了必须串行化的所有麻烦,并使用字符串键附加到意图,并在另一端取消了相同的操作。
#30
0
POJO class "Post" (Note that it is implemented Serializable)
POJO类“Post”(注意它是可序列化的)
package com.example.booklib;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;
public class Post implements Serializable{
public String message;
public String bitmap;
List<Comment> commentList = new ArrayList<Comment>();
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getBitmap() {
return bitmap;
}
public void setBitmap(String bitmap) {
this.bitmap = bitmap;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
}
POJO class "Comment"(Since being a member of Post class,it is also needed to implement the Serializable)
POJO类“注释”(由于是Post类的成员,所以还需要实现Serializable)
package com.example.booklib;
import java.io.Serializable;
public class Comment implements Serializable{
public String message;
public String fromName;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
}
Then in your activity class, you can do as following to pass the object to another activity.
然后在activity类中,可以按照以下方式将对象传递给另一个活动。
ListView listview = (ListView) findViewById(R.id.post_list);
listview.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Post item = (Post)parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this,CommentsActivity.class);
intent.putExtra("post",item);
startActivity(intent);
}
});
In your recipient class "CommentsActivity" you can get the data as the following
在您的接收类“CommentsActivity”中,您可以获得如下的数据。
Post post =(Post)getIntent().getSerializableExtra("post");