Added/Fixed: Add support to consider empty String values as null for SharedPreferences

This commit is contained in:
agnostic-apollo
2021-09-04 05:31:01 +05:00
parent 197979fdcc
commit 52c1ee520f
2 changed files with 8 additions and 3 deletions

View File

@@ -245,17 +245,22 @@ public class SharedPreferenceUtils {
* @param sharedPreferences The {@link SharedPreferences} to get the value from. * @param sharedPreferences The {@link SharedPreferences} to get the value from.
* @param key The key for the value. * @param key The key for the value.
* @param def The default value if failed to read a valid value. * @param def The default value if failed to read a valid value.
* @param defIfEmpty If set to {@code true}, then {@code def} will be returned if value is empty.
* @return Returns the {@code String} value stored in {@link SharedPreferences}, otherwise returns * @return Returns the {@code String} value stored in {@link SharedPreferences}, otherwise returns
* default if failed to read a valid value, like in case of an exception. * default if failed to read a valid value, like in case of an exception.
*/ */
public static String getString(SharedPreferences sharedPreferences, String key, String def) { public static String getString(SharedPreferences sharedPreferences, String key, String def, boolean defIfEmpty) {
if (sharedPreferences == null) { if (sharedPreferences == null) {
Logger.logError(LOG_TAG, "Error getting String value for the \"" + key + "\" key from null shared preferences. Returning default value \"" + def + "\"."); Logger.logError(LOG_TAG, "Error getting String value for the \"" + key + "\" key from null shared preferences. Returning default value \"" + def + "\".");
return def; return def;
} }
try { try {
return sharedPreferences.getString(key, def); String value = sharedPreferences.getString(key, def);
if (defIfEmpty && (value == null || value.isEmpty()))
return def;
else
return value;
} }
catch (ClassCastException e) { catch (ClassCastException e) {
Logger.logStackTraceWithMessage(LOG_TAG, "Error getting String value for the \"" + key + "\" key from shared preferences. Returning default value \"" + def + "\".", e); Logger.logStackTraceWithMessage(LOG_TAG, "Error getting String value for the \"" + key + "\" key from shared preferences. Returning default value \"" + def + "\".", e);

View File

@@ -178,7 +178,7 @@ public class TermuxAppSharedPreferences {
public String getCurrentSession() { public String getCurrentSession() {
return SharedPreferenceUtils.getString(mSharedPreferences, TERMUX_APP.KEY_CURRENT_SESSION, null); return SharedPreferenceUtils.getString(mSharedPreferences, TERMUX_APP.KEY_CURRENT_SESSION, null, true);
} }
public void setCurrentSession(String value) { public void setCurrentSession(String value) {