In my Android Application I have to pass data (Variables regarding the state of the application) from an Activiy to another one. And I have to do this many times in others Activities. What's the best and more efficient way to do this? Should I read that information from the share preferences every time I need it or should I send it as an extra in the intents?
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.
Android uses the action ACTION_SEND to send data from one activity to another, even across process boundaries. You need to specify the data and its type. The system automatically identifies the compatible activities that can receive the data and displays them to the user.
This example demonstrate about How to send data from one activity to another in Android without intent. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
It really just depends on how long you need the data. If you only need it for the lifetime of the application then just pass the data with Intents
. This will be the easiest. You can put the data into a Bundle
to make passing them around even easier.
If you need it the next time you log in or you need it to be saved if your app is killed for some reason then use SharedPreferences
You also can store it in SharedPreferences
and open them up say, in the MainActivity
, and pass certain data around. It really just depends on what you need. I hope this helps but if you need a better explanation then please be a little more clear on what you want
In case you aren't familiar with SharedPreferences
, the docs have a good example to get you started
SharedPreferences
I think that it depends on why you need this data... If it is some general settings of the application, I think that user preference is better as it persists, but if it is just some data required by the others activities, you should use intent extras.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With