Saving Android Application State Using Static Constants - java

In my Android application I have used a Constants class to store app data like login user information using static variables. I'm able to use that data throughout the app. But, when I leave my app in background for a long time and start it later, it crashes. The error stack contains a NullPointerException on the variable that I have referenced from Constants class.

When your application is cleared from memory, all static variables (which are obviously stored in memory) are cleared as well. The Saving Data Training details many of the available solutions to store data so that it can be properly restored even if the application is killed. Simple key-value pairs can be stored in Shared Preferences.

From static or any variables you couldn't retrieve the last changes after the application is shutdown. For that you need to save the values into file system or any lightweight databases(for example SQLite). Whenever you start you application you need to load into your static fields from the file or database.

Related

What is the best way to share data throughout all activites?

So all of my activities will need the current location of the device, as well as a set of data retrieved through a Http request. I was wondering what is the best way to find this information once, and share it across all my activities?
To pass (or persist) data between application's activities, you can either use:
SharedPreferences:
Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application.
Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory().
Link to SharedPreferences example tutorial.
Intent.putExtra(...)
Whenever you need data from an activity to be in another activity, you can pass data between then while starting the activities. Intents in android offer this convenient way to pass data between activities using Extras.
Link to Intent pass data through extras tutorial.
You can use shared preferences to save data for Android. And get preferences when you want it.
Find your scenario:
If you are going to use a very small amount of data like name, phone
no, or some value, which you want to store even if the app is closed, then use shared preference.
If you are going to use a list of object (List<Object>) and is a
large amount of data, which you want to store even if the app is closed, then use ROOM/SQLite for it.
If you are going to use a list of object(List<Object>) and is a
small amount of data, which you want to store only when the app is
active, then use the static object.
I Think, you should use shared preference for location and static variable which is being retrieved from the network.
If you want to use the current location of the device, use fusedLocationProviderClient once you get it, store it in shared preference. Whenever you the location is provided by fusedLocationProviderClient update the shared preference data.
If the data retrieved from the network is an object and changes every time you open the app and is a small amount of data, then use the static variable, or else use ROOM/SQLite

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.
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.
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.
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.
Shared Preferences: This is generally for saving settings file with name and value pairs.
Writing to a database: You write your data to database. SQLite and Realm databases are the most popular ones.

Android: static variables and moving complex data

If I have a class that contains a static variable, say x:
class MyClass {
static boolean x = false;
// Other methods
}
Now let us say that, hypothetically, I set x = true; from my first activity. Is there any point through the rest of my app's life cycle (including various activities and threads) where this value will simple be 'reset' back to false due to how the 'Google JVM' or the android environment works? I have heard that static variables have a 'lifetime', that dies when the program dies. Do Activities count as separate 'programs'? What about services? Or even Widgets?
I am asking this because it is often difficult to share complex data structures that rely on other complex processing (like syncing data from an online database) in android due to how 'separated' activities are, and static variables are often a very quick and dirty solution to the problem. Other things I have tried include serialisation, but that doesn't really seem like a practical solution either (constantly serialising and decoding objects when the user navigates from one activity to the next seems like it would be very resource intensive).
If I am an evil person for doing this, please tell me what I am doing wrong, or even better, give me some links or examples of better ways to solve this problem.
Yes. There are times where that will reset. Primarily if the user leaves the app and starts fiddling around with other apps or if the user lets the phone go to sleep for a long period of time. The Android process could kill the actual app. Then the "state" of the app will be restored when the user comes back, however static variables will be at their defaults because the actual process was rebuilt.
Generally passing small objects between Activities and Services is done by overriding the Parcelable interface. This will allow you to save and restore objects using setOnInstanceState methods of both Activities, Views, and some adapters. They will likewise, have a restore method in which you can rebuild the object. Parcelable is preferable over Serializable.
Larger data may require a shared file or database depending on the data that you want to have synced. There is a 1 MB size limit for parcelables being passed between Activities. One common tactic is to save the information to a file and send a URI to the location of where the information can be retrieved.
Answering your question - yes, there is a situation when you set x = true and value will be 'reset' back to false. Well, not exactly reset but consider this scenario: you have an activity and a service. Service is using separate process (you can define that in AndroidManifest when you declare your service). Then those two processes (main app and service) won't share memory and setting x to true in your activity won't affect the value of MyClass.x in your service. In all other cases changing value in one place will be visible everywhere else. Hope it helps!
No, a static variable will not be changed unless you change it or the app ends, it is safe (but generally unclean) to use it. Closing the activity the variable lives in won't hurt it.
You suggest you just need to keep track of a value as you move around activities. In that case you can add the value in your Intents as what is called an 'extra'. If you need to also pass back the value after, android also has the startActivityForResult feature
Intent extras example:
x below could be any type of value including any object which implements Parcelable
Intent intent = new Intent(...);
intent.putExtra("myKey", x);
startActivity(intent);
in receiving class:
x = getIntent().getBooleanExtra("myKey");
Edit:
Given your additional comment - "lists of objects that contain yet more lists of objects" you may get a Parcel too large exception when trying to use extras, but this is an indication you have a bigger architectural problem and that there may be a better approach
Use Gson.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
You have two options. Convert to string , then put data in an intent then pass to activity. Or Convert to string with gson, save to a preference, then in the other activity, check if the preference is alive and read from it.
If you wish to be bold, you can persist to database preferably using Realm for Android or ObjectBox is a new mobile object database optimized for performance. With ObjectBox, we are bringing technology from NoSQL server databases to mobile.

Store and retrieve arrayList from internal memory?

I'm building a home replacement app. I need to store the ArrayList with the apps the user picked to show on the launcher in the internal memory. I mean the array mustn't be deleted when the app is closed.
I'm very close to finishing the app and I don't think I'll work a lot more on Java, I'm not a programmer so I just want the easiest way to do it. How can I store and retrieve an ArrayList in the internal memory?
Use SharedPreferenes to store and retrieve the arrayList..
Check this link..
Save ArrayList to SharedPreferences
You should store such data as Arraylists in the database and when you relaunch the app just fetch the data from database(SQLite) and display it to the user.
Heres a good tutorial on android SQLite.
Take a look at this link, for all the different data storage mechanisms in android. But for your requirement I would suggest using a db.
The easiest way is to use Java serialsation. It writes the content of an object to a (file-) outputstream. Thats a few lines of code.
a bit better (faster, less bytes, readable by other non java systems) is to uses a custom serialisation, using DataOuputStream. That creates a binary file in the format you define.

Storing State in Android

I have this listview that gets populated with the data that is downloaded from the internet.
Hence in the onCreate() method, I will run the async task to download the information and put it into the listview.
I placed a boolean value to whether if the list is downloaded or not during the saveInstanceState() method, this will work if the user gets out of the app from the home button and returns. However, when the user exits the program through the back button, the saveInstanceState() method is not run.
I do not want to download the list again, how can I check whether if it's downloaded before?
Check this out: Implementing the lifecycle callbacks
http://developer.android.com/guide/topics/fundamentals/activities.html
Use the callbacks to get noticed what happens to your activity and react if nesseceray.
You can use the Shared Preferences to store key-value data:
http://developer.android.com/guide/topics/data/data-storage.html
If you want to persist data beyond the LifeCycle of the application, you'll need to store it outside the Bundle.
Your options are:
Shared Preferences
Internal Storage (on Device)
External Storage (memory card)
Local Database
Network (which would probably defeat your question)
I'd suggest a private Internal Storage file for saving your data.
You can override Activity.onBackPressed() and save your state there as well.
Also, you can do
void onPause() {
if(isFinishing()) {
// save your state. maybe you'd be better off with using preferences (or other things suggested by people here), so you don't need to worry about the instance state.
}
}

Categories

Resources