Is it possible to aggregate key value pairs in the same shared preferences from different activities?
For example, if I have a shared preference named "SP" and it has a key "SP_A" that I have stored it through activity A. This key has some value. How can I aggregate another key "SP_B" with some value, through activity B in the same shared preference "SP", such that in activity C, I can retrieve key values corresponding to "SP_A" and "SP_B" under the same shared preference "SP"?
And if this question is being downvoted, I would encourage to please write in comment your reason to downvote it. If some question is a bad question liable to be downvoted, people should know the reason why it is bad so that they improve their question asking skills and the quality of questions on this forum gradually improves. Anonymous downvoting and running away will not help anyone.
Once you create a SharedPreference using something like:
mContext.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
You can access it and write to it from anywhere in your app in the same way you created it. In fact, its just an xml file within your app's local storage.
Related
I have read many blogs about how singleton are vulnerable in android.so my question is how to maintain such global objects or list in application.i know shared preference is one way but is there any way to maintain such objects or list efficiently.any help will be more helpful.
You can use a file or SQLite database to save data in android app. You can check below links to learn more about saving data in a file or SQLite database:
Saving data to a file is ideal to store long sequences of data that are generally read in order
https://developer.android.com/training/basics/data-storage/files.html
Saving data to a database is ideal for repeating or structured data:
https://developer.android.com/training/basics/data-storage/databases.html
use sharedPreferences, Sqlite database to manage your objects, singletons are not very good, but static variables are more hard to maintain and will make testing the cide more tough, you can use Shared preferences to maintain a global state if the data is not very large, if there is large amount of data then use of sqlite is recommended.
Shared preferences are extremely easy to use, if you have problem using sqlite though you can use orm libraries for android
here's a link to one: http://greenrobot.org/greendao/
If you just want to keep a list as Global until your app is running, then create a new class let's say "Helper" and Initialize a Static List in that class. Now you can access that list anywhere within the app by "Helper.yourStaticListName" and you can also add/remove or get data from the list anywhere within the app.
But if you want to keep that list even when app has been closed, then there are two solutions for that.
First Create a local database "SQLite file" in your app and add/remove or get data from it.
Check this tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
Second solution is to convert your data into a JSON and convert that JSON into String and save it in Shared Preferences. And whenever you need it just get the string from Shared Preferences and convert it into JSON and parse to get the data.
One last thing when you are talking about parsing a JSON, then "GSON library" is a good thing to work with.
Here is the link: http://guides.codepath.com/android/leveraging-the-gson-library
Hope this answer will help you.
How about using Android Service?
You can initialize / start it when your application started (and also stop them when your application stopped) and then bind them whenever you need (put and get your object / list).
I believe it will be an efficient way.
From conceptual point having a static variables or service-locators is very similar to having Singletons. Hence, having them as alternatives may not be be correct, if the intention is to avoid the Global state and consequences.
We can change Singleton-classes into instances, which are instantiated only once and injected into the components and methods as needed. We can use a IoC-framework to handle the injection part or do it manually with a factory pattern to construct (we can restrict only one instance creation as well) instances of the classes. This discussion thread gives lot of insights on the problem and various options.
So if I understand your question right, you need to store some global variables all over your application if that's so please take a look at this question
basically you create a class that extends application which would store anything you would like on start of your app and all of them can be accessed trough out the app.
hope this helps.
If you are trying to create a globally accessible object, the first thing you should ask yourself is: Why? Why do you need a globally accessible object? Most of the time you don't, and you can get away with creating an object with a limited scope which is passed around the app.
There are times when you do want globally accessible resources and using a singleton is just one way to accomplish that. According to the Android Docs your data storage options are:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.
Singletons are great, but the do have their own risks based on how they are implemented. Typically developers use this pattern when you are attempting to share a resource within the application, things like Loggers, Print spoolers, etc. There are multiple ways that you can create Singletons in Java, you can use a Lazy Initialization or Static initialization, each has their own pro/cons. In terms of "vulnerabilities", there are issues with whether or not the singleton is thread-safe, who/what can access it, and so on. This is why it makes sense to try and understand the problem you are trying to solve. Personally, I'm not clear on what exactly you are trying to solve, so I can't really elaborate on how this might help or hurt you. All I can say is that the biggest vulnerability is also it's greatest asset, which is that like most global variables, it can be accessed from anywhere at anytime. There can also be an issue whether or not the singleton is thread-safe.
Personally, I think you need to assess what it is you are trying to solve and the pick the appropriate solution. Maybe using a singleton is the correct solution, maybe it isn't. But understanding all your options and the strength/weakness of each one is going to be the best way to solve this issue. Unfortunately, you haven't provided enough context to your problem for me, or anyone for that matter, to give you a solid recommendation.
The best way to manage global objects is not having them at all. Based on my experience, in a lot of cases there are alternative options instead using singletons. There is so good explained in this post
shared preference is good but some time you will feel problem when do some modification make static constant variable in one pojo java class and use this variable anywhere.because shared preference will not change value after use or unless you dint modify .shared preference retrieving and storing is not very unfriendly. if you use constant you can modify easily .only one class you have to hit
I've come across two classes being used in a tutorial on splash screens PreferenceManager and SharedPreferences. I didn't gain a great deal of knowledge about them from the tutorial though.
So can someone explain to me what both classes do or are used for?
From the Android Developer site:
PreferenceManager:
Used to help create Preference hierarchies from activities or XML.
SharedPreferences:
Interface for accessing and modifying preference data returned by
getSharedPreferences(String, int). For any particular set of
preferences, there is a single instance of this class that all clients
share.
Put simply, PreferenceManager is normally used when you want to create a PreferenceActivity or load in some Preferences from an .xml file in your application with default values, and holds it's own referenced to SharedPreferences.
SharedPreferences is where you handle the storing and retrieving of key/value pairs that make up your preferences. So you can add variables with keys to retrieve the data later. This feeds into the PreferenceManager which can handle adding default values and setting up the default SharedPreferences.
You can use SharedPreferences throughout your application without needing to use PreferenceManager, but the opposite isn't strictly true.
Further reading:
PreferenceActivity (also PreferenceFragment), which uses
PreferenceManager in the examples.
Android Data Storage which
uses SharedPreferences (as well as other options).
Vogella article on Android Persistence.
StackOverflow issue on using SharedPreferences correctly.
Preferences is an Android lightweight mechanism to store and retrieve pairs
of primitive data types (also called Maps, and Associative Arrays).
In each entry of the form the key is a string and the value must be a primitive data type.
WHEN WE NEED THEM:
PREFERENCES are typically used to keep state information and shared data
among several activities of an application.
Shared Preferences is the storage, in android, that you can use to store some basic things related to functionality, users' customization or its profile.
Suppose you want to save user's name in your app for future purposes. You cant save such a little thing in database, So you better keep it saved in your Preferences. Preferences is just like a file , from which you can retrieve value anytime in application's lifetime in a KEY-VALUE pair manner.
Take another example, If you use whatsapp, we have a wallpaper option there. How the application knows which image serves as wall-paper for you whenever you open your whatsapp. This information is stored in preferences. Whenever you clear data for any app, preferences are deleted.
HOW TO USE THESE PREFERENCES :
final int mode = Activity.MODE_PRIVATE;
final String MYPREFS = "MyPreferences_001";
// create a reference to the shared preferences object
SharedPreferences mySharedPreferences;
// obtain an editor to add data to my SharedPreferences object
SharedPreferences.Editor myEditor;
mySharedPreferences = getSharedPreferences(MYPREFS, 0);
// using this instance you can get any value saved.
mySharedPreferences.getInt("backColor",Color.BLACK); // default value is BLACK set here
EDITING SHARED PREFERENCES :
myEditor = mySharedPreferences.edit();
//edit and commit
myEditor.putString("backColor", Color.RED);
myEditor.commit() //very imp.
As explained Artoo Detoo... Sharedpreferences kinda works like sessions in web development. you can use them to pass values from one activity to another and it stays that way as far as the app is in use except otherwise changed..
it is also use to user value (either after login or registration of the user). thats how much i can talk about it
SharedPreference APIs are used to save key-value pairs. They store them in files and are private or public based on the mode you instantiate the SharedPreference object. They are used to store a small set of key-value pairs. This key here is of type String and the value can be any primitive type.
PreferenceManager is part of the Preference APIs. Preference API allows you to define a complete settings UI. This settings UI is an XML layout. You use a PreferenceManager to manage this Preference object's tree. It uses the SharedPreference APIs to store the various settings a user might change using that graphical layout you created.
Reference - "Android Docs Training"
I have an application with 7 separate views. In each of those views there is an option to answer a 'yes' or 'no.' We are trying to save these 'yes' or 'no' values using shared preferences. Then, we want to have a new view/layout and be able to call those values from shared preferences. How do I go about doing that? My group and I have tried several different ways but cannot seem to get it to work. I know I don't have any code posted but it's because my code is just in bits and pieces. Thanks.
In your case I would not use getSharedPreferences() because it creates separate prefs files. Instead, you should use the main preferences file (call getPreferences() from the main Activity). This will be easier for you to manage than using shared preferences files.
I would write some code to show you how to do this, but the Android training page on this is about as clear as can be. Can you look it over and see if it answers your question? If not, post back here for clarification and I'll do what I can to help.
Here's the link to the page: https://developer.android.com/training/basics/data-storage/shared-preferences.html
Simple Do following Steps :
1)call getDefaultSharedPreferences() to create shared preferences
2) for each view just put values
3)in final view just create preference using getDefaultSharedPreferences() and then retrieve all the values
Hope this will help you
I am developing android application. I did not plan my project that much before. So when I thought that I finished my task then I realized that I am not done at all. I have some issues that I figured it out now. I want to go again from the beginning of the project.
I want to get the list of training that is in external database and data will be populated manually using SQLite browser (only training table, columns are _id, title, description, date and time, location.). And onclick of that item in list, it should start new activity with holding the training session all along the application activity. [On Training, people will fill their personal information (Now, person table), where the data of person should be stored in the particular training session].
Now, my questions are;
1. What type of Adapter should I use in this case and why?
2. Should I use shared preferences or Singleton method to keep the session of training all activities of application?
Both of those question are determined by your requirements for this software. You said it yourself that you 'did not plan my project that much before'. Sounds like you're at a point where you need to do some hard thinking about your requirements. Requirements will, in turn, determine the technologies/ methodologies you need to use.
With the information you've provided, it would be impossible for anyone to provide advice that would be anything better than a guess.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In my project I am developing at the moment, I have many configuration settings. Things such as
Alarm times
Amount of items to retrieve from the server
LocationManager integers such as minium location
These are all static final and are all in a class that corresponds to the value.
My question is, are there any problems with moving all of these values to a single static class?
My thinking is that when it comes to testing and tweeking the app, it will be easier to manage.
Building on #Snicolas's answer...
You should indeed persist your CONFIGURATION settings outside of code (file or database). BUT you should not "read" that configuration each time a value is required, that would be inefficient.
Using a class to manage configuration (ie. AppSettings) is a good idea. Making it static is one way to provide singleton-like access. In C# and ASP.NET a web app will guarantee one and only one instance of a static class and therefore multiple un-related requests from different users will share the exact same static values.
But in your case (I see the tag 'android') using Java your best bet may be a Singleton approach. I don't know how garbage collection works in Java but I'd say you should use a singleton to ensure one-and-only-one instance of your settings. The singleton Ensures an instance exists (or creates one if not) and then provides it to the caller.
This may also make it easier to support the ability to change configuration values while the app is running -- you can "watch" for setting changes on a regular basis.
I'm not a Java man but I'd be surprised (well no not really) if there wasn't already a library for handling this very problem.
I am pretty sure you are not talking about constants as you mentionned alarm times.
The problem with using only static fields inside a dedicated class is that your class can be garbage collected if the device is under memory pressure. In that case, they would simply be lost and reset when you would use them again.
So you should really consider persisting them in a file or in a database depending on the amount of data you wanna store. SharedPreferences can be usefull for a small amount of data, otherwise, consider using a database. That's a much more scalable solution and access times are better for larger data sets.
In the Rails world, it's good practice to implement a configuration model class that lazily loads and caches configuration information, which is persistently stored in serialized form in a simple two-column (key and serial data value) table or (less often) a flat file. A configuration editor is then just a View for this model.
This ought to be a good solution in Android as well.
Another idea will be to store these constants in a properties file. And load the constants when you need them. http://viralpatel.net/blogs/loading-java-properties-files/
If you find it convenient, it's a good practice.