SharedPreferences putInt method not working - android

private boolean rightReviewTiming() {
int insertKitCnt = sharedPreferences.getInt("insert_kit_cnt",0);
insertKitCnt++;
sharedPreferences.edit().putInt("insert_kit_cnt", insertKitCnt);
sharedPreferences.edit().commit();
insertKitCnt = sharedPreferences.getInt("insert_kit_cnt", 0);
Log.d("ehhehe", "rightReviewTiming: " + insertKitCnt);
if((insertKitCnt % 11 == 0) && (insertKitCnt % 2 == 0)) {
return true;
} else {
return false;
}
}
I want to update insert_kit_cnt key. But, its log always shows '0'. If you know where is the issue, please let me know about that. I think maybe insert_kit_cnt commit is not working. Is commit timing wrong?

Do the commit or apply on the editor that you're making change on.
sharedPreferences.edit().putInt("insert_kit_cnt", insertKitCnt).apply();

You are creating two editor references. You need to use only one reference of editor:
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("insert_kit_cnt", insertKitCnt);
editor.apply();
Or in one-liner code, you can also do like this:
sharedPreferences.edit().putInt("insert_kit_cnt", insertKitCnt).apply();

Related

Unity toggle to save password works flawlessly in Unity but doesn't work as expected

I have a problem with saving users login and password in PlayerPrefs. While it works very well in Unity (if the password is saved, the toggle is on on start) it doesn't work on Android (if the password is not saved, the toggle is still on on start). Before building for Android, I'm making sure that the toggle is off and password is not saved.
Here is my code:
void LoadUserPassOnStart(){
if(PlayerPrefs.HasKey("userSaved")){
if(PlayerPrefs.GetInt("userSaved") == 1){
loginEmail.text = PlayerPrefs.GetString("savedUsername");
loginPassword.text = PlayerPrefs.GetString("savedPass");
saveUserPassToggle.isOn = true;
int saved = PlayerPrefs.GetInt("userSaved");
Debug.Log(saved);
}
else if(PlayerPrefs.GetInt("userSaved") == 0)
{
saveUserPassToggle.isOn = false;
Debug.Log("Called false");
}
}
}
void SaveUserPass(Toggle saveUserPassToggle){
if(saveUserPassToggle.isOn){
PlayerPrefs.SetString("savedUsername", loginEmail.text);
PlayerPrefs.SetString("savedPass", loginPassword.text);
PlayerPrefs.SetInt("userSaved", 1);
Debug.Log("Saved");
}
else if(!saveUserPassToggle.isOn){
PlayerPrefs.SetString("savedUsername", "");
PlayerPrefs.SetString("savedPass", "");
PlayerPrefs.SetInt("userSaved", 0);
Debug.Log("Nulled");
}
}
I'm calling LoadUserPassOnStart in Start(){} and I'm adding SaveUserPass to the toggle:
saveUserPassToggle.onValueChanged.AddListener(delegate{ SaveUserPass(saveUserPassToggle);});
This issue drives me nuts, will be very grateful for suggestions.
try using PlayerPrefs.Save(); after Set the keys.
The issue was caused by the fact, that Android stores the info from PlayerPrefs even after the game is uninstalled.

Create a function that fires only once after app is installed on phone

I'm developing a mobile app using ApacheCordova/Phonegap.
I need a function that sends a SMS to me once per install. If I put my function on "DeviceReady" it will be run each time the app opens.
Is there any solution for a function to be run when app is installed OR when it runs for first time?
Any suggestion would be appreciated.
Check if it is the first time with a method and then perform the action if that method determines that it is the first time.
Ex:
isFirstTime() Method
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
// Send the SMS
}
return ranBefore;
}
You may want to add it to your onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topLevelLayout = findViewById(R.id.top_layout);
if (isFirstTime()) {
topLevelLayout.setVisibility(View.INVISIBLE);
}
I added a field to the localstorage and on startup just check if that field exists. So something like this:
if (window.localStorage.getItem("installed") == undefined) {
/* run function */
window.localStorage.setItem("installed", true);
}
Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android
This should be what u are searching for:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false))
{
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Use some boolean value if its true don't call that function other wise call that function example is here
if(smssent!=true)
{
//call sms sending method
}
else
{
//just leave blank or else notify user using some toast message
}
Note:-the boolean value store in some database like sharedprefernce or sqllite, files....

SharedPreferences lost on force quit?

I've added the SharedPreferences functionality to my App to launch a specific activity once the App starts after it has been quited.
I use the following code to save the string:
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("Stringval", "view1");
editor.commit();
Then the following to load the last used activity, this code is below OnCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref1.getString("Stringval", null);
if(str1 == "view0")
{
setContentView(R.layout.activity_view0);
}
else if(str1 == "view1")
{
setContentView(R.layout.activity_view1);
}
else
{
setContentView(R.layout.activity_no_setup);
}
}
The code works if the user just quits the App, then relaunches it (Only tested it in the Simulator so far) but whenever I use the task manager to force quit the app like this:
The App just relaunches without using the SharedPreferences.
What's the reason for the App to not load the SharedPreferences or is this just a simulator bug?
You can write
if(str1 != null && str1.equals("view0"))
{
setContentView(R.layout.activity_view0);
}
else if(str1 != null && str1.equals("view1"))
{
setContentView(R.layout.activity_view1);
}
else
{
setContentView(R.layout.activity_no_setup);
}
try this, May be helpful for you......

Do something when an activity loads 'N' times in android

I am developing an android app and I want it to do a particular action(say for example, go to a particular URL) when the user loads it for 'N' times. How do I go about doing it. I know its got to do with SharedPrefs and Activity LifeCycle but I am not being able to get a headstart into it. Can someone plz suggest how to proceed.
Use the onCreate method in your activity to set a counter in SharedPrefs. Increase it by 1 each time and when it reaches N, do your thing..
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
int count = sharedPreferences.getInt("count", 0);
if (count == N) {
...
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("count", count + 1);
editor.commit();
}

Using SharedPreferences to store data for use by Broadcast Receiver not working

I'm writing some code that turns airplane mode on or off (depending on user choice) when the screen turns on. I've kept flags for the user's choice (0 for off and 1 for on). For some reason though, no matter what the user picks, the value for the choice (airplanei) is always 1 in the activity. I'm sure the error is somewhere in the code I've posted; incorrect use of SharedPreferences most likely.
Code for Activity:-
protected void airplane(int i) {
// Store flag in SharedPreferences
SharedPreferences flags = this.getSharedPreferences("toggleflags",
MODE_WORLD_READABLE);
SharedPreferences.Editor editor = flags.edit();
if (i == 0)
editor.putInt("airplanei", 0);
else if (i == 1)
flags.edit().putInt("airplanei", 1);
else if (i == -1)
flags.edit().putInt("airplanei", -1);
editor.commit();
}
Code in Broadcast Reciever: -
public class Screen_On extends BroadcastReceiver{
#Override
public void onReceive(final Context context, Intent intent) {
SharedPreferences flag = context.getSharedPreferences("toggleflags", 0);
int i = flag.getInt("airplanei", 1);
if (i == 0) {
//Code to turn airplane mode off
} else if (i == 1) {
//Code to turn airplane mode on
}
}
}
Thanks for your time.
As #Matt already said you actually create two new instances of Editor but commit only first:
flags.edit().putInt("airplanei", 1); // New editor here
...
flags.edit().putInt("airplanei", -1);
...
editor.commit(); // Commit first editor instance
When (i == 0) you use editor.putInt() and for (i == 1) and (i == -1) you use flags.edit().
I believe you should use editor.putInt() for them all.

Categories

Resources