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

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

Related

How I can create history layout in android studio such as recent

I am building an app include edit text and button. The user can put text in the edit text, then click button to transfer him to the browser.
So, I would like to create other layout as recent to store the text that the user entered on the edit text.
How I can do that? I need the logic or code that can help me!
Also, should I have create database to store the data?
Example:
enter image description here
You can store data in multiple ways, and you will need to understand what is right for your use case. You can store data in memory, by simply creating a List with your data type and adding to it every time user will click a button, but then it will not persist between sessions with the app.
If you want the data to persist, then you would need to use permanent storage, and there are a lot of options here:
You could use Shared Preferences
You could use File System and save the data to a file
You could use a database i.e SQLite, and store data there
You could use external server, and get the data through REST API.
Generally, there is a good overview of data storage in Android in the documentation which also have code examples.
Every option comes in multiple ways to accomplish it. There are built-in solutions, and multiple libraries to help you with this task, but first of all, you will need to understand what is the predicted usage of this data. I.E Should user have access to the data from another device? Should the data be available offline? Will data have complex structure? How the app can expand in the future? e.t.c.
Only by knowing this you can design how you will handle it.
If you need logic or code to create view, then you will need ListView, or RecyclerView, Adapter for handling the data, extra xml layout file for single item of your data.

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.

Saving Android Application State Using Static Constants

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.

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.
}
}

Android storage advice?

When I log a user in, I pull down some user data. It's just a userid and stuff like that. A couple of strings really. The thing is I don't want to pull this down every time if it's the same user over and over and so I want to store it locally across sessions. I'm aware of SQLite but is making a table just for 1 row really the best solution? Is there not another, better way?
Check the developer.android.com site. Data Storage :
http://developer.android.com/guide/topics/data/data-storage.html#pref
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types
If primitive types is all you need, and the boundary is your application (no multi process stuff), then you should be OK with just using SharedPrefs. Anything else (files,sqlLite) is overkill. SharedPrefs has a clean api that should be sufficient for your needs.
See the developer.android.com site for shared pref usage.
You could use Shared Preferences. It is meant for that.
This other question asks about storing files on the device. The recommendation is to store files on the SD card (if available) and that could be a solution to your problem.

Categories

Resources