Strange Shared Preference on Android - android

I have 2 Fragments. 1st is for calculation while the 2nd is for settings.
I save the settings using SharedPreference.Editor.commit() on onPause() method. No problem so far with the saving. The problem I am facing is retrieving the SharedPreference value on my 1st Fragment. I retrieved the value every time I pressed the count button. For the 1st time, the values I am getting are the ones before change (which is the problem I am facing), I will only get my saved value when retrieving/pressing the count button for the 2nd time or more.
And I try to change the settings and then press home button to terminate the app from outside (which triggers onPause method) and when I reopened the settings, the values did change to my defined settings. So, I am sure the settings did saved when onPause is triggered.
I wonder what is going wrong here. Any helps is much appreciated.
As requested, this is my saving code on my SettingFragment :
#Override
public void onPause() {
super.onPause();
saveToPref();
}
public void saveToPref() {
SharedPreferences settings = getActivity().getSharedPreferences("mysettings", 0);
Editor edit = settings.edit();
edit.putString("begin", String.valueOf(ibegin)).putString("end", String.valueOf(iend)).commit();
}

Initialize your SharedPreferences object somewhere else, and do it once - maybe in onCreate. The reason why you're not seeing the change is because a different instance of SharedPreferences is opened somewhere, with the same constructor, and multiple instances of these do not automatically resolve/merge. While you're at it, initialize the Editor edit instance along with settings.

Ok, I have found my problem. The problem is that onPause() is triggered only when I start another activity (I started an activity onClick of Button count). I changed my code to trigger the saveToPref() by overriding onPageSelected of my ViewPager and on backPressed of my MainActivity.

Related

Detect if app has been opened for 3 times

I want to show a special activity on 3rd launch of my app. I've made some researches and found this Check if application is on its first run. But I still don't know how to detect if it's a 3rd time or not and also in answer on that question was described how to know if app was stopped and then resumed but I need a solution that will show my special activity when user will open it on 3rd time!!!
Can somebody help me with this?
Thank you!
In your launch activity put this code in onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
SaharedPreferences prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
int launch_count = prefs.getInt("launch_count", 0);
if(launch_count>=3){
// third time launch
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
} else {
prefs.edit()
.putInt("launch_count", launch_count+1)
.apply();
}
}
But this solution do not detect recreate activity, that will be reason to increment launch_count counter. You can solve this issue by creating "StartActivity", which increment counter and start main or specialy activity.
In your Application class in onCreate method you can add code that reads integer value from Shared Preferences. If there is no value the value is 0. Then just add to it 1 and save. Then in any activity you can read this value. If value is 3 you good to go.
Better way to store the integer value in your sharedperference. Every time have to check whether the range has been come or not.
Example:
At first time, initialize int i=0 and store the value as 0
Next step, which means on the next time retrieve the value from shared preference and store in it. Then check the value.
if(i==range)
//todo
else
//todo
keep the count in mysql db or shared preference ,and check and update on each launch of the app in splash screen or your first activity ,get the count and
if(count>=3){
// do the operations what you need to here
}else{
//first 3 opening of the app
}

android onDestroy works fine only on vd

Is anyone aware of the reason why my onDestroy method to save a bool inside my shared pref works fine on vd but doesn't always work on real device?
it looks like working when i quit the app and go back further to main screen but not when i quit the app, remain in the app list window and open the app back again.. weird
is there some bug i'm not aware of or may depend on my other classes? if so i can post the code but is very simple, just as said a bool save and a get
edit: if you guys try to create a scrollview in a fragment (frag of a MainActivity), and try to go on edit mode and press back button to quit your app, mess with it a few times and you'll see onDestroy and even onStop won't be called.
Q. So how am I supposed to save my pref before quitting an app in a consistent way? reliable all the times? also for this i'd need an onDestroy alternative not even onStop, cause I need to save pref only before app quit not on activity change, and since onDestroy isn't reliable (from what Android Dev guide says) what should I use??
thanks
WORKAROUND: I placed this in onCreateView()
boolPref = getActivity().getSharedPreferences("pref_bool", Context.MODE_PRIVATE);
firstVisit = boolPref.getBoolean("bool", DEFAULT);
if (firstVisit == false) {
scrollView.setVisibility(View.VISIBLE);
}else{
scrollView.setVisibility(View.INVISIBLE);
}
if (savedInstanceState == null) {
scrollView.setVisibility(View.INVISIBLE);
}
where firstVisit is boolean firstVisit; declared at start.
(this boolean trick was part of a solution from another post, but it didn't work well saved inside onDestroy() or onStop() cause sometimes they don't get called)
then I added this inside my button onClick:
boolPref = getActivity().getSharedPreferences("pref_bool", Context.MODE_PRIVATE);
SharedPreferences.Editor editor_bool = boolPref.edit();
editor_bool.putBoolean("bool", false);
editor_bool.apply();
scrollView.setVisibility(View.VISIBLE);
and it works, what it basically does is: set my scrollview to be hidden everytime my app starts (through savedInstanceState as #bwt suggested below), and remains hidden when i pass to another activity and come back (using bool = true) unless i press the button inside first activity (setting and saving bool == false) so from then on the scrollview is always visible even if i pass to another activity and come back
I think the right moment to save a preference is when it changes, not when the application quits. Specially since Android may choose to simply kill a process (and the included application) without calling any callback. Use apply() instead of commit(), so that the application does not have to wait.
Alternatively you can override onSaveInstanceState(). It is not part of the basic lifecycle but gives you the opportunity to store the current state of your Activity before being destroyed.

Reload Preferences in PreferenceActivity on Resume

In my app, some settings can possibly be changed while the PreferenceActivity is not open, and an issue I'm running into is that addPreferencesFromResource is called in onCreate, so say, I open the PreferenceActivity, then go to another screen from there, then do something that changes the settings, then hit the back key to go back to the PreferenceActivity, then certain settings have not changed on the layout.
So, how could I re-load all the Preferences every time onResume (or onStart()) is called without duplicating the layout?
edit: This solution will work for API 11 + only.
Im not sure I fully understand your problem, but you could add a call to recreate() into the onResume of the activity which from my understanding has the activity go through the entire lifecycle again.
In order to make sure that you only do this when there is in fact dirty data, I would set a flag in the SharedPreferences that lets your activity know in the onResume() that it needs to be recreated.
public void onResume(){
super.onResume();
SharedPreferences pref = getApplicationContext().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);
if(pref.getBoolean("isDirtyPrefs", true))
recreate();
}
I had a similar problem. Failing to find a simple way to make my PreferenceActivity refresh itself, my solution was to add this to my PreferenceActivity:
/**
* Called when activity leaves the foreground
*/
protected void onStop() {
super.onStop();
finish();
}
This will cause the Prefs screen to reload from SharedPreferences next time it is started. Needless to say, this approach won't work if you want to be able to go back to your preferences screen by using the back button.

How to retain the previous data even if we exit the Android app?

I have an Android tab application. Suppose at the third tab, I exit the app. When I starts the app again, it gets restated and shows the first tab. My requirement is when aplication starts it should go to the previously selected tab. How to do this?
You'll have to override the Method "onSavedInstanceState"
Please see this question:
Saving Android Activity state using Save Instance State
it is described there in detail.
Edit: as stated in the comments this only works with the normal way you would close your app on your phone and it is not neither persistent after reboot of the phone nor after killing your apps process.
If this all you wanted then override the back button of your activity and save the value of current displaying tab using in SharedPeferences
int currentTab = mHost.getCurrentTab();
and in OnCreate after you inflate your layout get the values stored above and set that value as current tab using
TabHost mHost = new TabHost(this);
mHost.setCurrentTab(currentTab );
For that you need to save some tag in shared preference and when the application starts again you have to read it from shared preference and call that particular tab according to that tag saved in preference.
for this u can use SharedPeferences like this.
SharedPreference s readHistory = context.getSharedPreferences(className.PREFS_NAME,0);
return readHistory.getString("from", "");
set pres from all your activity.
and check when u again start your app like this.
if(frmAct.equalsIgnoreCase("activity1"))
{
\\ call here your activity
}
else if(frmAct.equalsIgnoreCase("activity2"))
{
\\ call here your activity
}
You can save the data for using in future:
1) you can save the simple data in sharedpreferences.
2) you can also save the data in database
To save the last data you have to save the data in activity's onStop() method. Because before exiting from the application the onStop() method is called of the current activity.
This link Data Storage in Android will help you a lot.

After changing a preference (a setting), text showing settings doesn't update

I will try to explain a simple app scenario: My app goes right to a 'main view'. In this main view I have inserted a TextView which displays current settings created by way of the PreferenceManager. For simplicity sake, let's say I have a checkbox in my settings. When I first start my app - the TextView on my main view shows my checkbox setting correctly (true). Now I go to the settings menu, it pops-up, and then I change it to false. I go back to the main view and see no change. It still say's true even after I changed it to false. If I end the app and then re-start it - all is well and it shows my change.
Apparently the main view just stays in the background while I'm changing settings? How can I redraw or update the main view after I change settings?
You could implement OnSharedPreferenceChangeListener in your main Activity:
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (PREFKEY_OF_INTEREST.equals(key))
updateSomethingInMainView();
}
and in onCreate() call:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
When you go into your preferences your current activity should be paused and the resumed when you go back (see the lifecycle diagram on lifecycle diagram on the android site). You should be able to trigger some kind of redraw from within onResume() I would think. That will allow the data on the page to repopulate. Some sort of invalidate() call would do it I guess.

Categories

Resources