0

I want to fetch some important data in onCreate of my Application, and store them in the memory.

Can I assume the data I store in memory will be there? If the app get destroyed, can I assume onCreate will always get triggered again?

Patroclus
  • 1,163
  • 13
  • 31
  • How would you access these objects? If you don't have a way to access them, it is moot whether they are technically still in memory. – Stephen C Mar 05 '22 at 04:28
  • It's in a global object. I remembered Android can destroy the stack and restore the top of the stack when user enters the app. If only the topmost activity get created, does it mean my global object is gone and application onCreate won't get called? – Patroclus Mar 05 '22 at 04:42
  • 1
    What is the "global object" concept? Java doesn't have globals. Do you mean `static`? – Stephen C Mar 05 '22 at 04:44
  • Yes they are store in a static object – Patroclus Mar 05 '22 at 04:46

2 Answers2

1

From the documentation for onCreate

Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

If your application is killed in the background by the system, then it would have to call onCreate again next time it is launched. As long as you re-initialize your static value in onCreate each time it should be safe - assuming your application class would hold a reference to it to prevent it from being garbage collected.

You may also find this question useful regarding garbage collecting of static variables.

Tyler V
  • 9,694
  • 3
  • 26
  • 52
0

I don't think that you can depend on that. If you really need to recover the information, you'll need to store it somewhere that survives the destruction of the application, like local storage, or a database.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • I am fine with fetching it again. If the app get recreated, is Application onCreate guaranteed to be called? – Patroclus Mar 05 '22 at 04:43