Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Share Preferences vs Intent extra in order to share data

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?

like image 739
adrian4aes Avatar asked May 22 '13 21:05

adrian4aes


People also ask

What does Android shared preferences do?

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.

How do I transfer data from one Android app to another?

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.

How can I pass value from one activity to another activity in Android without intent?

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.


2 Answers

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

like image 83
codeMagic Avatar answered Oct 30 '22 21:10

codeMagic


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.

like image 26
ChristopheCVB Avatar answered Oct 30 '22 21:10

ChristopheCVB