I'm trying to write an activity that would be able to both write and read sharedpreferences data.
I initiate SharedPreferences at the beginning
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Then this function writes an int to SP and call another function.
public void SetHue(int i)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", i); // value to store
editor.commit();
ApplyHue();
}
this other function should read that int from SP...
public void ApplyHue()
{
int hueInt = preferences.getInt("storedInt", 0);
/// adjust background image hue according to hueInt.
}
I can't simply pass this int from one function to another, because I need other activities to be able to run ApplyHue() function, which should use hueInt from memory.
What do you think might be causing it to crash?
Thanks!
I think you wrote this line in the class before your onCreate method.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Decalare SharedPreferences preferences; in the class and then in onCreate
preferences = PreferenceManager.getDefaultSharedPreferences(this);
Hopefully your problem will be solved
Related
How to display an AlertDialog based on the number of execution of an activity(MainActivity). For example if MainActivity is opened for 5 times then i need to display an AlertDialog.
Saving data in Preference:
private static void saveCounter(Context context, int value) {
SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("count", value);
editor.commit();
}
Retrieve data from preference:
private static int getCounter(Context context) {
SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try {
return prefs.getInt("count", 0);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
These methods will make your work easy and you just have to pass the incremented value to saveCounter for saving the value and then for getting the value use getCounter
Dear archana,
Please save the varible/flag in SharedPreferences. Check varialble value (whether 5) then increment on every execution of activity until 5 and save to sharedprefrences and get it from there with every launch of activity.
In oncreate method of activity please update the variable with increment+1 and save it and check it in next launch
For more visit:
http://www.tutorialspoint.com/android/android_shared_preferences.htm
Thanks
Initialize your counter to 0 and increment it in onCreate() and onResume() methods of your activity. As soon as you increment these values, store these values in Shared Prefrences(as described in above answer). If you have trouble using Shared Preferences, try TinyDB, it is based on Shared Preferences and is much easier to handle.
I am trying to save data using default Shared Preferences, but cannot get this code working.
I cant retrieve an int value in another activity.
In my first activity, in onCreate, I want to create a scorecounter that counts up every time you receive points. It will be initiated on first run.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
if (preferences.getBoolean("first_run", true))
{
editor.putInt("totalpoang", 0);
editor.commit();
preferences.edit().putBoolean("first_time", false);
}
In my Activity B I want to retrieve the value, modify it, and then save it in preferences again.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
int poang = preferences.getInt(totalpoang, 0);
editor.putInt("antalpoang", totalpoang);
editor.commit();
However I only get the error totalpoang cannot be resolved as a variable.
I initialized it as a int in the first Activity, and I am trying to retrieve it as an int.
What am I doing wrong?
Change this
int poang = preferences.getInt(totalpoang, 0);
//editor.putInt("totalpoang", 0); // key is "totalpoang"
to
int poang = preferences.getInt("totalpoang", 0);
And then
editor.putInt("antalpoang", poang);
I have 27 characters that I want a player to unlock by beating scores, e.g. if his score is greater than 200 he unlocks character #1. I have a hard time trying to do that.
I have a class for characters that contains its number, the score required to unlock it, and a boolean to check if he is unlocked. But when it comes down to saving, I can't do that.
The main game loop is in file GameScreen. It has a value points counting the score.
When GameState changes to PlayerDead I want to check if any new character has been unlocked, and whether the high score has been beaten to save points.
Please help, I'm struggling with it for over a week and I can't find a good tutorial for SharedPrefs because all of them apply to GUI based activity that saves the name and surname you entered.
if you need sharedPrefs I can help you.
I can give some some example code.
or you can send your code and error if you get one, we update it.
but sharedPrefs is a good idea for that ? if user goes to application settings and clears data of your app, all data will be lost.
why dont you try create a sqlite databade, save it into assets directory and use it?
It's actually pretty simple, you use SharedPreferences to store key-value pairs. You can either call
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
From the GameScreen and then define a constant:
public static final String KEY_SCORE = "score";
To use as the key for the saving.
In order to actually save, you need an Editor:
SharedPreferences.Editor mEditor = mPrefs.edit();
//save data now, mPlayerScore is the score you keep track of
//if it's another type call putString(), etc
mEditor.putInt(KEY_SCORE, mPlayerScore);
//if that is the only thing you want for noe
//close and commit
mEditor.commit();
And in order to retrieve the saved score, during your onCreate() you can do:
public void getUserProgress() {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//no need for an editor when retrieving
mPlayerScore = mPrefs.getInt(KEY_SCORE, 0);
//second value passed was the default score
//if no score was found
}
In order to check for new character s being unlocked, you can call the following code after every game:
private void checkForUserUnlocks() {
if (mPlayerScore >= MyUnlockableCharacter.SCORE_NEEDED_TO_UNLOCK)
MyUnlockableCharacter.isUnlocked = true;
//and same for other unlockabld characters
}
There are other ways to access SharedPreferences, let me know if you need more info.
Use the below code to store and retrieve Score from SharedPreference.
public static void saveScore(Context context, int score){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("SCORE", value);
editor.commit();
}
public static int loadScore(Context context){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
int score = sharedPreferences.getInt("SCORE", 0);
return score;
}
Read Sample;
public int Read() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
int mCounter = mSharedPrefs.getInt("Counter", 0);
return mCounter;
}
Write Sample;
public void Write() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
mPrefsEditor.putInt("Counter", 15);
mPrefsEditor.commit();
}
I am trying to save a date in one activity and then have that date put in a textView in another activity. I am not sure about how to get the two activities to communicate with each other.
In file called report.java I have this method that gets the date and save it in sharedPrefernces.
private void updateLabel() {
date.setText(fmtDate.format(dateAndTime.getTime()));
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("date", date.getText().toString()); // value to store
editor.commit();
}
I am trying to figure out how to get my file called inspection use this to populate a textView
The problem I think I am having is with getting the correct name for the report file.
public static final String PREF_FILE_NAME = "report";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
then I have this code on a method called onResume()
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String strDate=preferences.getString("date", date.getText().toString());
date.setText(strDate);
}
You are saving the value to two seperate preference files.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
Use only one.
Why not use the default preference file that is accessible by all classes/activities of your app?
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(yourContext);
preferences.edit().putString(YOURKEY, yourStrValue);
This way you are not creating extra preference files in your app that you have to remember which values are stored in which files. Definately makes life easier.
I have an Android application in which I have my preferences in an XML file, which works fine. I now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?
I assume by preferences you are referring to your application's preferences and not Android phone settings.
To store preferences between runs of you application you need to do the following
Create a SharedPreferences object
SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
String n identifies your preferences and the second argument is the mode they'll be accessed
Instantiate an Editor object
SharedPreferences.Editor editor = settings.edit();
Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work
Write your preferences to the buffer
editor.put...(String, value)
There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)
Flush the buffer
editor.commit();
This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.
These preferences will by stored on the phone and will only be accessible to your application.
More documentation is here
I tried this but didn't work:
SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
Try this instead:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
You can save something in the sharedpreferences by using below code
public static void save(String valueKey, String value) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.putString(valueKey, value);
edit.commit();
}
To read preferences:
public static String read(String valueKey, String valueDefault) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
return prefs.getString(valueKey, valueDefault);
}