in my application, I used place picker.and data that place picker gave is sent to 3 different activities using shared preference.and show this data in TextView.problem is when I closed activity and again open that activity my data still visible in TextView.even when I cleared it in onDestroy().
here is my code for send data from place picker:
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("city_address", (String) cityAddress);
editor.putString("city_name", (String) city);
editor.commit();
Intent intent = new Intent(this, CleanlinessActivity.class);
startActivity(intent);
set data using this code in onCreate() of CleanlinessActivity
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
String n = settings.getString("city_name", "Enter Location");
String a = settings.getString("city_address", "");
cityname.setText(n);
cetlocation.setText(a);
and i cleared data using this code in CleanlinessActivity
#Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("city_address");
editor.clear().commit();
}
By closing the app you mean just clicking the home button then onDestroy() is never called, you can get a refresher of the android life cycles here
If what you are doing is simply clicking the home button then consider moving your code to the onStop() otherwise you need to commit() following the remove(...) The android documentation states "Mark in the editor that a preference value should be removed, which will be done in the actual preferences once commit() is called."
You have an instance of SharedPreferences called city_address which is having two fields or (Columns if we call it),but inside onDestroy()you are trying to to clear only one field of it called city_address,and the other field city_name field is left unchanged,if you want to completely remove the content of the city_address SharedPreferences use editor.clear().commit();
or``editor.clear().apply();`
Related
I have two buttons on a fragment, "start" and "finish". when "start" is pressed, it gets hidden and "end" is shown. when "end" is pressed "start" is shown. i want to retain the state when app is closed and run again
I would recommend using SharedPreferences to achieve this. They are meant to be to retain app state when run at a later time.
In your case, you need to use putBoolean() method from SharedPreferences.Editor something like this:
"Start" button onClickListener:
SharedPreferences sharedPref = context.getSharedPreferences(context, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.editor();
editor.putBoolean("isJobRunning","true");
editor.commit();
In the same way, you set the isJobRunning to false once "End" button is called.
I would also move this code to a dedicated method something like this:
private void updateJobStatus(boolean isJobRunning) {
SharedPreferences sharedPref = context.getSharedPreferences(context, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.editor();
editor.putBoolean("isJobRunning", isJobRunning); // difference is visible here!
editor.commit();
}
On the onCreateView() method on the Activity, you can check if the job is running this way:
SharedPreferences sharedPref = context.getSharedPreferences(context, MODE_PRIVATE);
sharedPref.getBoolean("isJobRunning", false); // Here, `false` is the default value if the key is not located in `SharedPref`
I have an activity A, it has a button to open B, which inserts a record. A can then refresh the view inside onActivityResult. This is a normal flow.
However, B can accept share intent to insert a record also. How can A know when this action is done from B to refresh the view just like the normal flow? (of course, I assume act A already running on background task)
I can, of course, detect the change using onResume inside A, but i wish to know if it is a proper method.
thank you
You can use onResume to refresh the view for activity A. Because other method would be using broadcastReceiver and broadcastIntent and that would create unnecessary load.
You can use sharedPreference to store if data has been changed in Activity B and then in onResume of Activity A fetch that shared Preference and refresh the view
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChanged = sharedPreferences.getBoolean("isChanged",false);
if(isChanged){
//refresh your views
//clear the shared prefernce
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("isChanged",false);
editor.apply();
}
}
Remember you have set that shared preference in ActivityB while loading data
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("isChanged",true);
editor.apply();
This question already has answers here:
TextView that gets Value from SharedPreferences shows nothing, though there should be default values
(4 answers)
Closed 6 years ago.
I am having an issue with SharedPreferences that is kind of weird.
I have an Activity that holds a Fragment in a ViewPager. The fragment shows an icon and text. You can change the icon (check mark or cross, check mark is default) and text displayed in this fragment from another activity.
Now I want to save the text and chosen icon, so the fragment is shown with the same text and icon, even when you close the app and restart it later.
So I tried to achieve this with SharedPreferences, but when I tried it, my fragment showed me no text though I have default values set and the icon is always the cross, no matter what it was before and though the default icon should be the check mark.
I am saving the values in onActivityCreated() of my Fragment when it is created with the data the user inputted in the activity before.
Saving:
SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//Here I am getting the values I want to save from a bundle, city and country...
editor.putString("savedCity", city);
editor.putString("savedCountry", country);
editor.putString("fragmentSaved", "yes");
editor.apply();
Then, I am getting the values in onCreate() of my Activity that holds the Fragment:
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//adding fragment that was created with user input
String ifAdded = sharedPref.getString("addedFragment", "no");
if(ifAdded.equalsIgnoreCase("yes")){
Bundle extras = getIntent().getExtras();
StatusFragment newFragment = new StatusFragment();
newFragment.setArguments(extras);
mSectionsPagerAdapter.addFragment(newFragment, extras.getString("city"));
editor.putString("addedFragment", "no");
editor.apply();
}
//Adding a saved fragment after restart
String storedSave = sharedPref.getString("fragmentSaved", "no");
if (storedSave.equalsIgnoreCase("yes")){
String storedCity = sharedPref.getString("savedCity", "somecity");
String storedCountry = sharedPref.getString("savedCountry", "somecountry");
Bundle saves = new Bundle();
StatusFragment savedFragment = new StatusFragment();
saves.putString("city", storedCity);
saves.putString("country", storedCity);
savedFragment.setArguments(saves);
mSectionsPagerAdapter.addFragment(savedFragment, saves.getString("city"));
}
In the activity where the fragments data is created, I have this:
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("addedFragment", "yes");
editor.apply();
fragmentHolder.putExtras(bundle);
startActivity(fragmentHolder);
bundle has the values the user typed in, and fragmentHolder is the activity that holds the fragment.
I searched for answers in different questions here on stackoverflow, but none of them worked for me, like:
Cannot get value from sharedpreferences
Shared Preferences get lost after shutting down device or killing the app
Shared Preferences reset data when app is force closed or device is restarted
SharedPreferences return only default value
SharedPreferences return only default value
Shared preference always taking default value
SharedPreferences keep getting default value
Sorry if I it is perhaps something trivial, but I haven't worked with Fragments much and I am using SharedPreferences the first time now.
I would be grateful for every helpful answer.
The problem is solved now. I had to use getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE); and some of my variables in the bundles and preferences got mixed up. I corrected this and now it works fine :) Thanks for your answers.
You are mixing up things that are stored in your SharedPreference and inside your applications resources (strings.xml)
editor.putString(getString(R.string.pref_fragment_saved), "Yes");
This line saves the string inside your preference XML, but then you try to read it as
getResources().getString(R.string.pref_fragment_saved).equals("Yes")
Which actually just reads the value R.string.pref_fragment_save from your strings.xml
The correct way of reading what you saved would be
getActivity().getPreferences(Context.MODE_PRIVATE).getString(getResources().getString(R.string.pref_fragment_saved), "defaultValue")
Or a bit cleaner:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
String key_frag_saved = getResources().getString(R.string.pref_fragment_saved);
String storedString = prefs.getString(key_frag_saved, "defValue");
if ( storedString.equalsIgnoreCase("yes") ) {...}
And the same way you would read the other saved values from your SharedPreference object instance.
You wanted to use this
SharedPreferences sharedPref = ...;
extras.putString("city", sharedPref.getString(getResources().getString(R.string.pref_saved_city), ""));
in your onCreate method
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);
How to display different content depending on whether the app is opened first time or the user setup something?
Imagine a activity A, B, If the user open the app first time or haven't setup something in activity B, Then display activity B, otherwise display activity A.
How to overcome this? Thank you.
Use PreferenceManager. In activity A add check for the preference firstLaunch. If it's not set, launch activity B. Then, in activity B, set it.
It could look like:
Activity A
#Override
protected void onResume() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// By default assume "true", which means this is the first launch.
if (prefs.getBoolean("firstLaunch", true)) {
// Start Activity B and finish myself.
Intent i = new Intent(getApplicationContext(), ActivityB.class);
startActivity(i);
finish();
}
}
Activity B
// Do it after you've initialized everything, so Activity A can be launched:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this)
SharedPreferences.Editor editor = prefs.edit();
// Set "fistLaunch" to "false", so Activity A will start next time.
editor.putBoolean("firstLaunch", false);
editor.commit();
If you want to show different activity if user opened the app first time and different activity second or third time and so on then you can use below approach.
You can use the SharedPreference to achieve this.
Check the condition like this in the Splash Activity :
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
if(!preferences.getBoolean("isFirstRun", false)) {
// This mean App Launch First Time
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
edit.putBoolean("isFirstRun", true);
edit.commit();
// Open the B Activity
} else {
// This mean App Launch Second or third ... time and start the A Activity
}