Added SharedPreferenceUtils

The `SharedPreferenceUtils` class has been added to provide static util functions for shared preferences like get and set while safely handling exceptions. The `TermuxSharedPreferences` class has been renamed to `TermuxAppSharedPreferences` since its to be used to handle only Termux App related shared preferences and not of other plugin apps. For plugin apps, separate classes can be created. However, Termux app and its plugins will share the same `TermuxPreferenceConstants` class that now has per app scoping since `v0.3.0`.
This commit is contained in:
agnostic-apollo
2021-03-16 20:51:41 +05:00
parent 4427c1675d
commit 9e82561804
7 changed files with 221 additions and 50 deletions

View File

@@ -32,7 +32,7 @@ import android.widget.Toast;
import com.termux.R; import com.termux.R;
import com.termux.app.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY; import com.termux.app.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY;
import com.termux.app.settings.preferences.TermuxSharedPreferences; import com.termux.app.settings.preferences.TermuxAppSharedPreferences;
import com.termux.app.terminal.TermuxSessionsListViewController; import com.termux.app.terminal.TermuxSessionsListViewController;
import com.termux.app.terminal.io.TerminalToolbarViewPager; import com.termux.app.terminal.io.TerminalToolbarViewPager;
import com.termux.app.terminal.TermuxSessionClient; import com.termux.app.terminal.TermuxSessionClient;
@@ -93,7 +93,7 @@ public final class TermuxActivity extends Activity implements ServiceConnection
/** /**
* Termux app shared preferences manager. * Termux app shared preferences manager.
*/ */
private TermuxSharedPreferences mPreferences; private TermuxAppSharedPreferences mPreferences;
/** /**
* Termux app shared properties manager, loaded from termux.properties * Termux app shared properties manager, loaded from termux.properties
@@ -154,7 +154,7 @@ public final class TermuxActivity extends Activity implements ServiceConnection
Logger.logDebug(LOG_TAG, "onCreate"); Logger.logDebug(LOG_TAG, "onCreate");
// Load termux shared preferences and properties // Load termux shared preferences and properties
mPreferences = new TermuxSharedPreferences(this); mPreferences = new TermuxAppSharedPreferences(this);
mProperties = new TermuxSharedProperties(this); mProperties = new TermuxSharedProperties(this);
setActivityTheme(); setActivityTheme();
@@ -670,7 +670,7 @@ public final class TermuxActivity extends Activity implements ServiceConnection
return null; return null;
} }
public TermuxSharedPreferences getPreferences() { public TermuxAppSharedPreferences getPreferences() {
return mPreferences; return mPreferences;
} }

View File

@@ -2,7 +2,7 @@ package com.termux.app;
import android.app.Application; import android.app.Application;
import com.termux.app.settings.preferences.TermuxSharedPreferences; import com.termux.app.settings.preferences.TermuxAppSharedPreferences;
import com.termux.app.utils.Logger; import com.termux.app.utils.Logger;
@@ -15,7 +15,7 @@ public class TermuxApplication extends Application {
private void updateLogLevel() { private void updateLogLevel() {
// Load the log level from shared preferences and set it to the {@link Loggger.CURRENT_LOG_LEVEL} // Load the log level from shared preferences and set it to the {@link Loggger.CURRENT_LOG_LEVEL}
TermuxSharedPreferences preferences = new TermuxSharedPreferences(getApplicationContext()); TermuxAppSharedPreferences preferences = new TermuxAppSharedPreferences(getApplicationContext());
preferences.setLogLevel(null, preferences.getLogLevel()); preferences.setLogLevel(null, preferences.getLogLevel());
Logger.logDebug("Starting Application"); Logger.logDebug("Starting Application");
} }

View File

@@ -23,7 +23,7 @@ import android.widget.ArrayAdapter;
import com.termux.R; import com.termux.R;
import com.termux.app.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY; import com.termux.app.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY;
import com.termux.app.TermuxConstants.TERMUX_APP.TERMUX_SERVICE; import com.termux.app.TermuxConstants.TERMUX_APP.TERMUX_SERVICE;
import com.termux.app.settings.preferences.TermuxSharedPreferences; import com.termux.app.settings.preferences.TermuxAppSharedPreferences;
import com.termux.app.terminal.TermuxSessionClient; import com.termux.app.terminal.TermuxSessionClient;
import com.termux.app.terminal.TermuxSessionClientBase; import com.termux.app.terminal.TermuxSessionClientBase;
import com.termux.app.utils.Logger; import com.termux.app.utils.Logger;
@@ -161,7 +161,7 @@ public final class TermuxService extends Service {
} }
// Make the newly created session the current one to be displayed: // Make the newly created session the current one to be displayed:
TermuxSharedPreferences preferences = new TermuxSharedPreferences(this); TermuxAppSharedPreferences preferences = new TermuxAppSharedPreferences(this);
preferences.setCurrentSession(newSession.mHandle); preferences.setCurrentSession(newSession.mHandle);
// Launch the main Termux app, which will now show the current session: // Launch the main Termux app, which will now show the current session:

View File

@@ -12,7 +12,7 @@ import androidx.preference.PreferenceManager;
import com.termux.R; import com.termux.R;
import com.termux.app.settings.preferences.TermuxPreferenceConstants; import com.termux.app.settings.preferences.TermuxPreferenceConstants;
import com.termux.app.settings.preferences.TermuxSharedPreferences; import com.termux.app.settings.preferences.TermuxAppSharedPreferences;
import com.termux.app.utils.Logger; import com.termux.app.utils.Logger;
public class DebuggingPreferencesFragment extends PreferenceFragmentCompat { public class DebuggingPreferencesFragment extends PreferenceFragmentCompat {
@@ -41,7 +41,6 @@ public class DebuggingPreferencesFragment extends PreferenceFragmentCompat {
logLevelListPreference.setEntryValues(logLevels); logLevelListPreference.setEntryValues(logLevels);
logLevelListPreference.setEntries(logLevelLabels); logLevelListPreference.setEntries(logLevelLabels);
logLevelListPreference.setKey(TermuxPreferenceConstants.KEY_LOG_LEVEL);
logLevelListPreference.setValue(String.valueOf(Logger.getLogLevel())); logLevelListPreference.setValue(String.valueOf(Logger.getLogLevel()));
logLevelListPreference.setDefaultValue(Logger.getLogLevel()); logLevelListPreference.setDefaultValue(Logger.getLogLevel());
@@ -53,13 +52,13 @@ public class DebuggingPreferencesFragment extends PreferenceFragmentCompat {
class DebuggingPreferencesDataStore extends PreferenceDataStore { class DebuggingPreferencesDataStore extends PreferenceDataStore {
private final Context mContext; private final Context mContext;
private final TermuxSharedPreferences mPreferences; private final TermuxAppSharedPreferences mPreferences;
private static DebuggingPreferencesDataStore mInstance; private static DebuggingPreferencesDataStore mInstance;
private DebuggingPreferencesDataStore(Context context) { private DebuggingPreferencesDataStore(Context context) {
mContext = context; mContext = context;
mPreferences = new TermuxSharedPreferences(context); mPreferences = new TermuxAppSharedPreferences(context);
} }
public static synchronized DebuggingPreferencesDataStore getInstance(Context context) { public static synchronized DebuggingPreferencesDataStore getInstance(Context context) {
@@ -69,6 +68,8 @@ class DebuggingPreferencesDataStore extends PreferenceDataStore {
return mInstance; return mInstance;
} }
@Override @Override
@Nullable @Nullable
public String getString(String key, @Nullable String defValue) { public String getString(String key, @Nullable String defValue) {
@@ -97,6 +98,8 @@ class DebuggingPreferencesDataStore extends PreferenceDataStore {
} }
} }
@Override @Override
public void putBoolean(String key, boolean value) { public void putBoolean(String key, boolean value) {
if(key == null) return; if(key == null) return;

View File

@@ -0,0 +1,185 @@
package com.termux.app.settings.preferences;
import android.content.SharedPreferences;
import com.termux.app.utils.Logger;
public class SharedPreferenceUtils {
private static final String LOG_TAG = "SharedPreferenceUtils";
/**
* Get a {@code boolean} from {@link SharedPreferences}.
*
* @param sharedPreferences The {@link SharedPreferences} to get the value from.
* @param key The key for the value.
* @param def The default value if failed to read a valid value.
* @return Returns the {@code boolean} value stored in {@link SharedPreferences}, otherwise returns
* default if failed to read a valid value, like in case of an exception.
*/
public static boolean getBoolean(SharedPreferences sharedPreferences, String key, boolean def) {
if(sharedPreferences == null) {
Logger.logError(LOG_TAG, "Error getting boolean value for the \"" + key + "\" key from null shared preferences. Returning default value \"" + def + "\".");
return def;
}
try {
return sharedPreferences.getBoolean(key, def);
}
catch (ClassCastException e) {
Logger.logStackTraceWithMessage(LOG_TAG, "Error getting boolean value for the \"" + key + "\" key from shared preferences. Returning default value \"" + def + "\".", e);
return def;
}
}
/**
* Set a {@code boolean} in {@link SharedPreferences}.
*
* @param sharedPreferences The {@link SharedPreferences} to set the value in.
* @param key The key for the value.
* @param value The value to store.
*/
public static void setBoolean(SharedPreferences sharedPreferences, String key, boolean value) {
if(sharedPreferences == null) {
Logger.logError(LOG_TAG, "Ignoring setting boolean value \"" + value + "\" for the \"" + key + "\" key into null shared preferences.");
return;
}
sharedPreferences.edit().putBoolean(key, value).apply();
}
/**
* Get an {@code int} from {@link SharedPreferences}.
*
* @param sharedPreferences The {@link SharedPreferences} to get the value from.
* @param key The key for the value.
* @param def The default value if failed to read a valid value.
* @return Returns the {@code int} value stored in {@link SharedPreferences}, otherwise returns
* default if failed to read a valid value, like in case of an exception.
*/
public static int getInt(SharedPreferences sharedPreferences, String key, int def) {
if(sharedPreferences == null) {
Logger.logError(LOG_TAG, "Error getting int value for the \"" + key + "\" key from null shared preferences. Returning default value \"" + def + "\".");
return def;
}
try {
return sharedPreferences.getInt(key, def);
}
catch (ClassCastException e) {
Logger.logStackTraceWithMessage(LOG_TAG, "Error getting int value for the \"" + key + "\" key from shared preferences. Returning default value \"" + def + "\".", e);
return def;
}
}
/**
* Set an {@code int} in {@link SharedPreferences}.
*
* @param sharedPreferences The {@link SharedPreferences} to set the value in.
* @param key The key for the value.
* @param value The value to store.
*/
public static void setInt(SharedPreferences sharedPreferences, String key, int value) {
if(sharedPreferences == null) {
Logger.logError(LOG_TAG, "Ignoring setting int value \"" + value + "\" for the \"" + key + "\" key into null shared preferences.");
return;
}
sharedPreferences.edit().putInt(key, value).apply();
}
/**
* Get a {@code String} from {@link SharedPreferences}.
*
* @param sharedPreferences The {@link SharedPreferences} to get the value from.
* @param key The key for the value.
* @param def The default value if failed to read a valid value.
* @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.
*/
public static String getString(SharedPreferences sharedPreferences, String key, String def) {
if(sharedPreferences == null) {
Logger.logError(LOG_TAG, "Error getting String value for the \"" + key + "\" key from null shared preferences. Returning default value \"" + def + "\".");
return def;
}
try {
return sharedPreferences.getString(key, def);
}
catch (ClassCastException e) {
Logger.logStackTraceWithMessage(LOG_TAG, "Error getting String value for the \"" + key + "\" key from shared preferences. Returning default value \"" + def + "\".", e);
return def;
}
}
/**
* Set a {@code String} in {@link SharedPreferences}.
*
* @param sharedPreferences The {@link SharedPreferences} to set the value in.
* @param key The key for the value.
* @param value The value to store.
*/
public static void setString(SharedPreferences sharedPreferences, String key, String value) {
if(sharedPreferences == null) {
Logger.logError(LOG_TAG, "Ignoring setting String value \"" + value + "\" for the \"" + key + "\" key into null shared preferences.");
return;
}
sharedPreferences.edit().putString(key, value).apply();
}
/**
* Get an {@code int} from {@link SharedPreferences} that is stored as a {@link String}.
*
* @param sharedPreferences The {@link SharedPreferences} to get the value from.
* @param key The key for the value.
* @param def The default value if failed to read a valid value.
* @return Returns the {@code int} value after parsing the {@link String} value stored in
* {@link SharedPreferences}, otherwise returns default if failed to read a valid value,
* like in case of an exception.
*/
public static int getIntStoredAsString(SharedPreferences sharedPreferences, String key, int def) {
if(sharedPreferences == null) {
Logger.logError(LOG_TAG, "Error getting int value for the \"" + key + "\" key from null shared preferences. Returning default value \"" + def + "\".");
return def;
}
String stringValue;
int intValue;
try {
stringValue = sharedPreferences.getString(key, Integer.toString(def));
if(stringValue != null)
intValue = Integer.parseInt(stringValue);
else
intValue = def;
} catch (NumberFormatException | ClassCastException e) {
intValue = def;
}
return intValue;
}
/**
* Set an {@code int} into {@link SharedPreferences} that is stored as a {@link String}.
*
* @param sharedPreferences The {@link SharedPreferences} to set the value in.
* @param key The key for the value.
* @param value The value to store.
*/
public static void setIntStoredAsString(SharedPreferences sharedPreferences, String key, int value) {
if(sharedPreferences == null) {
Logger.logError(LOG_TAG, "Ignoring setting int value \"" + value + "\" for the \"" + key + "\" key into null shared preferences.");
return;
}
sharedPreferences.edit().putString(key, Integer.toString(value)).apply();
}
}

View File

@@ -12,7 +12,7 @@ import com.termux.app.settings.preferences.TermuxPreferenceConstants.TERMUX_APP;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public class TermuxSharedPreferences { public class TermuxAppSharedPreferences {
private final Context mContext; private final Context mContext;
private final SharedPreferences mSharedPreferences; private final SharedPreferences mSharedPreferences;
@@ -22,7 +22,9 @@ public class TermuxSharedPreferences {
private int MAX_FONTSIZE; private int MAX_FONTSIZE;
private int DEFAULT_FONTSIZE; private int DEFAULT_FONTSIZE;
public TermuxSharedPreferences(@Nonnull Context context) { private static final String LOG_TAG = "TermuxAppSharedPreferences";
public TermuxAppSharedPreferences(@Nonnull Context context) {
mContext = TermuxUtils.getTermuxPackageContext(context); mContext = TermuxUtils.getTermuxPackageContext(context);
mSharedPreferences = getSharedPreferences(mContext); mSharedPreferences = getSharedPreferences(mContext);
@@ -36,11 +38,11 @@ public class TermuxSharedPreferences {
public boolean getShowTerminalToolbar() { public boolean getShowTerminalToolbar() {
return mSharedPreferences.getBoolean(TERMUX_APP.KEY_SHOW_TERMINAL_TOOLBAR, TERMUX_APP.DEFAULT_VALUE_SHOW_TERMINAL_TOOLBAR); return SharedPreferenceUtils.getBoolean(mSharedPreferences, TERMUX_APP.KEY_SHOW_TERMINAL_TOOLBAR, TERMUX_APP.DEFAULT_VALUE_SHOW_TERMINAL_TOOLBAR);
} }
public void setShowTerminalToolbar(boolean value) { public void setShowTerminalToolbar(boolean value) {
mSharedPreferences.edit().putBoolean(TERMUX_APP.KEY_SHOW_TERMINAL_TOOLBAR, value).apply(); SharedPreferenceUtils.setBoolean(mSharedPreferences, TERMUX_APP.KEY_SHOW_TERMINAL_TOOLBAR, value);
} }
public boolean toogleShowTerminalToolbar() { public boolean toogleShowTerminalToolbar() {
@@ -52,11 +54,11 @@ public class TermuxSharedPreferences {
public boolean getKeepScreenOn() { public boolean getKeepScreenOn() {
return mSharedPreferences.getBoolean(TERMUX_APP.KEY_KEEP_SCREEN_ON, TERMUX_APP.DEFAULT_VALUE_KEEP_SCREEN_ON); return SharedPreferenceUtils.getBoolean(mSharedPreferences, TERMUX_APP.KEY_KEEP_SCREEN_ON, TERMUX_APP.DEFAULT_VALUE_KEEP_SCREEN_ON);
} }
public void setKeepScreenOn(boolean value) { public void setKeepScreenOn(boolean value) {
mSharedPreferences.edit().putBoolean(TERMUX_APP.KEY_KEEP_SCREEN_ON, value).apply(); SharedPreferenceUtils.setBoolean(mSharedPreferences, TERMUX_APP.KEY_KEEP_SCREEN_ON, value);
} }
@@ -79,72 +81,53 @@ public class TermuxSharedPreferences {
} }
public int getFontSize() { public int getFontSize() {
int fontSize; int fontSize = SharedPreferenceUtils.getIntStoredAsString(mSharedPreferences, TERMUX_APP.KEY_FONTSIZE, DEFAULT_FONTSIZE);
String fontString; return TextDataUtils.clamp(fontSize, MIN_FONTSIZE, MAX_FONTSIZE);
try {
fontString = mSharedPreferences.getString(TERMUX_APP.KEY_FONTSIZE, Integer.toString(DEFAULT_FONTSIZE));
if(fontString != null)
fontSize = Integer.parseInt(fontString);
else
fontSize = DEFAULT_FONTSIZE;
} catch (NumberFormatException | ClassCastException e) {
fontSize = DEFAULT_FONTSIZE;
}
fontSize = TextDataUtils.clamp(fontSize, MIN_FONTSIZE, MAX_FONTSIZE);
return fontSize;
} }
public void setFontSize(String value) { public void setFontSize(int value) {
mSharedPreferences.edit().putString(TERMUX_APP.KEY_FONTSIZE, value).apply(); SharedPreferenceUtils.setIntStoredAsString(mSharedPreferences, TERMUX_APP.KEY_FONTSIZE, value);
} }
public void changeFontSize(Context context, boolean increase) { public void changeFontSize(boolean increase) {
int fontSize = getFontSize(); int fontSize = getFontSize();
fontSize += (increase ? 1 : -1) * 2; fontSize += (increase ? 1 : -1) * 2;
fontSize = Math.max(MIN_FONTSIZE, Math.min(fontSize, MAX_FONTSIZE)); fontSize = Math.max(MIN_FONTSIZE, Math.min(fontSize, MAX_FONTSIZE));
setFontSize(Integer.toString(fontSize)); setFontSize(fontSize);
} }
public String getCurrentSession() { public String getCurrentSession() {
return mSharedPreferences.getString(TERMUX_APP.KEY_CURRENT_SESSION, ""); return SharedPreferenceUtils.getString(mSharedPreferences, TERMUX_APP.KEY_CURRENT_SESSION, null);
} }
public void setCurrentSession(String value) { public void setCurrentSession(String value) {
mSharedPreferences.edit().putString(TERMUX_APP.KEY_CURRENT_SESSION, value).apply(); SharedPreferenceUtils.setString(mSharedPreferences, TERMUX_APP.KEY_CURRENT_SESSION, value);
} }
public int getLogLevel() { public int getLogLevel() {
try { return SharedPreferenceUtils.getInt(mSharedPreferences, TERMUX_APP.KEY_LOG_LEVEL, Logger.DEFAULT_LOG_LEVEL);
return mSharedPreferences.getInt(TERMUX_APP.KEY_LOG_LEVEL, Logger.DEFAULT_LOG_LEVEL);
}
catch (Exception e) {
Logger.logStackTraceWithMessage("Error getting \"" + TERMUX_APP.KEY_LOG_LEVEL + "\" from shared preferences", e);
return Logger.DEFAULT_LOG_LEVEL;
}
} }
public void setLogLevel(Context context, int logLevel) { public void setLogLevel(Context context, int logLevel) {
logLevel = Logger.setLogLevel(context, logLevel); logLevel = Logger.setLogLevel(context, logLevel);
mSharedPreferences.edit().putInt(TERMUX_APP.KEY_LOG_LEVEL, logLevel).apply(); SharedPreferenceUtils.setInt(mSharedPreferences, TERMUX_APP.KEY_LOG_LEVEL, logLevel);
} }
public boolean getTerminalViewKeyLoggingEnabled() { public boolean getTerminalViewKeyLoggingEnabled() {
return mSharedPreferences.getBoolean(TERMUX_APP.KEY_TERMINAL_VIEW_KEY_LOGGING_ENABLED, TERMUX_APP.DEFAULT_VALUE_TERMINAL_VIEW_KEY_LOGGING_ENABLED); return SharedPreferenceUtils.getBoolean(mSharedPreferences, TERMUX_APP.KEY_TERMINAL_VIEW_KEY_LOGGING_ENABLED, TERMUX_APP.DEFAULT_VALUE_TERMINAL_VIEW_KEY_LOGGING_ENABLED);
} }
public void setTerminalViewKeyLoggingEnabled(boolean value) { public void setTerminalViewKeyLoggingEnabled(boolean value) {
mSharedPreferences.edit().putBoolean(TERMUX_APP.KEY_TERMINAL_VIEW_KEY_LOGGING_ENABLED, value).apply(); SharedPreferenceUtils.setBoolean(mSharedPreferences, TERMUX_APP.KEY_TERMINAL_VIEW_KEY_LOGGING_ENABLED, value);
} }
} }

View File

@@ -328,7 +328,7 @@ public class TermuxViewClient implements TerminalViewClient {
public void changeFontSize(boolean increase) { public void changeFontSize(boolean increase) {
mActivity.getPreferences().changeFontSize(mActivity, increase); mActivity.getPreferences().changeFontSize(increase);
mActivity.getTerminalView().setTextSize(mActivity.getPreferences().getFontSize()); mActivity.getTerminalView().setTextSize(mActivity.getPreferences().getFontSize());
} }