Android putSerializable vs putString

2019-07-16 23:11发布

问题:

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);

and to read the 'someString' extra i do:

Bundle b2 = getIntent().getBundleExtra("coolBundle");
        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) ?

回答1:

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; 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.