Last active
September 14, 2018 20:55
-
-
Save OrenBochman/47cb11ec3a304e1ea15c27e47bb44b2b to your computer and use it in GitHub Desktop.
android sharepreferencess
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
protected void onPause() { | |
super.onPause(); | |
SharedPreferences.Editor preferencesEditor = mPreferences.edit(); | |
preferencesEditor.clear(); | |
preferencesEditor.putInt("count", mCount); | |
preferencesEditor.putInt("color", mCurrentColor); | |
preferencesEditor.apply(); | |
} | |
@Override | |
protected void onCreate(Bundle savedState) { | |
//... | |
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE); | |
if (savedInstanceState != null) { | |
mCount = mPreferences.getInt("count", 1); | |
mShowCount.setText(String.format("%s", mCount)); | |
mCurrentColor = mPreferences.getInt("color", mCurrentColor); | |
mShowCount.setBackgroundColor(mCurrentColor); | |
mNewText = mPreferences.getString("text", ""); | |
} else { | |
// … | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//interface and callback | |
public class SettingsActivity extends AppCompatActivity | |
implements OnSharedPreferenceChangeListener { ... | |
public void onSharedPreferenceChanged( | |
SharedPreferences sharedPreferences, String key) { | |
if (key.equals(MY_KEY)) { | |
// Do something | |
} | |
} | |
} | |
//Creating and registering listener | |
SharedPreferences.OnSharedPreferenceChangeListener listener = | |
new SharedPreferences.OnSharedPreferenceChangeListener() { | |
public void onSharedPreferenceChanged( | |
SharedPreferences prefs, String key) { | |
// Implement listener here | |
} | |
}; | |
prefs.registerOnSharedPreferenceChangeListener(listener); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment