android correct lifecycle to update between two activities - android

I have this in a fragment to set visible or invisible a textview:
startText = (TextView) view.findViewById(R.id.starting_text);
/** GET SHARED PREF VALUE */
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("prefN_b", Context.MODE_PRIVATE);
nnS = sharedPreferences.getInt("numB", DEFAULT);
Log.d("THIS", Integer.toString(nnS));
if (nnS > 0){
startText.setVisibility(View.INVISIBLE);
}else{
startText.setVisibility(View.VISIBLE);
}
and in another activity i update shared pref with this:
/** GET SHARED PREF VALUE */
SharedPreferences sharedPreferences = getSharedPreferences("prefN_b", Context.MODE_PRIVATE);
nnS = sharedPreferences.getInt("numB", DEFAULT);
/** GET TITLE FROM DATABASE */
DatabaseConnector dbConnector = new DatabaseConnector(this);
dbConnector.open();
Cursor c = dbConnector.ListAllNotes();
itemNN = c.getCount();
/** SAVE/UPDATE SHARED PREF VALUE */
SharedPreferences.Editor editorr = sharedPreferences.edit();
editorr.putInt("numB", itemNN);
editorr.commit();
right now are both placed under onCreate of respective activities, so this only update upon app restart, i'd like it to work upon moving from activity to activity, where should i place the codes? i tried onPause and onRestart combination but didn't work.. thanks
SOLVED:
AS #Mobile Developer suggests below I placed both codes in respectives onResume(). In the fragment onResume() I had to modify the textview fetch to: startText = (TextView) this.getActivity().findViewById(R.id.starting_text);

You could add a preference listener (registerOnSharedPreferenceChangeListener) in your first activity that updates the TextView's visibility when the preference changes.
Additionally as Mobile Developer mentioned, you could check the preference in the first activity's onResume() and update your TextView there.

Why don't use startActivityForResult(#Intent intent, #int requestCode) instead of startActivity(#Intent)
And data from second activity will receive in onActivityResult(in first activity)

Related

Shared Preference data not cleared when activity is closed

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();`

Difficulty with SharedPreference data storage and losing values on exit

I am having trouble storing primitive data in an instance of SharedPreferences. Everything works as I thought it would, but when I close or exit my app and reopen it, the values in the SharedPreference go back to the default states.
I think it may have to do with either where or how I set the default values. Here is the snippet I am referring to that resides in the onCreate() of my main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null){
userDetails = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.putInt("list_code", 0); //stores the number corresponding to a word list
edit.putInt("highscore", 0); //stores the starting score
edit.commit();
}
Thougts?
The Bundle != null when your activity "restarts". For instance when screen was rotated or system killed background activity and recreated it. Otherwise it equals null. So to save some data between different instances of activity you need to check whether you save data before or not.
Sample:
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
int highScore = preferences.getInt("highscore", -1);
if (highScore == -1) {
//preferences was never used, so put default value
highScore = 0;
preferences.edit().putInt("highscore", highScore).commit();
}

Android: Shared Preference value doesn't change even after committing

In an Activity_A, i have:
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreference settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
in Activity_B i have:
//changing the previously added **city** value
SharedPreferences settings = getSharedPreferences(Activity_A.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("city", myCity);
editor.commit();
in Activity_C i have:
SharedPreferences settings = getSharedPreferences(Activity_A.PREFS_NAME, 0);
String city = settings.getString("city", "default");
//here i am getting the previous value of **city**, not the updated 1 from Activity_B
But once i restart the application then it gives the correct value.
What am i doing wrong?
Thank You
In Activity C where you want to show the value, when do you get the value from the SharedPreferences?
You should get the SharedPreferences values in the onResume method i think because if you do this in the onCreate method no changes will be there if you co back to Activity C.
This is because the onCreate method will only be called once the Activity is first created. When you navigate back (away) from Activity C it goes on the backstack and is later restored using the onRestart or onResume. This means that the onCreate method is not called again.
So i suggest that you do the getting from the SharedPreferences in the onResume method.
Activity lifecylce: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
I'm right?
Rolf

Create method that returns value gotten at applucation start

I'm developing an application where I want to find out what volume the user had when he started my app from a method thats not onCreate(). I have created an int based on the current volume inside my onCreate but since it can't return anything I don't know how to get my int from there. It's very important that I use the int I generated at in onCreate().
How can this be done?
#pawegio right, if you want to use same vol level what user set up, use preferences.
This is how to:
WRITE into preferences
SharedPreferences pref =
context.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
/*
* Get the editor for this object. The editor interface abstracts the implementation of
* updating the SharedPreferences object.
*/
SharedPreferences.Editor editor = pref.edit();
/*
* Write the keys and values to the Editor
*/
editor.putInt("VolumLevel", 60);
/*
* Commit the changes. Return the result of the commit.
*/
e.commit();
READ from preferences
SharedPreferences pref = context.getSharedPreferences("MyAppPreferences", MODE_PRIVATE);
int volLevel = pref.getInt("VolumLevel", 50 /*Default if value wasn't setup yet*/);
return volLevel;
If I well understood you, you should use: SharedPreferences to save that value.

How to update internal values of a PreferenceActivity when SharedPreferences change

I use a Preference in a PreferenceActivity to load default values: when this specific Preference is clicked, something like this happens:
private String mResetKeys = "key1,key2,key3";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor prefs_editor = prefs.edit();
for (String current_pref : mResetKeys.split(",")) {
prefs_editor.remove(current_pref);
}
prefs_editor.commit();
But afterwards, the Preferences whose corresponding SharedPreference was reset still show the old value - it seems to be cached in the Preference. Only when I leave the PreferenceActivity and reopen it, the Preferences show the new values.
How can I update the PreferenceActivity programmatically?
I had a similar problem. This probably isn't the most correct fix but it worked for my purposes. Right after I did the commits, I called the Activity.recreate(); method.
The activity will restart (onDestroy()/onCreate()/etc) but for my purposes all I needed was a special handling on one preference. I listened for a certain preference with an OnPreferenceClickListener and made an alert dialog box with a kind of warning message and an option to change their mind. If they did want to change their mind, I did my commit of the new value to the preference activity and then called recreate() so that the checkbox preference would be updated.
However, I am also interested in a way to do this without recreating the activity...
Update preference value without reloading PreferenceActivity
from http://liquidlabs.ca/2011/08/25/update-preference-value-without-reloading-preferenceactivity/
Here is how to update default shared preference value of target element (in this case EditTextPreference)
public class YourCustomPreference extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
// some logic goes above, when you want to reset value and update EditTextPreference value
// For convenience, I am going to wrap two different task in different methods
private void resetPreferenceValue() {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefEditor = sharedPref.edit(); // Get preference in editor mode
prefEditor.putString("your_edit_text_pref_key", "DEFAULT-VALUE"); // set your default value here (could be empty as well)
prefEditor.commit(); // finally save changes
// Now we have updated shared preference value, but in activity it still hold the old value
this.resetElementValue();
}
private void resetElementValue() {
// First get reference to edit-text view elements
EditTextPreference myPrefText = (EditTextPreference) super.findPreference("your_edit_text_pref_key");
// Now, manually update it's value to default/empty
myPrefText.setText("DEFAULT-VALUE"); // Now, if you click on the item, you'll see the value you've just set here
}
}

Categories

Resources