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.
Related
I have 2 int in my navigation drawer, the value of whom changes upon clicking different button on different locations in the app.
I got the code to successfully increment and update them, but the problem is that they got reset when I open the app after closing or exiting it.
How can I make them stay there after getting updated?
If you want any code from my app, then please tell me.
Sorry for bad formatting of the question, but I have no idea how to do this and hence I haven't posted any code.
You must save the info in a persistent storage.
You can use SharedPreferences.
SharedPreferences prefs= getSharedPreferences("aName", MODE_PRIVATE);
//save the value
prefs.edit()
.putInt("nameOfTheValue", theValue).apply();
// get the data
prefs.getInt("nameOfTheValue", aDefaultValue);
You should save them as User SharedPreferences in onDestroy method.
public void onDestroy() {
super.onDestroy();
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//set the sharedpref
Editor editor = settings.edit();
editor.putInt("FIRST_INT", firstIntValue);
editor.putInt("SECOND_INT", secondIntValue);
editor.commit();
}
And then you can get them back wen needed:
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//get the sharepref
int firstInt = settings.getInt("FIRST_INT", 0);
int secondInt = settings.getInt("SECOND_INT", 0);
I'm trying to make a custom preferenceDialog which has four radioButtons, I would like to save the selected radiobutton with a diferent String and persist the value. Whe the dialog reopens, recover the string, compare and check the matched radiobutton.
I've tried persistance functions but I'm not able to achive it..
Can someone help me please?
How about using SharedPreference to persist values?
Code Example:
// Gets SharedPreference with private mode
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
HARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
// Saves int values
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(KEY_NAME, value);
editor.commit();
// Gets int values
sharedPref.getInt(KEY_NAME, defaultValue);
I have created an app for alarm service..such that a person can set a alarm to a specific time and the alarm will pop up as a notification..Now i want to create that alarm service app to a task reminder app such a way that at the time of creating or setting the task , user input the message in the edit text and save it and then when the alarm pops up , and if the user taps the notification , a new activity comes up and the message that he typed earlier is printed in front of him..(i mean the message is show as a text view to him) So Please tell me how could i do that using shared preferences..
In simple way just tell how could a load the stored string from the activity where the string was created and save with the help of a button and to load that same string and pass it in a text view to some other activity..
You can use shared-preferences to store data in one activity. and these data will be available in any activity with in same application.
http://developer.android.com/reference/android/content/SharedPreferences.html
example is available at http://developer.android.com/guide/topics/data/data-storage.html
Good Luck.......
I would like to suggest you to do all your preference tasks in your Application Utils.clas
// Declaration
public static String KEY = "SESSION";
// Method declaration :
public static void saveUserName(String userid, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", userid);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
// You can save the values in preference by calling the below :
Utils.saveUserName("12345",YourActivity.this);
// Finally you can retrieve the stored value by calling this code snippet :
String myUserName = Utils.getUserName(YourActivity.this);
Hope it helps
You can use SharedPreferences.
Using setSetting, you can set the text at caller class. Similarly, you can get the text which was set in the caller class using getSetting in the called class.
Method to set the Preference-
public void setSetting(String key, String value) {
if(getActivity() != null)
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
// Commit the edits!
editor.commit();
}
}
Method to get the preference-
public String getSetting(String key, String def) {
try
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
return settings.getString(key, def);
}
catch(Exception e)
{
e.printStackTrace();
}
return "";
}
Here,
public abstract SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.
More on Android developer reference.
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'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