I have an if loop when a chebkox in sharedpreferences changed status. But I'm not able to set putBoolean("blabla", false); when the status changed.
For example: User hits checkbox, CB gets checked, if says uncheck it but it won't uncheck.
My Code:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("cbSaveUsername")) {
SharedPreferences.Editor SFEdit2 = sharedPreferences.edit();
SFEdit2.putBoolean("cbSaveUsername", false);
SFEdit2.commit();
}
}
Can anyone tell me my mistake?
Edit: It looks like it works programatically but the tick is still in the box :o Where could be the mistake? I use it like Gunaseelan postet
Try to use onPause() and onResume() methods.
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
For more details onSharedPreferenceChanged not fired if change occurs in separate activity?
Related
I have an app where I take the Name of the user in an editText and I have it storing to firebase but when I get out of the activity and go back into it, the editText field does not show the Name of the user anymore. I want their name to stay in the editText field.
also how would I do the same thing but for an image in an ImageView that the user puts in. Please help.
IDEA:
You can use shared preference. When user launches his application first task will be load his user name and password from shared preference.
By doing this you can also manage a session manager for better user experience.
For example: After every successful authentication you can store the basic information of the user that is needed to update the screen everytime.
Benefit:
This will help you to show old data on screen if user launches your app without internet enabled. You can check the internet and if disabled then simply show the old data from preference.
You Can do something like this
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
text.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
prefs.edit().putString("autoSave", s.toString()).commit();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
//At here you can call some method to get the text from shared preferences and display it on EDitText
}
or You can save into DB at onTextChanged() method
Here is a little activity example which saves the username into SharedPreferences at stop of activity and restores the value to the EditText when activity is (re)started:
public class Test extends Activity {
EditText edtUser;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
edtUser = (EditText) findViewById(R.id.editTextUser);
edtUser.setText(preferences.getString("username", ""));
}
#Override
protected void onStop() {
super.onStop();
preferences.edit().putString("username", edtUser.getText().toString()).commit();
}
}
Set on click listener to edit text.
Inside on click enable edit text and write to firebase using setValue.
Set on click to parent layout or check is focus changed of edit text. Inside read from firebase using add value event listener.
In Oncreate disable edit text and read from firebase using add value event listener.
This will auto save and retrieve edit text data seamlessly.
In OnCreate create method of activity
//Initialize edittext
mEditText = (EditText) findViewById(R.id.edittext);
// Disable mEditText
mEditText.setEnabled(false);
//Read from firebase and set text to mEditText if mTextEdit is not in focus
if (!mEditText.isFocused()){
mFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String editTextData = (String) dataSnapshot.getValue();
mEditText.setText(editTextData);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
// Set onclick listener to mEditText
mEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mEditText.setEnabled(true);
editTextData = mEditText.getText().toString();
mFirebaseRef.setValue(editTextData);
}
});
This works for me and UI looks simple without any extra buttons to switch between edit and save.
Hope I understood your requirement correctly. Thanks
I have a situation with onResume() method and I don't know how to solve it.
conssider the following code:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
Log.d("tag", "onCreate");
}
#Override
protected void onResume() {
super.onResume();
//do something only when everytime the activity comes to screen
Log.d("tag", "onResume");
}
private void myMethod() {
this.onResume();
}
}
If we asume that myMethod will definitly be called, I don't want to let onResume() to execute //do something only when everytime the activity comes to screen. I should note that myMethod is a fixed method and cannot be changed.
PS:The reason that I am asking this question is that I have a simillar situation with PermissionDispatcher library with android 6 and I want to call a "risky permission" in the onReume() method but if the user denies the permission, it will call the onReume() again, and since the permission required task is in the onResume(), the permission will be denied again and cauases an inifite loop
could anyone give me a suggestion?
UPDATE: here is the permissionDispatcher library and the issue that is related to my problem
verify this method Already Executed or not simply in if Condition
Bool a=true;
#Override
protected void onResume() {
super.onResume();
//do something only when everytime the activity comes to screen
if(a==true)
{
//your Actions
}
else if(a==false)
{
//do nothing
}
}
Use SharedPreferences in onResume
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean firstStart = settings.getBoolean("firstStart", true);
if(firstStart) {
//do something only when everytime the activity comes to screen
Log.d("tag", "onResume");
//display your Message here
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstStart", false);
editor.commit();
}
}
I have in my app preference activity with EditTextPreference and I added this, to detect, when the text in edittext is changed. All works, except for that, the code runs always twice... I tryed to add System.out.println("now"); to proove if the code runs twice, and it writes "now" two times...
Here is the code:
SharedPreferences.OnSharedPreferenceChangeListener myPrefListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.admin_activity);
myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
switch(key) {
case "prefAddUser":
EditTextPreference connectionPref = (EditTextPreference) findPreference(key);
String jmeno = connectionPref.getText();
System.out.println("now");
add_user(jmeno); //custom method to add user to MySQL database
Toast.makeText(getApplicationContext(), "add user", Toast.LENGTH_SHORT).show();
connectionPref.setText("");
break;
}
}
};
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(myPrefListner);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(myPrefListner);
}
I don't know what to do with this weird problem...
What should I do?
Calling OnSharedPreferenceChangeListener in anonymous class makes it become the target of garbage collection.
As soon as you leave the current scope and can cause unregisterOnSharedPreferenceChangeListener() to be call on a null context.
Implement it in the class scope like this:
public class SettingsActivity extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
...
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
Read the next tutorials for further explanation:
1. Good So answer on the subject
2. Official documentation here
I want to save some values with SharedPreferences in my app. These values constantly change when it is active (for example every game brings some coins, and I want to save these coins). However I don't know when the user will quit the app in order to save the coins then for next time. So in every activity where the coins change I have:
#Override
protected void onStop() {
super.onStop();
SharedPreferences sp = getSharedPreferences("my_pref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("coins", MainActivity.COINS);
editor.commit();
}
Is there a way to do this better.
use isFinishing() in onPause() method that means that the application paused and if isFinishing() is true then your app will end
#Override
protected void onPause() {
super.onPause();
if(isFinishing())
{
//finishing logic here
}
}
I wanna display a dialog when the user selects a specific item from a ListPreference in my preferenceActivity. But, I cannot get the onSharedPreferenceChanged() to work. I've put a Toast in the beginning of the method, and it does not show, so the method doesn't even run through, why is this?
Here's my code: (Thanks)
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Toast.makeText(Preferences.this, "prefs Changed", Toast.LENGTH_SHORT)
.show();
if (key.equals("boolean_ad_type")) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String value = sharedPreferences.getString("boolean_ad_type", "");
if (value != null && value.equals("Pop-up Ads")) {
Toast.makeText(Preferences.this, "Pop-up Ads Selected",
Toast.LENGTH_SHORT).show();
}
}
}
And do I need to implement it in the activity like this? (I've tried with and without, no difference)
public class Preferences extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
onSharedPreferenceChanged not fired if change occurs in separate activity?
public class MyActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
you have to set a click listener for that specific preference you want to show the dialog in your onCreate
PreferenceScreen ps2 = (PreferenceScreen) findPreference("ic_vol");
ps2.setOnPreferenceClickListener(this);