Difficulty with SharedPreference data storage and losing values on exit - android

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

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

android correct lifecycle to update between two activities

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)

Android maintain activity state with data

I have 2 different activities. MainActivity, ContactList & ContactDetails. Now from MainActivity user will tap on Add new and application will open ContactList screen from where user can select any contact to see details which opens ContactDetails activity. Now if user select any no. from ContactDetails, application will go back to MainActivity and add the selected no. in arraylist. I am able to add the data but my problem is that whenever add new record old records are erased. I found the reason that evertime i open MainActivity from ContactDetails it creates new Activity. So i am looking for a way to use OnResume or OnResult Method to solve the problem.
In ContactDetails
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("CONTACT_NO", CONTACT_NO); startActivity(intent)
In MainActivity OnResume method
String data = getIntent().getExtras().getString("keyName");
arr.add(data);
If you are looking to persist data during the lifetime of your Activity, SharefPreferences will serve you well. An example:
Write (onPause/onDestroy):
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read (onResume/onCreate):
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Read more here.
Update
Alternatively, you can use onSavedInstanceState. Example:
Save state:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Restore state:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
More information about managing Activity states here.
From where ever you are getting the list in MainActivity.java, take it as public static ArrayList or String array and do not initialize it in MainActivity.java.
Also if you have not called finish() for MainActivity (while going to ContactListActivity.java), then add the new data to the arraylist in onResume(). But remember to keep a checking - whether you have a new data to add or not because for the first time, there would be no data to add (as per your posted question).

Keep variable value

My application has only one service class (not activity) in which I keep value of one variable that is being dynamically calculated through one method. Then i need to save that value for further comparing.
For example:
class MyClass extends Service{
static int number1;
private void Method(){
int number 2;
/// some calculations for number2 ///
if number2 != number1 { number1 = number2 }
}
I need to compare that variable (number1) to the some other variable (number2) that my application has calculated. This is working well, but when Android OS kills my service, and start that service on some intent (let say after phone reboot) the value of number1 is being lost and I can't use it for comparing.
So how to do it? I thought to write simple TXT file in which one i could keep value of number1 after killing the service,
is there any other way?
the quickest way is to save your variable's value in SharedPreferences and retrieve it for later use.
For example:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
this code is taken from android developer's page which is for Activity but you may adapt it in your service easily by changing it
You have to save the value to a file or a database as Android users usually monitor services and applications and can close the service
so
persist it in database so later when your service is started you can check the saved value.

How to skip an activity? android

i have a default activity that starts first (Activity A), and from there the user can go to another activity (Activity B). In B after some work the user sets a sharedpreference. the next time the app starts i want to check in A if sharedpreference is null to go to B. and i put this if just under
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
and it encapsulates the whole onCreate. when the app starts it skips A and on B i shows the layout and the FC with NullPointerException.
Any one got experience with this?
OR
any one got a better idea on skipping A?
Well Simon you have to use Shared prefrences. save your data in shared prefrences. Then in the activity where you want to use the data in Shared prefres again get instance of same shared prefrence. get the data and use it.
go through this code
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
probably you will get an insight
To answer my own question. i had a location listener in onDestroy an because it was not initialized because of skipping onCreate it returned NullPointer.

Categories

Resources