Android putSerializable与putString [英] Android putSerializable vs putString
问题描述
我有一个这样定义的POJO对象:
i have a POJO object defined like this:
public class MYPOJO implements Serializable {
int myint;
String mystring;
}
然后当我将信息传递给活动时,我这样做:
then when im passing the info to an activity i do this:
Intent i = new Intent(this, WearActivity.class);
Bundle b = new Bundle();
MYPojo pojo = new MYPojo();
pojo.mystring="cool";
b.putSerializable("someString", pojo.mystring);//this line is my issue
i.putExtra("coolBundle",b);
startActivityForResult(i, 0);
并额外阅读"someString":
and to read the 'someString' extra i do:
Bundle b2 = getIntent().getBundleExtra("coolBundle");
b2.getString("someString");
所以现在我的问题是:如果最后我仍然要求检索b2.getString("someString"),那么如果我执行以下操作,真的有什么区别吗?
So now onto my question: is there really any difference if i do the following if if at the end im still calling for retrieval b2.getString("someString") :
b.putString("someString",pojo.mystring)
vs
b.putSerializable("someString",pojo.mystring) ?
推荐答案
在实践中,除了效率"或可能的用法外,在活动之间传递字符串或传递可序列化的字符串之间没有什么区别反射/安全性.将String作为可序列化"传入时,可能更多是设计和原理问题.本质上,通过传入一个可序列化的String,Android/Java将利用String的包装器,该包装器在后台包含char []的数据结构.
In practice, there isn't a difference you'll see between passing a string, or passing a serializable string between activities, besides "efficiency" or possible usage of reflection/security. It might be more of a design and principle issue I have with passing a String in as "serializable". Essentially by passing in a String as Serializable, Android/Java will utilize the wrapper of String, which contains a data structure of char[] behind the scenes.
TLDR;如果您的POJO中包含更多数据,我强烈建议您实施Parcelable.可以在此处中找到更多信息.但是,如果您只传递一个字符串,则可以使用Android为我们提供的putString/getString方法.
TLDR; If your POJO contained more data, I would highly recommend implementing Parcelable. More information can be found in this SO answer here. But if you are going to be passing just a String, I would use the putString/getString methods that Android provides for us.
这篇关于Android putSerializable与putString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!