Tester
Tester

Reputation: 149

Android Variables in Background

I'd like to know how I can set a variable that will stay the same after I have closed the app. In this case I don't want to make it with a SharedPreference or a DataBase.

Thanks in advance.

Upvotes: 0

Views: 360

Answers (2)

Thracian
Thracian

Reputation: 66849

Variables endure for the life cycle of an app. When user closes an app and that app is not running a service in the background everything is deleted. In some occurences(but this has a slight chance) static variables from previous session can be read incidentally if app is restarted again, but this is not a correct behaviour.

There are 3 ways to keep your data.

  1. Write to file: You can create files in txt, json or in any other format you wish, and read from these files on runtime to get values from previous session. I don't prefer writing to file to keep data very much. If you don't know how to use database and want mess with it, you can use this.
  2. Shared Preferences: This is generally for saving settings file with name and value pairs.
  3. Writing to a database: You write your data to database. SQLite and Realm databases are the most popular ones.

Upvotes: 2

David Medenjak
David Medenjak

Reputation: 34532

If the app gets closed any variable will be long gone on the next start.

The only way to keep data is to use persistence of some sort, and the most commonly used one is SharedPreferences.

You can alternatively write to a file, send your data to a server (and load it again on the next start), or use a database.


You can also make use of a Service which you keep running in the background, that keeps your values. But you will have no guarantee about when / how the system might stop it, and they would be lost—again—like before.


If you want to keep some value, you need to persist it.

Upvotes: 2

Related Questions