0

I know that if I want to send a custom object O from Activity A to Activity B, I have to make the object O implement Parcelable. However, currently my object O has a lot of various types of fields. In this case, can I just use a singleton? For example,

1. in Activity B, I create a public static Object o; 2. in Activity A, I do B.o = ObjectToSend; startActivity(intent for B); 3. in Activity B's onCreate(), I do O o = B.o; if o is not null, use o.. 

Is there a problem with this approach? Thanks

1
  • 1
    I would discourage the misuse of the design pattern Commented Oct 13, 2014 at 17:39

3 Answers 3

1

can you just make it serializable? ( if so, look into this question for an example: Pass serializable object throught intent )

if you really want to go with the "static" approach, i'd look into using a subclass of Application, it's more designed to handle application state, which is what your are trying to pass around. if so, google "android custom application class" and you will get some pretty good blogs and posts about using it.

a decent note on Parcelable vs Serializable

Sign up to request clarification or add additional context in comments.

4 Comments

It's not much harder to make something Parcelable than Serializable and it prevents many possible problems
as the link i included talks about, to make somethign Serializable, you just add "implements .." to each class. to make it Parcelable you have to add boiler plate type methods to each class. i'd take 2 words over a constructor and extra method any day.
The object I want to pass has the following field. HashMap<String, ThirdPartyLibraryObjectWhichDoesNotImplementParcelableOrSerializable>. In this case I don't think I can make it parcelable or serializable... can I? Wouldn't it be much simpler to just set this object in a static singleton field from A and read it from B?
if you can't update that 3rd party class, i'd go with the Application subclass. that would be the cleanest way to do it. Make it the owner of your data.
1

Assuming no other threads could change those variables it will work that way, but it's usually more common to separate the Singleton out into it's own class (e.g.)

public class ObjectSingleton{ private static ... someobject; //getters and setters } 

So it's easier to wrap thread safe code around it.

Comments

0

You can subclass your own Application class and make your object a field of that class. Your Application subclass exists as long as your program is running so your object will be there all the time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.