This question already has answers here:
can someone explain me how SharedPreferences works in Android in a very detailed yet easy understanding?
(2 answers)
Closed 6 years ago.
I'm trying to save information on an Android app I've made. I want to save a name, "Robert". For this I've been looking into Shared Preferences and I can't find a tutorial that explains how to create SharedPreferences.
All tutorials start like this:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
But they don't explain where the getPreferences() take the object from.
When is this object (SharedPreferences object) created? Is it created along with the context? Is it created together with each activity?
I'm pretty new to Android, but an intermediate(minus) Java programmer.
SharedPreferences are created like this:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Robert");
editor.commit(); //Or use editor.apply()
Then you get them again like this:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
So, the getString() gets the value you stored before, and returns the default value if you haven't stored a string for 'name' yet.
The object you store is saved in the system, and is constantly available to be grabbed.
UPDATE:
The getSharedPreferences() method returns a SharedPreferences.Editor interface.
According to the android docs
Interface used for modifying values in a SharedPreferences object. All
changes you make in an editor are batched, and not copied back to the
original SharedPreferences until you call commit() or apply()
UPDATE 2:
This answer contains more info on the storage of SharedPreferences.
SharedPreferences are stored in your app's data folder as an xml file. It doesn't matter what context you use to getSharedPreferences from. It will pull those preferences from that file. Once loaded for the first time, the preferences file is cached process-wide so you will get the same object back on each subsequent getSharedPreferences call (even if they are from different Activities).
More information here and here.
Related
I have 3 activities, that connect like this:
A -> B -> C.
On A you input a text that will be used in C, then B opens and you input another text to be used in C. But when C opens, produces null errors.
I came up with a solution, to start A then go directly to C and onCreate of C, start B as if it was going from A to B.
Is there a better solution? Is my solution decent or will it cause more problems than it fixes? Thanks for any help.
There are several options - Intent extras, SharedPreferences, SQLite database, internal/external storage, Application class, static data classes etc.
For situation you've explained, I recommend using SharedPreferences to store data, it's relatively easy approach and you can access stored data at any time from any Activity or class, here is a simple usage guide:
Input data into SharedPreferences:
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Get data from SharedPreferences:
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}
You have 4 solutions in this case the
first one is which you mentioned
the second one is using an intent with put extra in every activity that you will go from
the third solution is using a static variables so that the variables will not be affected if activity reopened (not recommended)
the fourth one you can use shared preference to save the data (which will be the best solution in my opinion)
This is not a very good idea as their may be delays in starting the activity as you would be doing some other operations as well in the onCreate method of activity B and C. Will cause performance issues in future due to delay in showing the activity.
Things you can do...
If the data is very small lets say a key value pair then why not use shared preferences.
Or use a database to store the data as and when it gets created, after which when the activity is created query it and show it.
I think, You can pass the input to next activity through intent.
Since it is a text input,
intent.putExtra("A_Activity_Input","YourinputString"); //in activity A
Then Activity B starts, Get the string using
String Input_A_Activity=getIntent().getStringExtra("A_Activity_Input");
After When you are starting C activity from B, send both data using intent
intent.putExtra("A_Activity_Input",Input_A_Activity);
intent.putExtra("B_Activity_Input","YourinputString");
In Activity C, Get the string from the intent.
Since you just need a data to process, Storing it in SQL or SharedPref or something else wastes memory
I'm currently making a simple RPG in Android Studio using Java, and am having trouble identifying the best way to store and modify the game variables, such as player name, money etc.
The videos and resources I have looked at have offered multiple solutions, such as passing the variables through to different intents using bundles, using singletons, using shared preferences or simply using static variables.
Originally, I was planning to use an instance of a 'PlayerInfo' class in the main activity to store the information, and use bundles to pass the data, however, as the data will be needed in almost every activity, is this the best way?
Thanks for any help!
The ideal choice in your case would be to use SharedPreferences and store items as key value pairs! You can write to sharedpreferences file this way:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
And read from the Sharedpreferences file this way:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Here is a complete tutorial on Sharedpreferences if you dind it hard!
Note: Sharedpreferences will only be a good option if the data you are saving is small, if your data is large and has relationships in between, would advice you to use Sqlite or Realm
I need to store the user input and other string to a local storing method to use it later. Also I need to update it with data every time the user inputs other preferences and read it. I've chosen JSON for this task, hope it's the best option.
My problem is that every time I close the app (or update the app version) the file gets reset.
I would save the JSONObject to the internal storage and update, change, read and check for its existence every time the app starts.
This file is the core of my app as it stores the preferences.
UPDATE:
I've used SharedPreferences to do my task:
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
Ok, I've switched to using SharedPreferences. Thanks for your recommendations.
I have a fragment which is sort of like a test. The user can choose from a spinners menu if this test has passed, failed or undecided. Once the user leaves this fragment and then comes back to it later, I want the spinners menu to display what the user had previously selected.
Can anyone tell me how to keep track of this information? I am a beginner with Java and Android programming. Also, let me know if further explanation is required.
It probably depends on what scope you want to be able to refer to these tests in. For example, do you want these fragments to be emptied after the user closes the app, or not?
If it is just while in the app "session", you could just create an object in your fragment and override the onResume method to populate the spinners with the appropriate data.
If you want to save the info after the app is closed, there are a couple of options. For smaller sets of data you could use shared preferences
if you have an undetermined amount of "tests", I would advise saving whatever data you need to a file, and parsing it to fill the fields in the fragments
Take a look at this to get an idea of how to save data: http://developer.android.com/intl/es/training/basics/data-storage/files.html
I've done something similar to what your doing. I used shared preferences to save the string like so
Saving the string you got from the spinner in a fragment
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
mSharedPreferencesEditor.putString("my_unique_key", myString);
// commit changes
mSharedPreferencesEditor.apply();
Remember to always apply the changes after you made them and you can save as many strings as you want as long as they each have a unique key.
Then to retrieve the value just
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String myStringValue = mSharedPreferences.getString("my_unique_key", null);
The second argument (null) will be returned if it could not find any data that had that unique key. (i.e if you haven't saved it yet)
You can also use another string instead of null like this
String myStringValue = mSharedPreferences.getString("my_unique_key", "could not find value");
or if you want to bundle a bunch of data together like say create an object to save a bunch of strings then save that object to a file I could show you that if you wanted to
I am really confused about how to save my ArrayList of custom objects into SharedPreference. I looked up a very popular thread but did not understand solution as certain variables were not given context. My arraylist has certain things like Strings, UUIDs, and Dates, and I do not mind going to API 11 to avoid using gson or json. If someone were to be so kind as to explain the solution in this or provide their own I would really appreciate. I am new to this, been doing for a couple of months and want to make sure I understand everything in depth but my english is not so well. Thank you in advance!
Serialize that arraylist and store it in sharedPreference.
Profile profile = myProfile;
String serializedData = profile .serialize();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Profile", serializedData);
editor.apply();
For Deserialize
String profileSerialized = prefs.getString("Profile", "");
profile = Profile.create(profileSerialized);
I would look into storing the data into a SQLiteDatabase. SharedPreferences wasn't intended to save custom objects. If you really want to use SharedPreferences then Gson will be the best solution. API 11 added the ability to save a list of strings, not objects.