Riccardo Vailati
Riccardo Vailati

Reputation: 203

How can I store references of non-serializable objects in Java? (Android)

I'm experimenting some stuff with Java for Android. I'm still new to Android programming and I haven't been using Java in A LOT, so I may be a little rusty.

So, here's the situation: I got an Activity that, each time you press a button, creates and starts a new CountDownTimer. If I close the activity, the CountDownTimers started before will still be running. I need a way to recover the references to the ContDownTimer instances from another Activity.

I thought about Serialization, but the abstract class CountDownTimer doesn't seem to implement Serializable. (I get an error while I try to deserialize the objects. Besides, since they ARE running, it means they still are on the heap, right? I only need a way to reference them. I'm a little bit confused on this whole topic of serialization, but that's not the point... or is it?)

Next attempt was going to be an Android Service, but they're even more confusing than Serialization and also look a little like an overkill, due to battery consumption and the fact that CountDownTimers (as far as I understood it) already run on a thread (or a process?) of their own. So I decided i would pay a visit here to see if I was heading in the right direction before starting to struggle with the world of Services.

Upvotes: 2

Views: 391

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006819

I need a way to recover the references to the ContDownTimer instances from another Activity.

Then they should not have been part of the first activity originally. Put them in some central storage location. That could be a singleton or a Service. Or, it could be that the answer is to dump CountDownTimer entirely and do something else. Since we do not know what you are trying to accomplish, it is difficult to provide you with good advice.

I thought about Serialization

That would not make much sense for a CountDownTimer.

Besides, since they ARE running, it means they still are on the heap, right?

As long as your process is around.

I'm a little bit confused on this whole topic of serialization

Serialization is for persisting objects to disk. That would not make much sense for a CountDownTimer.

due to battery consumption

A Service does not intrinsically consume any battery. How you use a service might.

the fact that CountDownTimers (as far as I understood it) already run on a thread (or a process?) of their own

No, they do not. They use the main application thread.

So I decided i would pay a visit here to see if I was heading in the right direction

We have no way of answering that, since we have no idea what you are trying to implement. While CountDownTimer might be part of a proper solution to your problem, it might not, let alone the rest of it.

Upvotes: 2

Related Questions