Instance state to keep button visibility - android

How do I keep button Visibility when returning from another activity?
My Code:
#Override
protected void onStop() {
super.onStop();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
SharedPreferences.Editor edit = btVis.edit();
edit.putString("btS1",btSub1.getVisibility()+"");
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
int btS1 = Integer.parseInt("View." +btVis.getString("btS1",""));
btSub1.setVisibility(btS1);
}
I get an error cause setVisibility needs to be in format View.(VISIBILITY) for example. But I parsed btS1 as an int in the format View.(VISIBILITY) so I dont know why it doesn't work. How do I fix this?

You forgot to call editor.commit(); which means your int was never actually saved.
#Override
protected void onStop() {
super.onStop();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
SharedPreferences.Editor edit = btVis.edit();
edit.putString("btS1",btSub1.getVisibility()+"");
editor.commit();
}
Edit:
I see you also did something wrong
int btS1 = Integer.parseInt("View." +btVis.getString("btS1",""));
While you do get the id via the class View, you don't need to get it from your shared prefs that way. You already just stored the Integer that is referred to in View.GONE and View.Visisble.
To make this work you just need:
int btS1 = Integer.parseInt(btVis.getString("btS1",""));
But I don't see why you would parse it to a String and then parse it back to an int. Also I would do the saving on OnPause instead of OnStop. So completely reworked you should do this:
#Override
protected void onPause() {
super.onPause();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS, 0);
SharedPreferences.Editor edit = btVis.edit();
edit.putInt("btS1", btSub1.getVisibility());
edit.commit();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS, 0);
int btS1 = btVis.getInt("btS1", 0);
btSub1.setVisibility(btS1);
}

try this one in onResume() method.
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
int visibility = Integer.parseInt(btVis.getString("btS1",""));
switch(visibility){
case View.VISIBLE: //make button visible
break;
case View.INVISIBLE: //make button invisible
break;
}
}
Make sure to commit editor at the end of onStop() method

Related

Change in shared preference not firing

I have a Floating Action Button in my layout. Users can choose the position of this button, left or right. This can be selected in the preferences.
The code to do this works OK, but a change in the preference is not detected by the listener.
If the app is restarted, the Floating Action Button is displayed according to the new preference, so I know the process with this preference works, but unfortunately the listener seems to fail.
What do I have to do to get the listener firing when the preference has changed?
Listener in my MainActivity:
private final SharedPreferences.OnSharedPreferenceChangeListener
mPositionFabListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.e(TAG,"Are we getting here?");
// We do not get here when preference has changed. Why not??
// Code to update Floating Action Button to new position
}
};
I register the listener in the onResume() method of the MainActivity and unregister in the onPause().
#Override
protected void onResume() {
super.onResume();
PrefUtils.registerOnPrefChangeListener(mPositionFabListener);
}
#Override
protected void onPause() {
PrefUtils.unregisterOnPrefChangeListener(mPositionFabListener);
super.onPause();
}
The registerOnPrefChangeListener method is declared in a seperate class:
public class PrefUtils {
public static boolean getBoolean(String key, boolean defValue) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext());
return settings.getBoolean(key, defValue);
}
public static void putBoolean(String key, boolean value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit();
editor.putBoolean(key, value);
editor.apply();
}
public static int getInt(String key, int defValue) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext());
return settings.getInt(key, defValue);
}
public static void putInt(String key, int value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit();
editor.putInt(key, value);
editor.apply();
}
public static void registerOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
try {
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).registerOnSharedPreferenceChangeListener(listener);
} catch (Exception ignored) {}
}
public static void unregisterOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
try {
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).unregisterOnSharedPreferenceChangeListener(listener);
} catch (Exception ignored) {}
}
}
UPDATE:
In the GeneralPrefsFragment class I put in this listener for testing purposes. This listener is working. So why does it not work in the MainActivity?
public class GeneralPrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Preference preference = findPreference(PrefUtils.POSITION_FLOATING_MENU_BUTTON);
Preference.OnPreferenceChangeListener mListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
PrefUtils.putBoolean(PrefUtils.POSITION_FLOATING_MENU_BUTTON, Boolean.TRUE.equals(newValue));
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit().commit(); // to be sure all prefs are written
Log.e(TAG, "The listener in " + TAG + " is listening");
// This listener is fired as soon as changes in the preference are made!
// Why is the same kind of listener not fired in the MainActivity?
return true;
}
};
preference.setOnPreferenceChangeListener(mListener);
}
}
SOLUTION:
I got a fix. I still do not know why the former setup didn't work, but I got it working, thanks to the code in this answer.
In the MainAcivity's onCreate() method I placed the following listener and this one gets triggered when the preferences have changed.
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener mPrefsFabListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (PrefUtils.POSITION_FLOATING_MENU_BUTTON.equals(key)) {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams paramsFab = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
if (PrefUtils.getBoolean(PrefUtils.POSITION_FLOATING_MENU_BUTTON, false)) {
paramsFab.gravity = Gravity.BOTTOM | Gravity.START;
} else {
paramsFab.gravity = Gravity.BOTTOM | Gravity.END;
}
}
}
};
prefs.registerOnSharedPreferenceChangeListener(mPrefsFabListener);
The OnSharedPreferenceChangeListener gets unregistered in the onPause() method of the MainAcitivity. That is a problem, because the MainActivity gets paused as soon as the General Preferences Activity is started in order to change the preferences. So, the listener is unregistered and therefore not listening right at the point where it is needed!
I removed the unregisterOnPrefChangeListener from the onPause() and put in the following code. This worked perfectly!
#Override
protected void onDestroy() {
PrefUtils.unregisterOnPrefChangeListener(mPositionFabListener);
super.onDestroy();
}

Listening for Preference change

I am implementing Preferences according to Google tutorial. But I do not receive changes in my event listener. I realized that it is because I unregister the listener in onResume, like Google recommended. Did I miss something or is google advice wrong?
For proper lifecycle management in the activity, we recommend that you
register and unregister your
SharedPreferences.OnSharedPreferenceChangeListener during the
onResume() and onPause() callbacks, respectively:
public class MyActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener,
SharedPreferences.OnSharedPreferenceChangeListener {
public boolean onOptionsItemSelected(MenuItem item) {
case R.id.action_level: {
Intent intent = new Intent();
intent.setClass(this, GamePreferenceActivity.class);
startActivity(intent);
return true;
...
protected void onPause() {
Log.d(logTag, "onPause()");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
protected void onResume() {
Log.d(logTag, "onResume()");
super.onResume();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(MyPreferenceActivity.KEY_COMPLEXITY)) {
String value = sharedPreferences.getString(key, "EASY");
logic.setLevel(Level.valueOf(value));
restartGame(null);
}
}
My activity starts an intent with preferences activity.
public class GamePreferenceActivity extends Activity {
public static final String KEY_COMPLEXITY = "prefGameComplexity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new GamePreferenceFragment())
.commit();
PreferenceManager.setDefaultValues(this, R.xml.game_prefs, false);
}
}
public class GamePreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.game_prefs);
}
}
You need to call commit() or apply() to save changes in preferences.
Example:
// Access the default SharedPreferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// The SharedPreferences editor - must use commit() to submit changes
SharedPreferences.Editor editor = preferences.edit();
// Edit the saved preferences
editor.putString("UserName", "JaneDoe");
editor.putInt("UserAge", 22);
editor.commit(); //or editor.apply() -- Read below for difference between these two
Difference between commit() and apply():
apply() was added in 2.3, it commits without returning a boolean indicating success or failure.
commit() returns true if the save works, false otherwise.
apply() was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.
This is the way how I register and unregister listener:
#Override
public void onResume() {
super.onResume();
// Register the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
Show us your onSharedPreferenceChanged, maybe you made mistake there.

SharedPreferences troublesome nullpointerexception

(REMOVED THE OLD CONTENT OF THE POST)
EDIT #2: Okay, so now I am crystal clear that it is the editor trying to reach the preference that causes the nullpointerexception. Any help here on how to fix it?
Here is the updated activity:
public SharedPreferences sharedPreferences;
Editor editor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requesting to turn the title OFF
requestWindowFeature(Window.FEATURE_NO_TITLE);
// making it full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// set our MainGamePanel as the View
setContentView(new MainGamePanel(this));
// Restore preferences
this.sharedPreferences = getPreferences(MODE_PRIVATE);
this.editor = sharedPreferences.edit();
try {
int wins = GetPreferences("wins");
int fails = GetPreferences("fails");
gamePanel.winn = wins;
gamePanel.failn = fails;
} catch (NullPointerException npe) {
Log.d(TAG, "Nothing to load");
}
//INIT SOUND
mSoundManager.initSounds(getBaseContext());
//SOUNDS
mSoundManager.addSound(1, R.raw.draw);
mSoundManager.addSound(2, R.raw.cheer);
mSoundManager.addSound(3, R.raw.boo);
}
#SuppressWarnings("deprecation")
#Override
public void onBackPressed()
{
super.onBackPressed();
if (gamePanel.gamei==true) {
gamePanel.back();
} else if (gamePanel.menui==true) {
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
}
public void onPause()
{
super.onPause();
//KILL ALL
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
#Override
protected void onStop(){
super.onStop();
//KILL ALL
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
public int GetPreferences(String key) {
return sharedPreferences.getInt(key, 0);
}
public void SavePreferences(String key, int value) {
editor.putInt(key, value);
editor.apply();
}
public void writeWin () {
SavePreferences("wins", gamePanel.winn);
}
public void writeFail () {
SavePreferences("fails", gamePanel.failn);
}
The editor is what is causing the nullpointerexception: this.editor = sharedPreferences.edit();. EDIT: It's the sharedPreferences that is causing the nullpointerexception, not the editor.
It seems like the editor cannot reach the Preference: this.sharedPreferences = getPreferences(MODE_PRIVATE);.
Any idea on how to fix this?
It look like the declaration
Editor editor;
should be
SharedPreferences.Editor editor;
I finally got it fixed by using a listener! It apparantely was the gamePanel that was null inside of the activity. Go here for more information:
nullpointerexception when trying to reach activity

Why is my value saved to SharedPreferences in onPause() not restored in onResume()?

I have the following code:
SharedPreferences KITPrefs;
EditText passPhraseExample;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
passPhraseExample = (EditText) findViewById(R.id.editTextPassPhraseExample);
KITPrefs = getPreferences(Activity.MODE_PRIVATE);
#Override
public void onResume() {
super.onResume();
passPhraseExample.setText(KITPrefs.getString("passPhraseExample", ""));
}
#Override
public void onPause() {
super.onPause();
SharedPreferences.Editor editor = KITPrefs.edit();
editor.putString("passPhraseExample", passPhraseExample.getText()
.toString());
}
..yet when I enter a value in "passPhraseExample," move to the next Activity, and then go back (in the Emulator), the passPhraseExample EditText is empty. Shouldn't it have the value I entered into it, saved, and then "restored"?
You don't commit your changes.
Call editor.commit() after writing the string in onPause(). Otherwise your changes are not saved.

SharedPreference problem in android

public class WordDisplay extends Activity {
private int level;
private int group;
private int set;
private WordDisplay mContext=this;
private int l;
private int g;
private int s;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wordset);
set_Word_Display_Event();
loadPreferences();
}
protected void loadPreferences() {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
l= preferences.getInt("Level", 0);
g=preferences.getInt("Group", 0);
s= preferences.getInt("Set", 0);
// Log.d("lll"," - "+preferences.getInt("level",0));
}
#Override
protected void onStop() {
super.onStop();
savePreferences(this.level,this.group,this.set);
}
protected void savePreferences(int level, int group, int set) {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
//preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("Level", l);
editor.putInt("Group", g);
editor.putInt("Set", s);
editor.commit();
//return getPreferences(s).getInt("Set", 0);
}
}
Here, my data could not persist properly. what is the wrong my code. please give good convenience.
Comments of the above code, Also checking but could not any effect.
First, onStop() "might" never be called (see Activity life cycle), practice is to save your data in the onPause() method.
Maybe try to add more logs to see what's going on?
is onStop() called?
what are the saved / loaded values?
etc.
Try it with a final string constant in your class:
public static final String PREFS_NAME = "MyPreferences";
and then always use the member function:
getSharedPreferences(PREFS_NAME, 0);
normally there is no magic to do.
http://developer.android.com/guide/topics/data/data-storage.html#pref

Categories

Resources