I have a spin to win activity in my app that user can use to get coins.
i would like to make that after the user use the spinner he would have to wait for 8 hours before being allowed to open the spin activity again.
how to do that ?
one way will be:
determine those 8 hours from the moment he spinned ->
long duration = System.currentTimeMillis() + your8hours;
save this data (sharedpreference) ->
SharedPreferences sharedPreferences = new SharedPreferences();
sharedPreferences = getSharedPreferences("MYDURATIONSAVED", Context.MODE_PRIVATE)
Editor editor = sharedPreferences.edit();
editor.putInt("durationSaved", duration);
editor.apply();
in the new session, you retrieve the data ->
long alreadyExistingDuration = sharedPreferences.getLong("durationSaved", -1);
and simply compare it in order to check if the user is allowed or not to spin again ->
long check = System.currentTimeMillis();
if(check >= alreadyExistingDuration){
allow...
}
if you would have put a sample of your code I would have use it
for example, if you use sqlite, firebase or files to store your data, it may have been a different answer
But the data that you need to store is primitive so sharedpreference should be enough
Related
I'm implementing the concept of if today date is present one alert message show one time only.
Example 5-8-14 only once toast message show.
6-8-14 only once toast message show
'
in every date only once toast show.
Edit:
Only after first start of App, a toast with current date should appear. If I start my app second or third time, then there should no toast appear
Logic:
What:
1. When ever you show the toast, Save the date/day in sharedPreferences.
2. Then each time, compare the value of "today's date" with the sharedPref value, if its different, show the toast.
How:
- Make a function for the toast, inside which update the Shared Pref value.
- In an "if" loop, compare the default shared pref value - so when you run the app for the first time, it'l return the default value and enter the show toast function.
Eg.
if(!(sharedPrefSavedDate.equals(sharedPrefDefaultValue))){
if(!(String.valueOf(new SimpleDateFormat("dd").format(new java.util.Date())).equals(sharedPrefSavedDate)){
showToast();
}
}
Inside showToast(), save the value of today's date in Shared Preferences.
The saved value can be integer or String. Can change .equals to != of = accordingly.
May require:
How to use shared preferences
Example with integer on android developers
Look into sharedPreferences.
Here a Link to android developer: sharedPreferences
Set a bool-value after first start and after each start check this value and if it's true, then don't show toast
GetDate:
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy");
String strDate = sdf.format(c.getTime());
Link: Get current time and date
Write:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBool("Toast", True);
editor.putString("Date", strDate);
editor.commit();
Read:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
bool bToast = sharedPref.getBool("Toast", False);
String strDate = sharedPref.getString("Date", null);
I have my own Objects which I need to store for later use. The User saves this object, it is turned into a JSON String, then when the User is connected to a network, the JSON String is turned back into the object operations are performed on it.
My problem is that, at run time, how do I know how to store the object?
i.e
Gson gson= new Gson();
String pointOfInterest = gson.toJson(point);
SharedPreferences.Editor sharedprefEditor = application_shared_preferences.edit();
sharedprefEditor.putString(?KEY?,pointOfInterest);
What can I use for the value of KEY? If I use an index, it will get reset every time I open or close the app, and this will replace my Objects.
Edit
Sorry I didn't make this clear enough, the method that the above code is in can be run an arbitrary number of times and there could be several pointsOfInterest to store.
First of all, if you use an index, the Preference will stay forever:
For instance:
sharedprefEditor.putString("JSON569",pointOfInterest);
You can also save the index in an other preference; for instance separated by a column:
sharedprefEditor.putString("indexes","569;789;852");
You can, easily check if an instance exists:
myPreference.getString("JSON789","").contentEquals("");
Or get all your instances:
for (int anIndex:indexes)
Log.i("TAG","Current value: "+myPreference.getString("JSON"+anIndex,""));
Please xplain a little bit more your question, I see no difficulties there/
You can name the key whatever you want, just make it consistent. One way to do it is make a constant in your class for it:
public class MyClass {
private static final String OBJECT_KEY = "myObjectKey";
...
Then when you save your object:
Gson gson= new Gson();
String pointOfInterest = gson.toJson(point);
SharedPreferences.Editor sharedprefEditor = application_shared_preferences.edit();
sharedprefEditor.putString(OBJECT_KEY,pointOfInterest);
When you load it, just use OBJECT_KEY to get a string out of the shared preferences:
String objectString = sharedPrefs.getString( OBJECT_KEY, "" );
I have problem understanding shared preferences. I have activity where user will insert password, start price, waiting price etc. My plan was to set starting value, and than user would change that value if he wants.
My question is: If I create prefs in onCreate() method, how change would apply (using SharedPreferences.Editor) when every time i run application it should create new values in prefs.
To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();
No it will change the previous one by key....
http://mobile.tutsplus.com/tutorials/android/android-application-preferences/
EDIT:
OK It turns out this code was working (more or less) I'd left in a line that reset the booleans I was trying to change. Thanks everyone for the help though.
Having trouble using SharedPreferences to read in saved array data when my app starts.
My _dPad Boolean and my _FreePlay Integer loads, saves and passes to and from my _renderer without any problems.
The trouble starts when I try and use some arrays
easteregg[] only has 2 entries right now so obviously I could just just turn them into separate variables but I wish to add more arras of longer length so this makes a convenient test example.
I've noted on the code what appears to happen (the easteregg[] settings just doesn't appear to have changed)
to read data:
// Read saved preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
_renderer._dPad = prefs.getBoolean("_dPad", false); // * works ok *
_renderer._FreePlay = prefs.getInt("_FreePlay", 1); // * works ok *
_renderer.easteregg[0] = prefs.getBoolean("easteregg[0]", false ); // * not working
_renderer.easteregg[1] = true; // * even this is not working
setRenderer(_renderer);
to write data:
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
// As good a time as any to save current config
save = false ; // don't commit if nothing changed.
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = prefs.edit();
if (_renderer._dPad != prefs.getBoolean("_dPad",false)){ save = true ;
editor.putBoolean("_dPad", _renderer._dPad);}
if (_renderer._FreePlay != prefs.getInt("_FreePlay",1)){ save = true ;
editor.putInt("_FreePlay", _renderer._FreePlay);}
editor.putBoolean("easteregg[0]", _renderer.easteregg[0]);
editor.putBoolean("easteregg[1]", _renderer.easteregg[1]);
if (save == true){editor.commit();}
}
And in the .renderer class
// START SAVE DATA
public boolean _dPad ; // false no Virtual Pad *Works Fine*
public int _FreePlay ; // 1 = no free play *Works Fine*
public boolean[] easteregg = new boolean[2]; *Values don't load or save*
//public boolean easteregg[]; // tried this first *CAUSES CRASH*
// END SAVE DATA
Do I have to convert the arrays to strings? I don't get how to change them.
I put your code into a quick activity, creating just the shell of the renderer class as you have above and found that your save boolean is false, so it never commits the preferences.
I forced the save to true, and played around with it and everything worked fine from there.
I'd recommend adding checks to the easter eggs the same as you have for any other preference; test to see if the current value is the same as the saved value, and if not, set the save flag.
I would suggest saving the array as a string in a single variable. It appears you have an array of booleans. So loop through it to make it a series of either ints (0, 1) or the string "true" or "false" then save it to an int or string.
I suspect the probelm might be that your setting name contains square brackets. I think that in key value names, the key name must be a valid variable name. And square brackets are not allowed in variable names.
However i would also expect this to throw an error. Does the code work if you name you settings "easteregg_01" and "easteregg_02"?
The best solutions would be to convert your array into JSON string and store it as preference value. If you have small amount of data, you can as well stick with org.json classes provided by android. If you have more data, GSON pull parser would be better, as it utlizes pull parser. And if you are really lazy, you grab my small databinding library and do:
String jsonState = preferences.getString(GAME_STATE, null);
StateStorage storage = JSONUnmarshaller.unmarshall(new JsonReader(new
StringReader(jsonState)), StateStorage.class);
and it will instantiate java class for you and fill in the data. And to save:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
StringWriter writer = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(writer);
JSONMarshaller.marshall(jsonWriter, ss);
editor.putString(GAME_STATE, writer.toString());
editor.commit();
Databinding library is available on github, or from maven central:
https://github.com/ko5tik/jsonserializer
PS: at the moment I work on injection of preference values ( at the moment primitives only):
https://github.com/ko5tik/andject
hi
I have a scenario like this
I made a chat program where a user can ad friends just like in yahoo messenger or hotmail messenger. If there are many friend requests coming in to one user i´m saving them dynamically
like this: (Every request(string) look like this "queryaddnewfriend:name:UUID")
String msg = intent.getStringExtra("payload");
String[] split = msg.split(":");
String name = split[1];
String UUID = split[2];
if(msg.startsWith("queryaddnewfriend")){
//queryaddnewfriend:name:UUID
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext() );
String frn = prefs.getString("friendrequest1", "");
if(frn == ""){
SharedPreferences.Editor editor = prefs.edit();
String newReq = name.concat(":");
newReq = newReq.concat(UUID); //create the name:UUID string
editor.putString("friendrequest".concat( Integer.toString(1)), newReq);
editor.commit();
}else{
for(int index = 1; index < 1000; ++index) {
String line = prefs.getString("friendrequest".concat( Integer.toString(index)), "");
if(line == ""){
Log.d(TAG,"create new *********************************************");
String newLine = name.concat(":");
newLine = newLine.concat(UUID); //create the name:UUID string
SharedPreferences.Editor editor = prefs.edit();
editor.putString("friendrequest".concat( Integer.toString(index)), newLine);
editor.commit();
break;
}
}
}
So my SharedPreferences has non, one, or many rows like this
Dynamically added (notes the "friendrequest1" incrementation )
prefs.getString("friendrequest1","queryaddnewfriend:name:UUID");
prefs.getString("friendrequest2","queryaddnewfriend:name:UUID");
prefs.getString("friendrequest3","queryaddnewfriend:name:UUID");
The friend requests are showed to the user one by one starting with friendrequest3.
The problem comes when the user accept a friend request.
I have to remove the friendrequest3 and at the same time there could be a
new friend request coming in and the code above is executed adding a new friendrequest4.
Im using C2DM so I have no control when Google cloud is executing the above code.
When i remove "friendrequest3" because user has responded ACCEPT or REJECT friend
I will do editor.remove("friendrequest3") editor.commit();
But if the above code has added "friendrequest4" my code will fail.
the complexity of this code is now quite high and i guess one can make it higher
and at the same time increasing the "bug factor"
Any thought about doing this better would be nice, thanks!
If it were me, I think I'd be using Sqlite for this, not preferences. It's much easier to manage and process rows of data, and you'll also find it's quicker. I've found that writing a series of preferences in quick succession is actually very, very slow, as writing to flash RAM can sometimes take a lot longer than you'd expect. For that reason when I write to prefs, I usually fire off a new thread to do it.
But my suggestion is.... use a database Sqlite to store the incoming messages, and put them behind a content provider.