Android Value of SharedPreferences is not updating while app is running - android

I have 2 activity say for e.g MainActivity and PlayActivity.
I am retrieving value of currentLevel from SharedPreferences in MainActivity using following code.
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
// comment this to see if value is saved or not
currentLevel=sharedPreferences.getInt("currentlevel",1);
and I am Updating value of currentLevel in PlayActivity using following code.
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("currentlevel",currentLevel+1);
editor.apply();
Now my problem is while running app i am not able to update its value. For e.g while i am in PlayActivity and i won a level and i updated value of Shared Preference but while running app if i go back to MainActivity and try to retrieve CurrentLevel value, i got previous value not updated one.
Please Help. One more thing if i push updated of my app in future will sharedPrefrence also get updated with default 1 value or it will retain its previous value.

sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("currentlevel",currentLevel+1);
editor.commit();

I have created a quick sample for you to inspect. It's a "Empty Activity" project (as per the latest Android Studio template) with all defaults (in Kotlin).
After the project was created, I added a second Empty Activity (via the same template), and then I modified their layouts to have an Edit Text and a button.
What do Activities do when they start?
Load any existing Shared Preference value.
Populate the EditText with the existing value (which defaults to 0)
What does button click do?
Save existing value into shared preferences.
Launches next (or previous) activity.
Activity 1 goes to Activity 2, and Activity 2 goes back to 1.
Notice how no matter what number and what activity you use, the other picks it right away.
Here's where I left the project for your inspection:
https://github.com/Gryzor/MySharedPreferences
If you don't want to bother with a git clone, here's what Activity 1 does:
// Obtain our private Shared Preferences
// This comes from ContextWrapper.
val sharedPreferences = getSharedPreferences("sample", Context.MODE_PRIVATE)
// restore existing value
val current = sharedPreferences.getInt("A_NUMBER", 0)
editText.setText("$current")
button.setOnClickListener {
val text = editText.text.toString()
val value = try {
text.toInt()
} catch (e: NumberFormatException) {
0
}
// Save the current value
sharedPreferences.edit().putInt("A_NUMBER", value).apply()
// ... and go to the next activity
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
finish()
}
The other activity is identical, sans the intent line:
val intent = Intent(this, MainActivity::class.java)
Conclusion
What I wanted to point out with all this nonsense, is that you are mismanaging your instances and not correctly using something. It's hard to tell because we haven't seen your source code.
Good luck :-)

Related

Saving Fragment's State Through out the application

I have an application where app has both online & offline mode.
Once the fragment is loaded a network call is made and data is set.
The user makes some changes into fragment UI like adding buttons, Editing TextBoxes etc. I have to maintain that state throughout the application.
I have next & previous buttons, when i press on previous button on the fragment is reloading even though i tried to adding it to back stack while replacing it and calling getActivity().onBackPressed();.
Things I have Tried :
1) saving the values into bundles is too much data & hard ti retrieve due to bulk of data/values.
If you use viewpager, you can keep the last state of the fragments and it will not reload untill the offscreen limit u set as below.
mViewPager.setOffscreenPageLimit(limit); //limit: integer value >=1
If you have large number of data you want to save, use SQLite, otherwise you can use Shared Preferences
For more info visit this link
First get the reference to your shared preferences file
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
after this write to Shared Preferences with
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "value");
//use editor.apply() if you want to save your data imedialtly
editor.commit();
when you want to retrieve the data (onCreateView/onViewCreated)
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
EditText editex = (EditText) view.findViewById(R.id.your_view_id);
editext.setText(sharedPref.getString("key", defaultValue))
}
But keep in mind, Shared Preferences will save and keep your data even if your app is killed/destoyed

How to create pop-up when first open app in Android?

I write an application, I want to get a phone number, but getline1number() not working on any devices.
So, I want to create a pop-up to enter a phone number and submit to save and don't show in next time open app.
Like this:
You can always use SharedPreferences to do such things:
SharedPreferences sp = getSharedPreferences("FirstTimeFile", Context.MODE_PRIVATE);
/**
* when the app is opened for the first time, no such variable
* (appIsOpenedForTheFirstTime) exists. So, it becomes true.
*/
boolean appIsOpenedForTheFirstTime = sp.getBoolean("IsAppOpenedForFirstTime",true);
//since it is true, it will be set to false after the execution of following block:
if(appIsOpenedForTheFirstTime) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("IsAppOpenedForFirstTime", false);
editor.commit();
//PUT THE CODE FOR YOUR POPUP HERE
}
As the SharedPreferences values remain in the application data even after you close the app, so the next time you open the app, the value of appIsOpenedForTheFirstTime will be false and hence your pop-up code won't be executed.
Ah, as a side-note, if you clear the app data, everything gets cleared - including the SharedPreferences. Read this official article for in-depth understanding.

SharedPreferences in Android saving the visibility of an ImageView

I have a menu activity that acts as a level selector. When the user finishes a level (activity) and returns to the menu, I want it to set an image visible in the menu to show that said level has been completed. Also, I want this info to save from a session to another.
My aproach has been to try SharedPreferences. This is the code from the level activity that writes the save:
private int levelNumber
SharedPreferences save = getSharedPreferences("SaveGame", MODE_PRIVATE);
SharedPreferences.Editor editor = save.edit();
editor.putInt("levelComplete",levelNumber);
editor.commit();
GameActivity.this.finish();
This is the relevant code from the menu that reads the save and sets the image visible based on the levelNumber:
clear_stage = new ImageView[clear];
clear_stage[0] = (ImageView)findViewById(R.id.clear1);
clear_stage[1] = (ImageView)findViewById(R.id.clear2);
clear_stage[2] = (ImageView)findViewById(R.id.clear3);
clear_stage[3] = (ImageView)findViewById(R.id.clear4);
clear_stage[4] = (ImageView)findViewById(R.id.clear5);
SharedPreferences save = getApplicationContext().getSharedPreferences("SaveGame", MODE_PRIVATE);
clear = save.getInt("levelComplete", 0);
clear_stage[clear].setVisibility(View.VISIBLE);
I have the visibility set to "gone" in the xml, by the way.
Now, my main problem is that the visible image changes every time that a level is completed, and the last image goes invisible again (gets overwritten).
Is there a way to store the clear value each time a level is complete?
I tried with:
SharedPreferences saveall = getSharedPreferences("SaveGame", MODE_PRIVATE);
SharedPreferences.Editor editor = saveall.edit();
editor.putInt("clear_stage",clear);
editor.commit();
But it isn't working, and I don't really know what I should do next. Ask me anything if the post wasn't clear enough.
I think your problem is that your'e loading as an int, not an array. I would look here for a better explanation. Is it possible to add an array or object to SharedPreferences on Android particularyly sherifs' answer

How to pre populate data between the screens in android

I have an app with 3 screens.
For each screens i have next button in each screen to go to the next screen.
problem:
Scenario 1:
--> I filled the data in first screen
--> I go to the second screen.
--> When i come back to the first page i am able to see the data what i filled.
-->But when i again go to the second page i am not able to see the data what i filled in the second form.
How can i manage this in android?
Thanks in advance...
You can save the data in Shared preferences. Check this : Shared Preferences Android and Example
Hope this helps.
You need to save the state yourself using your activities' lifecycle methods. Read this: http://developer.android.com/training/basics/activity-lifecycle/recreating.html
You can save temporary data in application data. Once in the onCreate method, you can reuse that data, or you can use an activity flag to ensure that there's only one instance of your activity in the backstack.
try
{
//in first run app. go to catch and in other go to try
SharedPreferences pref = getSharedPreferences("pref",0);
SharedPreferences.Editor edit = pref.edit();
String x= pref.getString("login", null);
edit.commit();
if(x.equals("first"))
{
//here you can fill editbox by value you entered before
edt1.setText(x);
//and make this way to all edittext
}
}
catch(Exception e)
{
SharedPreferences pref = getSharedPreferences("pref",0);
SharedPreferences.Editor edit = pref.edit();
edit.putString("login",edt1.getText().toString());
//edt1.getText().toString() value(s) you want to save
edit.commit();
Intent intent = new Intent(getApplicationContext(), First.class);
startActivity(intent);
}

android Shared Preferences issue

i want to force use to fill Settings Page in two cases
1) when user first launch Application
2) when database version is change i want that setting page should be filled first before proceding
in my Setting class i set shared preferences "false" , and then i check it in below code
class setting //main class
String flag = sharedPreferences.getString("CreatedFlag","");
if(flag.equals("true"))
{
// Move to second activity
Intent i =new Intent();
i.setClass(someclass.this,otherPage.class );
startActivity(i);
finish();
}
else
{ // Stay on Settings page }
Problem : it run fine when user first launch application ,it show setting page and fill tht page ,
but when user run application second time it show setting page again ,coz shared preference still have true value ,
thn again user run app 3rd time Shared Preference have update value which is false ,and show other page
what i want is tht Setting page show only once if its there is no setting define ,other wise it goes to home page
need help ,
I dont shee here where you're actually saving the preferences, I assume its in the otherPage activity??
If not add this to the first activity
SharedPreferences prefs = this.getsharedPreferences("myApp",0);
//check for the Created value in the shared preferences
String createdFlag = prefs.getString("Created","false"); // set default value == false
if(createdFlag == "false){
goToSettingsPage(); // to the settings page we go...
}
Then on your settings page:
SharedPreferences prefs = this.getSharedPreferences("myApp",0);
SharedPreferences.Editor ed = prefs.edit(); // create the editor
ed.putString("Created","true"); // put the value to the prefs
ed.commit(); // commit the changes
After the first run, the shared prefs file will be persisted, and then should not goto the settings page the second time its run.

Categories

Resources