Use requireContext, requireActivity and requirePreference where possible

This commit is contained in:
Alexander Bakker 2022-04-10 18:44:25 +02:00
parent f7b4cceb81
commit beadf4db8b
17 changed files with 123 additions and 113 deletions

View file

@ -47,14 +47,14 @@ public abstract class DatabaseImporter {
_context = context; _context = context;
} }
protected Context getContext() { protected Context requireContext() {
return _context; return _context;
} }
protected abstract SuFile getAppPath() throws DatabaseImporterException, PackageManager.NameNotFoundException; protected abstract SuFile getAppPath() throws DatabaseImporterException, PackageManager.NameNotFoundException;
protected SuFile getAppPath(String pkgName, String subPath) throws PackageManager.NameNotFoundException { protected SuFile getAppPath(String pkgName, String subPath) throws PackageManager.NameNotFoundException {
PackageManager man = getContext().getPackageManager(); PackageManager man = requireContext().getPackageManager();
return new SuFile(man.getApplicationInfo(pkgName, 0).dataDir, subPath); return new SuFile(man.getApplicationInfo(pkgName, 0).dataDir, subPath);
} }

View file

@ -34,7 +34,7 @@ public class FreeOtpPlusImporter extends DatabaseImporter {
State state; State state;
if (isInternal) { if (isInternal) {
state = new FreeOtpImporter(getContext()).read(stream); state = new FreeOtpImporter(requireContext()).read(stream);
} else { } else {
try { try {
String json = new String(IOUtils.readAll(stream), StandardCharsets.UTF_8); String json = new String(IOUtils.readAll(stream), StandardCharsets.UTF_8);

View file

@ -34,7 +34,7 @@ public class GoogleAuthImporter extends DatabaseImporter {
@Override @Override
public State read(InputStream stream, boolean isInternal) throws DatabaseImporterException { public State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
SqlImporterHelper helper = new SqlImporterHelper(getContext()); SqlImporterHelper helper = new SqlImporterHelper(requireContext());
List<Entry> entries = helper.read(Entry.class, stream, "accounts"); List<Entry> entries = helper.read(Entry.class, stream, "accounts");
return new State(entries); return new State(entries);
} }
@ -42,7 +42,7 @@ public class GoogleAuthImporter extends DatabaseImporter {
@Override @Override
public DatabaseImporter.State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException { public DatabaseImporter.State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile path = getAppPath(); SuFile path = getAppPath();
SqlImporterHelper helper = new SqlImporterHelper(getContext()); SqlImporterHelper helper = new SqlImporterHelper(requireContext());
List<Entry> entries = helper.read(Entry.class, path, "accounts"); List<Entry> entries = helper.read(Entry.class, path, "accounts");
return new State(entries); return new State(entries);
} }

View file

@ -34,7 +34,7 @@ public class MicrosoftAuthImporter extends DatabaseImporter {
@Override @Override
public State read(InputStream stream, boolean isInternal) throws DatabaseImporterException { public State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
SqlImporterHelper helper = new SqlImporterHelper(getContext()); SqlImporterHelper helper = new SqlImporterHelper(requireContext());
List<Entry> entries = helper.read(Entry.class, stream, "accounts"); List<Entry> entries = helper.read(Entry.class, stream, "accounts");
return new State(entries); return new State(entries);
} }
@ -42,7 +42,7 @@ public class MicrosoftAuthImporter extends DatabaseImporter {
@Override @Override
public DatabaseImporter.State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException { public DatabaseImporter.State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile path = getAppPath(); SuFile path = getAppPath();
SqlImporterHelper helper = new SqlImporterHelper(getContext()); SqlImporterHelper helper = new SqlImporterHelper(requireContext());
List<Entry> entries = helper.read(Entry.class, path, "accounts"); List<Entry> entries = helper.read(Entry.class, path, "accounts");
return new State(entries); return new State(entries);
} }

View file

@ -19,7 +19,7 @@ public class WinAuthImporter extends DatabaseImporter {
@Override @Override
public WinAuthImporter.State read(InputStream stream, boolean isInternal) throws DatabaseImporterException { public WinAuthImporter.State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
GoogleAuthUriImporter importer = new GoogleAuthUriImporter(getContext()); GoogleAuthUriImporter importer = new GoogleAuthUriImporter(requireContext());
DatabaseImporter.State state = importer.read(stream); DatabaseImporter.State state = importer.read(stream);
return new State(state); return new State(state);
} }

View file

@ -41,23 +41,23 @@ public abstract class SimpleWebViewDialog extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) { public Dialog onCreateDialog(Bundle savedInstanceState) {
final View view; final View view;
try { try {
view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_web_view, null); view = LayoutInflater.from(requireActivity()).inflate(R.layout.dialog_web_view, null);
} catch (InflateException e) { } catch (InflateException e) {
e.printStackTrace(); e.printStackTrace();
return new AlertDialog.Builder(getActivity()) return new AlertDialog.Builder(requireActivity())
.setTitle(android.R.string.dialog_alert_title) .setTitle(android.R.string.dialog_alert_title)
.setMessage(getString(R.string.webview_error)) .setMessage(getString(R.string.webview_error))
.setPositiveButton(android.R.string.ok, null) .setPositiveButton(android.R.string.ok, null)
.show(); .show();
} }
AlertDialog dialog = new AlertDialog.Builder(getActivity()) AlertDialog dialog = new AlertDialog.Builder(requireActivity())
.setTitle(_title) .setTitle(_title)
.setView(view) .setView(view)
.setPositiveButton(android.R.string.ok, null) .setPositiveButton(android.R.string.ok, null)
.show(); .show();
String content = getContent(getContext()); String content = getContent(requireContext());
final WebView webView = view.findViewById(R.id.web_view); final WebView webView = view.findViewById(R.id.web_view);
webView.loadData(content, "text/html", "UTF-8"); webView.loadData(content, "text/html", "UTF-8");
return dialog; return dialog;
@ -70,11 +70,11 @@ public abstract class SimpleWebViewDialog extends DialogFragment {
protected String getBackgroundColor() { protected String getBackgroundColor() {
int backgroundColorResource = _theme == Theme.AMOLED ? R.attr.cardBackgroundFocused : R.attr.cardBackground; int backgroundColorResource = _theme == Theme.AMOLED ? R.attr.cardBackgroundFocused : R.attr.cardBackground;
return colorToCSS(ThemeHelper.getThemeColor(backgroundColorResource, getContext().getTheme())); return colorToCSS(ThemeHelper.getThemeColor(backgroundColorResource, requireContext().getTheme()));
} }
protected String getTextColor() { protected String getTextColor() {
return colorToCSS(0xFFFFFF & ThemeHelper.getThemeColor(R.attr.primaryText, getContext().getTheme())); return colorToCSS(0xFFFFFF & ThemeHelper.getThemeColor(R.attr.primaryText, requireContext().getTheme()));
} }
@SuppressLint("DefaultLocale") @SuppressLint("DefaultLocale")

View file

@ -27,17 +27,17 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
super.onCreatePreferences(savedInstanceState, rootKey); super.onCreatePreferences(savedInstanceState, rootKey);
addPreferencesFromResource(R.xml.preferences_appearance); addPreferencesFromResource(R.xml.preferences_appearance);
_groupsPreference = findPreference("pref_groups"); _groupsPreference = requirePreference("pref_groups");
_groupsPreference.setOnPreferenceClickListener(preference -> { _groupsPreference.setOnPreferenceClickListener(preference -> {
Intent intent = new Intent(getActivity(), GroupManagerActivity.class); Intent intent = new Intent(requireActivity(), GroupManagerActivity.class);
intent.putExtra("groups", new ArrayList<>(_vaultManager.getVault().getGroups())); intent.putExtra("groups", new ArrayList<>(_vaultManager.getVault().getGroups()));
startActivityForResult(intent, CODE_GROUPS); startActivityForResult(intent, CODE_GROUPS);
return true; return true;
}); });
_resetUsageCountPreference = findPreference("pref_reset_usage_count"); _resetUsageCountPreference = requirePreference("pref_reset_usage_count");
_resetUsageCountPreference.setOnPreferenceClickListener(preference -> { _resetUsageCountPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showSecureDialog(new AlertDialog.Builder(getActivity()) Dialogs.showSecureDialog(new AlertDialog.Builder(requireActivity())
.setTitle(R.string.preference_reset_usage_count) .setTitle(R.string.preference_reset_usage_count)
.setMessage(R.string.preference_reset_usage_count_dialog) .setMessage(R.string.preference_reset_usage_count_dialog)
.setPositiveButton(android.R.string.yes, (dialog, which) -> _prefs.clearUsageCount()) .setPositiveButton(android.R.string.yes, (dialog, which) -> _prefs.clearUsageCount())
@ -47,12 +47,12 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
}); });
int currentTheme = _prefs.getCurrentTheme().ordinal(); int currentTheme = _prefs.getCurrentTheme().ordinal();
Preference darkModePreference = findPreference("pref_dark_mode"); Preference darkModePreference = requirePreference("pref_dark_mode");
darkModePreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.theme_titles)[currentTheme])); darkModePreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.theme_titles)[currentTheme]));
darkModePreference.setOnPreferenceClickListener(preference -> { darkModePreference.setOnPreferenceClickListener(preference -> {
int currentTheme1 = _prefs.getCurrentTheme().ordinal(); int currentTheme1 = _prefs.getCurrentTheme().ordinal();
Dialogs.showSecureDialog(new AlertDialog.Builder(getActivity()) Dialogs.showSecureDialog(new AlertDialog.Builder(requireActivity())
.setTitle(R.string.choose_theme) .setTitle(R.string.choose_theme)
.setSingleChoiceItems(R.array.theme_titles, currentTheme1, (dialog, which) -> { .setSingleChoiceItems(R.array.theme_titles, currentTheme1, (dialog, which) -> {
int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition(); int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
@ -61,7 +61,7 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
dialog.dismiss(); dialog.dismiss();
getResult().putExtra("needsRecreate", true); getResult().putExtra("needsRecreate", true);
getActivity().recreate(); requireActivity().recreate();
}) })
.setNegativeButton(android.R.string.cancel, null) .setNegativeButton(android.R.string.cancel, null)
.create()); .create());
@ -69,11 +69,11 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
return true; return true;
}); });
Preference langPreference = findPreference("pref_lang"); Preference langPreference = requirePreference("pref_lang");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
langPreference.setOnPreferenceChangeListener((preference, newValue) -> { langPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRecreate", true); getResult().putExtra("needsRecreate", true);
getActivity().recreate(); requireActivity().recreate();
return true; return true;
}); });
} else { } else {
@ -82,12 +82,12 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
} }
int currentViewMode = _prefs.getCurrentViewMode().ordinal(); int currentViewMode = _prefs.getCurrentViewMode().ordinal();
Preference viewModePreference = findPreference("pref_view_mode"); Preference viewModePreference = requirePreference("pref_view_mode");
viewModePreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.view_mode_titles)[currentViewMode])); viewModePreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.view_mode_titles)[currentViewMode]));
viewModePreference.setOnPreferenceClickListener(preference -> { viewModePreference.setOnPreferenceClickListener(preference -> {
int currentViewMode1 = _prefs.getCurrentViewMode().ordinal(); int currentViewMode1 = _prefs.getCurrentViewMode().ordinal();
Dialogs.showSecureDialog(new AlertDialog.Builder(getActivity()) Dialogs.showSecureDialog(new AlertDialog.Builder(requireActivity())
.setTitle(R.string.choose_view_mode) .setTitle(R.string.choose_view_mode)
.setSingleChoiceItems(R.array.view_mode_titles, currentViewMode1, (dialog, which) -> { .setSingleChoiceItems(R.array.view_mode_titles, currentViewMode1, (dialog, which) -> {
int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition(); int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
@ -102,13 +102,13 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
return true; return true;
}); });
Preference codeDigitGroupingPreference = findPreference("pref_code_group_size"); Preference codeDigitGroupingPreference = requirePreference("pref_code_group_size");
codeDigitGroupingPreference.setOnPreferenceChangeListener((preference, newValue) -> { codeDigitGroupingPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true); getResult().putExtra("needsRefresh", true);
return true; return true;
}); });
Preference issuerPreference = findPreference("pref_account_name"); Preference issuerPreference = requirePreference("pref_account_name");
issuerPreference.setOnPreferenceChangeListener((preference, newValue) -> { issuerPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true); getResult().putExtra("needsRefresh", true);
return true; return true;

View file

@ -32,7 +32,7 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
super.onCreatePreferences(savedInstanceState, rootKey); super.onCreatePreferences(savedInstanceState, rootKey);
addPreferencesFromResource(R.xml.preferences_backups); addPreferencesFromResource(R.xml.preferences_backups);
_backupsPreference = findPreference("pref_backups"); _backupsPreference = requirePreference("pref_backups");
_backupsPreference.setOnPreferenceChangeListener((preference, newValue) -> { _backupsPreference.setOnPreferenceChangeListener((preference, newValue) -> {
if ((boolean) newValue) { if ((boolean) newValue) {
selectBackupsLocation(); selectBackupsLocation();
@ -44,7 +44,7 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
return false; return false;
}); });
_androidBackupsPreference = findPreference("pref_android_backups"); _androidBackupsPreference = requirePreference("pref_android_backups");
_androidBackupsPreference.setOnPreferenceChangeListener((preference, newValue) -> { _androidBackupsPreference.setOnPreferenceChangeListener((preference, newValue) -> {
_prefs.setIsAndroidBackupsEnabled((boolean) newValue); _prefs.setIsAndroidBackupsEnabled((boolean) newValue);
updateBackupPreference(); updateBackupPreference();
@ -53,7 +53,7 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
}); });
Uri backupLocation = _prefs.getBackupsLocation(); Uri backupLocation = _prefs.getBackupsLocation();
_backupsLocationPreference = findPreference("pref_backups_location"); _backupsLocationPreference = requirePreference("pref_backups_location");
if (backupLocation != null) { if (backupLocation != null) {
_backupsLocationPreference.setSummary(String.format("%s: %s", getString(R.string.pref_backups_location_summary), Uri.decode(backupLocation.toString()))); _backupsLocationPreference.setSummary(String.format("%s: %s", getString(R.string.pref_backups_location_summary), Uri.decode(backupLocation.toString())));
} }
@ -62,7 +62,7 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
return false; return false;
}); });
_backupsTriggerPreference = findPreference("pref_backups_trigger"); _backupsTriggerPreference = requirePreference("pref_backups_trigger");
_backupsTriggerPreference.setOnPreferenceClickListener(preference -> { _backupsTriggerPreference.setOnPreferenceClickListener(preference -> {
if (_prefs.isBackupsEnabled()) { if (_prefs.isBackupsEnabled()) {
scheduleBackup(); scheduleBackup();
@ -70,10 +70,10 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
return true; return true;
}); });
_backupsVersionsPreference = findPreference("pref_backups_versions"); _backupsVersionsPreference = requirePreference("pref_backups_versions");
_backupsVersionsPreference.setSummary(getResources().getQuantityString(R.plurals.pref_backups_versions_summary, _prefs.getBackupsVersionCount(), _prefs.getBackupsVersionCount())); _backupsVersionsPreference.setSummary(getResources().getQuantityString(R.plurals.pref_backups_versions_summary, _prefs.getBackupsVersionCount(), _prefs.getBackupsVersionCount()));
_backupsVersionsPreference.setOnPreferenceClickListener(preference -> { _backupsVersionsPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showBackupVersionsPickerDialog(getActivity(), _prefs.getBackupsVersionCount(), number -> { Dialogs.showBackupVersionsPickerDialog(requireActivity(), _prefs.getBackupsVersionCount(), number -> {
number = number * 5 + 5; number = number * 5 + 5;
_prefs.setBackupsVersionCount(number); _prefs.setBackupsVersionCount(number);
_backupsVersionsPreference.setSummary(getResources().getQuantityString(R.plurals.pref_backups_versions_summary, _prefs.getBackupsVersionCount(), _prefs.getBackupsVersionCount())); _backupsVersionsPreference.setSummary(getResources().getQuantityString(R.plurals.pref_backups_versions_summary, _prefs.getBackupsVersionCount(), _prefs.getBackupsVersionCount()));
@ -96,7 +96,7 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
} }
int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION; int flags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
getContext().getContentResolver().takePersistableUriPermission(data.getData(), flags); requireContext().getContentResolver().takePersistableUriPermission(data.getData(), flags);
_prefs.setBackupsLocation(uri); _prefs.setBackupsLocation(uri);
_prefs.setIsBackupsEnabled(true); _prefs.setIsBackupsEnabled(true);
@ -132,10 +132,10 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
private void scheduleBackup() { private void scheduleBackup() {
try { try {
_vaultManager.scheduleBackup(); _vaultManager.scheduleBackup();
Toast.makeText(getActivity(), R.string.backup_successful, Toast.LENGTH_LONG).show(); Toast.makeText(requireActivity(), R.string.backup_successful, Toast.LENGTH_LONG).show();
} catch (VaultRepositoryException e) { } catch (VaultRepositoryException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.backup_error, e); Dialogs.showErrorDialog(requireContext(), R.string.backup_error, e);
} }
} }
} }

View file

@ -14,20 +14,20 @@ public class BehaviorPreferencesFragment extends PreferencesFragment {
super.onCreatePreferences(savedInstanceState, rootKey); super.onCreatePreferences(savedInstanceState, rootKey);
addPreferencesFromResource(R.xml.preferences_behavior); addPreferencesFromResource(R.xml.preferences_behavior);
Preference copyOnTapPreference = findPreference("pref_copy_on_tap"); Preference copyOnTapPreference = requirePreference("pref_copy_on_tap");
copyOnTapPreference.setOnPreferenceChangeListener((preference, newValue) -> { copyOnTapPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true); getResult().putExtra("needsRefresh", true);
return true; return true;
}); });
Preference entryHighlightPreference = findPreference("pref_highlight_entry"); Preference entryHighlightPreference = requirePreference("pref_highlight_entry");
entryHighlightPreference.setOnPreferenceChangeListener((preference, newValue) -> { entryHighlightPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true); getResult().putExtra("needsRefresh", true);
_entryPausePreference.setEnabled(_prefs.isTapToRevealEnabled() || (boolean) newValue); _entryPausePreference.setEnabled(_prefs.isTapToRevealEnabled() || (boolean) newValue);
return true; return true;
}); });
_entryPausePreference = findPreference("pref_pause_entry"); _entryPausePreference = requirePreference("pref_pause_entry");
_entryPausePreference.setOnPreferenceChangeListener((preference, newValue) -> { _entryPausePreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true); getResult().putExtra("needsRefresh", true);
return true; return true;

View file

@ -62,7 +62,7 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
_iconPacksView = view.findViewById(R.id.view_icon_packs); _iconPacksView = view.findViewById(R.id.view_icon_packs);
_adapter = new IconPackAdapter(this); _adapter = new IconPackAdapter(this);
_iconPacksRecyclerView = view.findViewById(R.id.list_icon_packs); _iconPacksRecyclerView = view.findViewById(R.id.list_icon_packs);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
_iconPacksRecyclerView.setLayoutManager(layoutManager); _iconPacksRecyclerView.setLayoutManager(layoutManager);
_iconPacksRecyclerView.setAdapter(_adapter); _iconPacksRecyclerView.setAdapter(_adapter);
_iconPacksRecyclerView.setNestedScrollingEnabled(false); _iconPacksRecyclerView.setNestedScrollingEnabled(false);
@ -83,7 +83,7 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
@Override @Override
public void onRemoveIconPack(IconPack pack) { public void onRemoveIconPack(IconPack pack) {
Dialogs.showSecureDialog(new AlertDialog.Builder(getContext()) Dialogs.showSecureDialog(new AlertDialog.Builder(requireContext())
.setTitle(R.string.remove_icon_pack) .setTitle(R.string.remove_icon_pack)
.setMessage(R.string.remove_icon_pack_description) .setMessage(R.string.remove_icon_pack_description)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> { .setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
@ -91,7 +91,7 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
_iconPackManager.removeIconPack(pack); _iconPackManager.removeIconPack(pack);
} catch (IconPackException e) { } catch (IconPackException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.icon_pack_delete_error, e); Dialogs.showErrorDialog(requireContext(), R.string.icon_pack_delete_error, e);
return; return;
} }
_adapter.removeIconPack(pack); _adapter.removeIconPack(pack);
@ -111,10 +111,10 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
} }
private void importIconPack(Uri uri) { private void importIconPack(Uri uri) {
ImportIconPackTask task = new ImportIconPackTask(getContext(), result -> { ImportIconPackTask task = new ImportIconPackTask(requireContext(), result -> {
Exception e = result.getException(); Exception e = result.getException();
if (e instanceof IconPackExistsException) { if (e instanceof IconPackExistsException) {
Dialogs.showSecureDialog(new AlertDialog.Builder(getContext()) Dialogs.showSecureDialog(new AlertDialog.Builder(requireContext())
.setTitle(R.string.error_occurred) .setTitle(R.string.error_occurred)
.setMessage(R.string.icon_pack_import_exists_error) .setMessage(R.string.icon_pack_import_exists_error)
.setPositiveButton(R.string.yes, (dialog, which) -> { .setPositiveButton(R.string.yes, (dialog, which) -> {
@ -125,7 +125,7 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
.setNegativeButton(R.string.no, null) .setNegativeButton(R.string.no, null)
.create()); .create());
} else if (e != null) { } else if (e != null) {
Dialogs.showErrorDialog(getContext(), R.string.icon_pack_import_error, e); Dialogs.showErrorDialog(requireContext(), R.string.icon_pack_import_error, e);
} else { } else {
_adapter.addIconPack(result.getIconPack()); _adapter.addIconPack(result.getIconPack());
updateEmptyState(); updateEmptyState();
@ -139,7 +139,7 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
_iconPackManager.removeIconPack(pack); _iconPackManager.removeIconPack(pack);
} catch (IconPackException e) { } catch (IconPackException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.icon_pack_delete_error, e); Dialogs.showErrorDialog(requireContext(), R.string.icon_pack_delete_error, e);
return false; return false;
} }

View file

@ -53,9 +53,9 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
_importerType = (Class<? extends DatabaseImporter>) savedInstanceState.getSerializable("importerType"); _importerType = (Class<? extends DatabaseImporter>) savedInstanceState.getSerializable("importerType");
} }
Preference importPreference = findPreference("pref_import"); Preference importPreference = requirePreference("pref_import");
importPreference.setOnPreferenceClickListener(preference -> { importPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showImportersDialog(getContext(), false, definition -> { Dialogs.showImportersDialog(requireContext(), false, definition -> {
_importerType = definition.getType(); _importerType = definition.getType();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
@ -65,15 +65,15 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
return true; return true;
}); });
Preference importAppPreference = findPreference("pref_import_app"); Preference importAppPreference = requirePreference("pref_import_app");
importAppPreference.setOnPreferenceClickListener(preference -> { importAppPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showImportersDialog(getContext(), true, definition -> { Dialogs.showImportersDialog(requireContext(), true, definition -> {
startImportEntriesActivity(definition.getType(), null); startImportEntriesActivity(definition.getType(), null);
}); });
return true; return true;
}); });
Preference exportPreference = findPreference("pref_export"); Preference exportPreference = requirePreference("pref_export");
exportPreference.setOnPreferenceClickListener(preference -> { exportPreference.setOnPreferenceClickListener(preference -> {
startExport(); startExport();
return true; return true;
@ -113,30 +113,30 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
} }
ImportFileTask.Params params = new ImportFileTask.Params(uri, "import", null); ImportFileTask.Params params = new ImportFileTask.Params(uri, "import", null);
ImportFileTask task = new ImportFileTask(getContext(), result -> { ImportFileTask task = new ImportFileTask(requireContext(), result -> {
if (result.getException() == null) { if (result.getException() == null) {
startImportEntriesActivity(_importerType, result.getFile()); startImportEntriesActivity(_importerType, result.getFile());
} else { } else {
Dialogs.showErrorDialog(getContext(), R.string.reading_file_error, result.getException()); Dialogs.showErrorDialog(requireContext(), R.string.reading_file_error, result.getException());
} }
}); });
task.execute(getLifecycle(), params); task.execute(getLifecycle(), params);
} }
private void startImportEntriesActivity(Class<? extends DatabaseImporter> importerType, File file) { private void startImportEntriesActivity(Class<? extends DatabaseImporter> importerType, File file) {
Intent intent = new Intent(getActivity(), ImportEntriesActivity.class); Intent intent = new Intent(requireActivity(), ImportEntriesActivity.class);
intent.putExtra("importerType", importerType); intent.putExtra("importerType", importerType);
intent.putExtra("file", file); intent.putExtra("file", file);
startActivityForResult(intent, CODE_IMPORT); startActivityForResult(intent, CODE_IMPORT);
} }
private void startExport() { private void startExport() {
View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_export, null); View view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_export, null);
TextView warningText = view.findViewById(R.id.text_export_warning); TextView warningText = view.findViewById(R.id.text_export_warning);
CheckBox checkBoxEncrypt = view.findViewById(R.id.checkbox_export_encrypt); CheckBox checkBoxEncrypt = view.findViewById(R.id.checkbox_export_encrypt);
CheckBox checkBoxAccept = view.findViewById(R.id.checkbox_accept); CheckBox checkBoxAccept = view.findViewById(R.id.checkbox_accept);
AutoCompleteTextView dropdown = view.findViewById(R.id.dropdown_export_format); AutoCompleteTextView dropdown = view.findViewById(R.id.dropdown_export_format);
DropdownHelper.fillDropdown(getContext(), dropdown, R.array.export_formats); DropdownHelper.fillDropdown(requireContext(), dropdown, R.array.export_formats);
dropdown.setText(getString(R.string.export_format_aegis), false); dropdown.setText(getString(R.string.export_format_aegis), false);
dropdown.setOnItemClickListener((parent, view1, position, id) -> { dropdown.setOnItemClickListener((parent, view1, position, id) -> {
checkBoxEncrypt.setChecked(position == 0); checkBoxEncrypt.setChecked(position == 0);
@ -144,7 +144,7 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
warningText.setVisibility(checkBoxEncrypt.isChecked() ? View.GONE : View.VISIBLE); warningText.setVisibility(checkBoxEncrypt.isChecked() ? View.GONE : View.VISIBLE);
}); });
AlertDialog dialog = new AlertDialog.Builder(getContext()) AlertDialog dialog = new AlertDialog.Builder(requireContext())
.setTitle(R.string.pref_export_summary) .setTitle(R.string.pref_export_summary)
.setView(view) .setView(view)
.setNeutralButton(R.string.share, null) .setNeutralButton(R.string.share, null)
@ -200,7 +200,7 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
file = File.createTempFile(fileInfo.getFilename() + "-", "." + fileInfo.getExtension(), getExportCacheDir()); file = File.createTempFile(fileInfo.getFilename() + "-", "." + fileInfo.getExtension(), getExportCacheDir());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.exporting_vault_error, e); Dialogs.showErrorDialog(requireContext(), R.string.exporting_vault_error, e);
return; return;
} }
@ -210,14 +210,14 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
cb.exportVault(stream); cb.exportVault(stream);
} catch (IOException | VaultRepositoryException e) { } catch (IOException | VaultRepositoryException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.exporting_vault_error, e); Dialogs.showErrorDialog(requireContext(), R.string.exporting_vault_error, e);
return; return;
} }
// if the user creates an export, hide the backup reminder // if the user creates an export, hide the backup reminder
_prefs.setIsBackupReminderNeeded(false); _prefs.setIsBackupReminderNeeded(false);
Uri uri = FileProvider.getUriForFile(getContext(), BuildConfig.FILE_PROVIDER_AUTHORITY, file); Uri uri = FileProvider.getUriForFile(requireContext(), BuildConfig.FILE_PROVIDER_AUTHORITY, file);
Intent intent = new Intent(Intent.ACTION_SEND) Intent intent = new Intent(Intent.ACTION_SEND)
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.setType(getExportMimeType(requestCode)) .setType(getExportMimeType(requestCode))
@ -253,7 +253,7 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
} }
private File getExportCacheDir() throws IOException { private File getExportCacheDir() throws IOException {
File dir = new File(getContext().getCacheDir(), "export"); File dir = new File(requireContext().getCacheDir(), "export");
if (!dir.exists() && !dir.mkdir()) { if (!dir.exists() && !dir.mkdir()) {
throw new IOException(String.format("Unable to create directory %s", dir)); throw new IOException(String.format("Unable to create directory %s", dir));
} }
@ -267,7 +267,7 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
if (_vaultManager.getVault().isEncryptionEnabled()) { if (_vaultManager.getVault().isEncryptionEnabled()) {
cb.exportVault(stream -> _vaultManager.getVault().export(stream)); cb.exportVault(stream -> _vaultManager.getVault().export(stream));
} else { } else {
Dialogs.showSetPasswordDialog(getActivity(), new Dialogs.SlotListener() { Dialogs.showSetPasswordDialog(requireActivity(), new Dialogs.SlotListener() {
@Override @Override
public void onSlotResult(Slot slot, Cipher cipher) { public void onSlotResult(Slot slot, Cipher cipher) {
VaultFileCredentials creds = new VaultFileCredentials(); VaultFileCredentials creds = new VaultFileCredentials();
@ -313,10 +313,10 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
outStream = new FileOutputStream(file); outStream = new FileOutputStream(file);
cb.exportVault(outStream); cb.exportVault(outStream);
new ExportTask(getContext(), new ExportResultListener()).execute(getLifecycle(), new ExportTask.Params(file, uri)); new ExportTask(requireContext(), new ExportResultListener()).execute(getLifecycle(), new ExportTask.Params(file, uri));
} catch (VaultRepositoryException | IOException e) { } catch (VaultRepositoryException | IOException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.exporting_vault_error, e); Dialogs.showErrorDialog(requireContext(), R.string.exporting_vault_error, e);
} finally { } finally {
try { try {
if (outStream != null) { if (outStream != null) {
@ -344,12 +344,12 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
public void onTaskFinished(Exception e) { public void onTaskFinished(Exception e) {
if (e != null) { if (e != null) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.exporting_vault_error, e); Dialogs.showErrorDialog(requireContext(), R.string.exporting_vault_error, e);
} else { } else {
// if the user creates an export, hide the backup reminder // if the user creates an export, hide the backup reminder
_prefs.setIsBackupReminderNeeded(false); _prefs.setIsBackupReminderNeeded(false);
Toast.makeText(getContext(), getString(R.string.exported_vault), Toast.LENGTH_SHORT).show(); Toast.makeText(requireContext(), getString(R.string.exported_vault), Toast.LENGTH_SHORT).show();
} }
} }
} }

View file

@ -5,6 +5,8 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import androidx.annotation.CallSuper; import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceFragmentCompat;
import com.beemdevelopment.aegis.Preferences; import com.beemdevelopment.aegis.Preferences;
@ -21,7 +23,6 @@ import dagger.hilt.android.AndroidEntryPoint;
public abstract class PreferencesFragment extends PreferenceFragmentCompat { public abstract class PreferencesFragment extends PreferenceFragmentCompat {
// activity request codes // activity request codes
public static final int CODE_IMPORT_SELECT = 0; public static final int CODE_IMPORT_SELECT = 0;
public static final int CODE_SLOTS = 2;
public static final int CODE_GROUPS = 3; public static final int CODE_GROUPS = 3;
public static final int CODE_IMPORT = 4; public static final int CODE_IMPORT = 4;
public static final int CODE_EXPORT = 5; public static final int CODE_EXPORT = 5;
@ -48,7 +49,7 @@ public abstract class PreferencesFragment extends PreferenceFragmentCompat {
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
Intent intent = getActivity().getIntent(); Intent intent = requireActivity().getIntent();
String preference = intent.getStringExtra("pref"); String preference = intent.getStringExtra("pref");
if (preference != null) { if (preference != null) {
scrollToPreference(preference); scrollToPreference(preference);
@ -62,7 +63,7 @@ public abstract class PreferencesFragment extends PreferenceFragmentCompat {
public void setResult(Intent result) { public void setResult(Intent result) {
_result = result; _result = result;
getActivity().setResult(Activity.RESULT_OK, _result); requireActivity().setResult(Activity.RESULT_OK, _result);
} }
protected boolean saveAndBackupVault() { protected boolean saveAndBackupVault() {
@ -70,10 +71,20 @@ public abstract class PreferencesFragment extends PreferenceFragmentCompat {
_vaultManager.saveAndBackup(); _vaultManager.saveAndBackup();
} catch (VaultRepositoryException e) { } catch (VaultRepositoryException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.saving_error, e); Dialogs.showErrorDialog(requireContext(), R.string.saving_error, e);
return false; return false;
} }
return true; return true;
} }
@NonNull
protected <T extends Preference> T requirePreference(@NonNull CharSequence key) {
T pref = findPreference(key);
if (pref == null) {
throw new IllegalStateException(String.format("Preference %s not found", key));
}
return pref;
}
} }

View file

@ -55,16 +55,16 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
super.onCreatePreferences(savedInstanceState, rootKey); super.onCreatePreferences(savedInstanceState, rootKey);
addPreferencesFromResource(R.xml.preferences_security); addPreferencesFromResource(R.xml.preferences_security);
Preference tapToRevealPreference = findPreference("pref_tap_to_reveal"); Preference tapToRevealPreference = requirePreference("pref_tap_to_reveal");
tapToRevealPreference.setOnPreferenceChangeListener((preference, newValue) -> { tapToRevealPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true); getResult().putExtra("needsRefresh", true);
return true; return true;
}); });
Preference screenPreference = findPreference("pref_secure_screen"); Preference screenPreference = requirePreference("pref_secure_screen");
screenPreference.setOnPreferenceChangeListener((preference, newValue) -> { screenPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRecreate", true); getResult().putExtra("needsRecreate", true);
Window window = getActivity().getWindow(); Window window = requireActivity().getWindow();
if ((boolean) newValue) { if ((boolean) newValue) {
window.addFlags(WindowManager.LayoutParams.FLAG_SECURE); window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
} else { } else {
@ -73,10 +73,10 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
return true; return true;
}); });
Preference tapToRevealTimePreference = findPreference("pref_tap_to_reveal_time"); Preference tapToRevealTimePreference = requirePreference("pref_tap_to_reveal_time");
tapToRevealTimePreference.setSummary(_prefs.getTapToRevealTime() + " seconds"); tapToRevealTimePreference.setSummary(_prefs.getTapToRevealTime() + " seconds");
tapToRevealTimePreference.setOnPreferenceClickListener(preference -> { tapToRevealTimePreference.setOnPreferenceClickListener(preference -> {
Dialogs.showTapToRevealTimeoutPickerDialog(getActivity(), _prefs.getTapToRevealTime(), number -> { Dialogs.showTapToRevealTimeoutPickerDialog(requireActivity(), _prefs.getTapToRevealTime(), number -> {
_prefs.setTapToRevealTime(number); _prefs.setTapToRevealTime(number);
tapToRevealTimePreference.setSummary(number + " seconds"); tapToRevealTimePreference.setSummary(number + " seconds");
getResult().putExtra("needsRefresh", true); getResult().putExtra("needsRefresh", true);
@ -84,12 +84,12 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
return false; return false;
}); });
_encryptionPreference = findPreference("pref_encryption"); _encryptionPreference = requirePreference("pref_encryption");
_encryptionPreference.setOnPreferenceChangeListener((preference, newValue) -> { _encryptionPreference.setOnPreferenceChangeListener((preference, newValue) -> {
if (!_vaultManager.getVault().isEncryptionEnabled()) { if (!_vaultManager.getVault().isEncryptionEnabled()) {
Dialogs.showSetPasswordDialog(getActivity(), new EnableEncryptionListener()); Dialogs.showSetPasswordDialog(requireActivity(), new EnableEncryptionListener());
} else { } else {
Dialogs.showSecureDialog(new AlertDialog.Builder(getActivity()) Dialogs.showSecureDialog(new AlertDialog.Builder(requireContext())
.setTitle(R.string.disable_encryption) .setTitle(R.string.disable_encryption)
.setMessage(getText(R.string.disable_encryption_description)) .setMessage(getText(R.string.disable_encryption_description))
.setPositiveButton(android.R.string.yes, (dialog, which) -> { .setPositiveButton(android.R.string.yes, (dialog, which) -> {
@ -97,7 +97,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
_vaultManager.disableEncryption(); _vaultManager.disableEncryption();
} catch (VaultRepositoryException e) { } catch (VaultRepositoryException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.disable_encryption_error, e); Dialogs.showErrorDialog(requireContext(), R.string.disable_encryption_error, e);
return; return;
} }
@ -112,13 +112,13 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
return false; return false;
}); });
_biometricsPreference = findPreference("pref_biometrics"); _biometricsPreference = requirePreference("pref_biometrics");
_biometricsPreference.setOnPreferenceChangeListener((preference, newValue) -> { _biometricsPreference.setOnPreferenceChangeListener((preference, newValue) -> {
VaultFileCredentials creds = _vaultManager.getVault().getCredentials(); VaultFileCredentials creds = _vaultManager.getVault().getCredentials();
SlotList slots = creds.getSlots(); SlotList slots = creds.getSlots();
if (!slots.has(BiometricSlot.class)) { if (!slots.has(BiometricSlot.class)) {
if (BiometricsHelper.isAvailable(getContext())) { if (BiometricsHelper.isAvailable(requireContext())) {
BiometricSlotInitializer initializer = new BiometricSlotInitializer(SecurityPreferencesFragment.this, new RegisterBiometricsListener()); BiometricSlotInitializer initializer = new BiometricSlotInitializer(SecurityPreferencesFragment.this, new RegisterBiometricsListener());
BiometricPrompt.PromptInfo info = new BiometricPrompt.PromptInfo.Builder() BiometricPrompt.PromptInfo info = new BiometricPrompt.PromptInfo.Builder()
.setTitle(getString(R.string.set_up_biometric)) .setTitle(getString(R.string.set_up_biometric))
@ -147,27 +147,27 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
return false; return false;
}); });
_setPasswordPreference = findPreference("pref_password"); _setPasswordPreference = requirePreference("pref_password");
_setPasswordPreference.setOnPreferenceClickListener(preference -> { _setPasswordPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showSetPasswordDialog(getActivity(), new SetPasswordListener()); Dialogs.showSetPasswordDialog(requireActivity(), new SetPasswordListener());
return false; return false;
}); });
_pinKeyboardPreference = findPreference("pref_pin_keyboard"); _pinKeyboardPreference = requirePreference("pref_pin_keyboard");
_pinKeyboardPreference.setOnPreferenceChangeListener((preference, newValue) -> { _pinKeyboardPreference.setOnPreferenceChangeListener((preference, newValue) -> {
if (!(boolean) newValue) { if (!(boolean) newValue) {
return true; return true;
} }
Dialogs.showPasswordInputDialog(getActivity(), R.string.set_password_confirm, R.string.pin_keyboard_description, password -> { Dialogs.showPasswordInputDialog(requireContext(), R.string.set_password_confirm, R.string.pin_keyboard_description, password -> {
if (isDigitsOnly(new String(password))) { if (isDigitsOnly(new String(password))) {
List<PasswordSlot> slots = _vaultManager.getVault().getCredentials().getSlots().findAll(PasswordSlot.class); List<PasswordSlot> slots = _vaultManager.getVault().getCredentials().getSlots().findAll(PasswordSlot.class);
PasswordSlotDecryptTask.Params params = new PasswordSlotDecryptTask.Params(slots, password); PasswordSlotDecryptTask.Params params = new PasswordSlotDecryptTask.Params(slots, password);
PasswordSlotDecryptTask task = new PasswordSlotDecryptTask(getActivity(), new PasswordConfirmationListener()); PasswordSlotDecryptTask task = new PasswordSlotDecryptTask(requireContext(), new PasswordConfirmationListener());
task.execute(getLifecycle(), params); task.execute(getLifecycle(), params);
} else { } else {
_pinKeyboardPreference.setChecked(false); _pinKeyboardPreference.setChecked(false);
Dialogs.showSecureDialog(new AlertDialog.Builder(getActivity()) Dialogs.showSecureDialog(new AlertDialog.Builder(requireContext())
.setTitle(R.string.pin_keyboard_error) .setTitle(R.string.pin_keyboard_error)
.setMessage(R.string.pin_keyboard_error_description) .setMessage(R.string.pin_keyboard_error_description)
.setCancelable(false) .setCancelable(false)
@ -180,7 +180,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
return false; return false;
}); });
_autoLockPreference = findPreference("pref_auto_lock"); _autoLockPreference = requirePreference("pref_auto_lock");
_autoLockPreference.setSummary(getAutoLockSummary()); _autoLockPreference.setSummary(getAutoLockSummary());
_autoLockPreference.setOnPreferenceClickListener((preference) -> { _autoLockPreference.setOnPreferenceClickListener((preference) -> {
final int[] items = Preferences.AUTO_LOCK_SETTINGS; final int[] items = Preferences.AUTO_LOCK_SETTINGS;
@ -190,7 +190,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
checkedItems[i] = _prefs.isAutoLockTypeEnabled(items[i]); checkedItems[i] = _prefs.isAutoLockTypeEnabled(items[i]);
} }
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) AlertDialog.Builder builder = new AlertDialog.Builder(requireContext())
.setTitle(R.string.pref_auto_lock_prompt) .setTitle(R.string.pref_auto_lock_prompt)
.setMultiChoiceItems(textItems, checkedItems, (dialog, index, isChecked) -> checkedItems[index] = isChecked) .setMultiChoiceItems(textItems, checkedItems, (dialog, index, isChecked) -> checkedItems[index] = isChecked)
.setPositiveButton(android.R.string.ok, (dialog, which) -> { .setPositiveButton(android.R.string.ok, (dialog, which) -> {
@ -210,7 +210,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
return false; return false;
}); });
_passwordReminderPreference = findPreference("pref_password_reminder_freq"); _passwordReminderPreference = requirePreference("pref_password_reminder_freq");
_passwordReminderPreference.setSummary(getPasswordReminderSummary()); _passwordReminderPreference.setSummary(getPasswordReminderSummary());
_passwordReminderPreference.setOnPreferenceClickListener((preference) -> { _passwordReminderPreference.setOnPreferenceClickListener((preference) -> {
final PassReminderFreq currFreq = _prefs.getPasswordReminderFrequency(); final PassReminderFreq currFreq = _prefs.getPasswordReminderFrequency();
@ -219,7 +219,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
.map(f -> getString(f.getStringRes())) .map(f -> getString(f.getStringRes()))
.toArray(String[]::new); .toArray(String[]::new);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) AlertDialog.Builder builder = new AlertDialog.Builder(requireContext())
.setTitle(R.string.pref_password_reminder_title) .setTitle(R.string.pref_password_reminder_title)
.setSingleChoiceItems(textItems, currFreq.ordinal(), (dialog, which) -> { .setSingleChoiceItems(textItems, currFreq.ordinal(), (dialog, which) -> {
int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition(); int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
@ -246,7 +246,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
SlotList slots = _vaultManager.getVault().getCredentials().getSlots(); SlotList slots = _vaultManager.getVault().getCredentials().getSlots();
boolean multiPassword = slots.findAll(PasswordSlot.class).size() > 1; boolean multiPassword = slots.findAll(PasswordSlot.class).size() > 1;
boolean multiBio = slots.findAll(BiometricSlot.class).size() > 1; boolean multiBio = slots.findAll(BiometricSlot.class).size() > 1;
boolean canUseBio = BiometricsHelper.isAvailable(getContext()); boolean canUseBio = BiometricsHelper.isAvailable(requireContext());
_setPasswordPreference.setEnabled(!multiPassword); _setPasswordPreference.setEnabled(!multiPassword);
_biometricsPreference.setEnabled(canUseBio && !multiBio); _biometricsPreference.setEnabled(canUseBio && !multiBio);
_biometricsPreference.setChecked(slots.has(BiometricSlot.class), true); _biometricsPreference.setChecked(slots.has(BiometricSlot.class), true);
@ -319,7 +319,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
if (_prefs.isPinKeyboardEnabled()) { if (_prefs.isPinKeyboardEnabled()) {
_pinKeyboardPreference.setChecked(false); _pinKeyboardPreference.setChecked(false);
Toast.makeText(getContext(), R.string.pin_keyboard_disabled, Toast.LENGTH_SHORT).show(); Toast.makeText(requireContext(), R.string.pin_keyboard_disabled, Toast.LENGTH_SHORT).show();
} }
} }
@ -327,7 +327,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
public void onException(Exception e) { public void onException(Exception e) {
e.printStackTrace(); e.printStackTrace();
updateEncryptionPreferences(); updateEncryptionPreferences();
Dialogs.showErrorDialog(getContext(), R.string.encryption_set_password_error, e); Dialogs.showErrorDialog(requireContext(), R.string.encryption_set_password_error, e);
} }
} }
@ -352,7 +352,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
@Override @Override
public void onSlotInitializationFailed(int errorCode, @NonNull CharSequence errString) { public void onSlotInitializationFailed(int errorCode, @NonNull CharSequence errString) {
if (!BiometricsHelper.isCanceled(errorCode)) { if (!BiometricsHelper.isCanceled(errorCode)) {
Dialogs.showErrorDialog(getContext(), R.string.encryption_enable_biometrics_error, errString); Dialogs.showErrorDialog(requireContext(), R.string.encryption_enable_biometrics_error, errString);
} }
} }
} }
@ -378,7 +378,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
@Override @Override
public void onException(Exception e) { public void onException(Exception e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.encryption_set_password_error, e); Dialogs.showErrorDialog(requireContext(), R.string.encryption_set_password_error, e);
} }
} }
@ -388,7 +388,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
if (result != null) { if (result != null) {
_pinKeyboardPreference.setChecked(true); _pinKeyboardPreference.setChecked(true);
} else { } else {
Dialogs.showSecureDialog(new AlertDialog.Builder(getActivity()) Dialogs.showSecureDialog(new AlertDialog.Builder(requireActivity())
.setTitle(R.string.pin_keyboard_error) .setTitle(R.string.pin_keyboard_error)
.setMessage(R.string.invalid_password) .setMessage(R.string.invalid_password)
.setCancelable(false) .setCancelable(false)

View file

@ -46,7 +46,7 @@ public class SecurityPickerSlide extends SlideFragment {
* if the API version is new enough, permission is granted and a scanner is found. * if the API version is new enough, permission is granted and a scanner is found.
*/ */
private void updateBiometricsOption(boolean autoSelect) { private void updateBiometricsOption(boolean autoSelect) {
boolean canUseBio = BiometricsHelper.isAvailable(getContext()); boolean canUseBio = BiometricsHelper.isAvailable(requireContext());
_bioButton.setEnabled(canUseBio); _bioButton.setEnabled(canUseBio);
_bioText.setEnabled(canUseBio); _bioText.setEnabled(canUseBio);
@ -66,7 +66,7 @@ public class SecurityPickerSlide extends SlideFragment {
@Override @Override
public void onNotFinishedError() { public void onNotFinishedError() {
Toast.makeText(getContext(), R.string.snackbar_authentication_method, Toast.LENGTH_SHORT).show(); Toast.makeText(requireContext(), R.string.snackbar_authentication_method, Toast.LENGTH_SHORT).show();
} }
@Override @Override

View file

@ -84,7 +84,7 @@ public class SecuritySetupSlide extends SlideFragment {
Strength strength = _zxcvbn.measure(_textPassword.getText()); Strength strength = _zxcvbn.measure(_textPassword.getText());
_barPasswordStrength.setProgress(strength.getScore()); _barPasswordStrength.setProgress(strength.getScore());
_barPasswordStrength.setProgressTintList(ColorStateList.valueOf(Color.parseColor(PasswordStrengthHelper.getColor(strength.getScore())))); _barPasswordStrength.setProgressTintList(ColorStateList.valueOf(Color.parseColor(PasswordStrengthHelper.getColor(strength.getScore()))));
_textPasswordStrength.setText((_textPassword.getText().length() != 0) ? PasswordStrengthHelper.getString(strength.getScore(), getContext()) : ""); _textPasswordStrength.setText((_textPassword.getText().length() != 0) ? PasswordStrengthHelper.getString(strength.getScore(), requireContext()) : "");
_textPasswordWrapper.setError(strength.getFeedback().getWarning()); _textPasswordWrapper.setError(strength.getFeedback().getWarning());
strength.wipe(); strength.wipe();
} }
@ -125,7 +125,7 @@ public class SecuritySetupSlide extends SlideFragment {
private void deriveKey() { private void deriveKey() {
PasswordSlot slot = new PasswordSlot(); PasswordSlot slot = new PasswordSlot();
KeyDerivationTask.Params params = new KeyDerivationTask.Params(slot, EditTextHelper.getEditTextChars(_textPassword)); KeyDerivationTask.Params params = new KeyDerivationTask.Params(slot, EditTextHelper.getEditTextChars(_textPassword));
KeyDerivationTask task = new KeyDerivationTask(getContext(), new PasswordDerivationListener()); KeyDerivationTask task = new KeyDerivationTask(requireContext(), new PasswordDerivationListener());
task.execute(getLifecycle(), params); task.execute(getLifecycle(), params);
} }
@ -153,7 +153,7 @@ public class SecuritySetupSlide extends SlideFragment {
@Override @Override
public void onNotFinishedError() { public void onNotFinishedError() {
if (!EditTextHelper.areEditTextsEqual(_textPassword, _textPasswordConfirm)) { if (!EditTextHelper.areEditTextsEqual(_textPassword, _textPasswordConfirm)) {
Toast.makeText(getContext(), R.string.password_equality_error, Toast.LENGTH_SHORT).show(); Toast.makeText(requireContext(), R.string.password_equality_error, Toast.LENGTH_SHORT).show();
} else if (_cryptType != SecurityPickerSlide.CRYPT_TYPE_BIOMETRIC) { } else if (_cryptType != SecurityPickerSlide.CRYPT_TYPE_BIOMETRIC) {
deriveKey(); deriveKey();
} else if (!_creds.getSlots().has(BiometricSlot.class)) { } else if (!_creds.getSlots().has(BiometricSlot.class)) {
@ -175,7 +175,7 @@ public class SecuritySetupSlide extends SlideFragment {
_creds.getSlots().add(slot); _creds.getSlots().add(slot);
} catch (SlotException e) { } catch (SlotException e) {
e.printStackTrace(); e.printStackTrace();
Dialogs.showErrorDialog(getContext(), R.string.enable_encryption_error, e); Dialogs.showErrorDialog(requireContext(), R.string.enable_encryption_error, e);
return; return;
} }
@ -201,7 +201,7 @@ public class SecuritySetupSlide extends SlideFragment {
@Override @Override
public void onSlotInitializationFailed(int errorCode, @NonNull CharSequence errString) { public void onSlotInitializationFailed(int errorCode, @NonNull CharSequence errString) {
if (!BiometricsHelper.isCanceled(errorCode)) { if (!BiometricsHelper.isCanceled(errorCode)) {
Dialogs.showErrorDialog(getContext(), R.string.encryption_enable_biometrics_error, errString); Dialogs.showErrorDialog(requireContext(), R.string.encryption_enable_biometrics_error, errString);
} }
} }
} }

View file

@ -107,7 +107,7 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
RecyclerViewPreloader<VaultEntry> preloader = new RecyclerViewPreloader<>(Glide.with(this), modelProvider, _preloadSizeProvider, 10); RecyclerViewPreloader<VaultEntry> preloader = new RecyclerViewPreloader<>(Glide.with(this), modelProvider, _preloadSizeProvider, 10);
_recyclerView.addOnScrollListener(preloader); _recyclerView.addOnScrollListener(preloader);
LinearLayoutManager layoutManager = new LinearLayoutManager(view.getContext()); LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
_recyclerView.setLayoutManager(layoutManager); _recyclerView.setLayoutManager(layoutManager);
_touchCallback = new SimpleItemTouchHelperCallback(_adapter); _touchCallback = new SimpleItemTouchHelperCallback(_adapter);
_touchHelper = new ItemTouchHelper(_touchCallback); _touchHelper = new ItemTouchHelper(_touchCallback);
@ -115,7 +115,7 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
_recyclerView.setAdapter(_adapter); _recyclerView.setAdapter(_adapter);
int resId = R.anim.layout_animation_fall_down; int resId = R.anim.layout_animation_fall_down;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(getContext(), resId); LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(requireContext(), resId);
_recyclerView.setLayoutAnimation(animation); _recyclerView.setLayoutAnimation(animation);
_refresher = new UiRefresher(new UiRefresher.Listener() { _refresher = new UiRefresher(new UiRefresher.Listener() {
@ -376,9 +376,8 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
} }
public void runEntriesAnimation() { public void runEntriesAnimation() {
final Context context = _recyclerView.getContext();
final LayoutAnimationController controller = final LayoutAnimationController controller =
AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down); AnimationUtils.loadLayoutAnimation(requireContext(), R.anim.layout_animation_fall_down);
_recyclerView.setLayoutAnimation(controller); _recyclerView.setLayoutAnimation(controller);
_recyclerView.scheduleLayoutAnimation(); _recyclerView.scheduleLayoutAnimation();
@ -386,7 +385,7 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
private void initializeGroupChip() { private void initializeGroupChip() {
View view = getLayoutInflater().inflate(R.layout.dialog_select_groups, null); View view = getLayoutInflater().inflate(R.layout.dialog_select_groups, null);
BottomSheetDialog dialog = new BottomSheetDialog(getContext()); BottomSheetDialog dialog = new BottomSheetDialog(requireContext());
dialog.setContentView(view); dialog.setContentView(view);
ChipGroup chipGroup = view.findViewById(R.id.groupChipGroup); ChipGroup chipGroup = view.findViewById(R.id.groupChipGroup);
@ -479,8 +478,8 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
float height = _viewMode.getDividerHeight(); float height = _viewMode.getDividerHeight();
if (_showProgress && height == 0) { if (_showProgress && height == 0) {
DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL); DividerItemDecoration divider = new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL);
divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.entry_divider)); divider.setDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.entry_divider));
_dividerDecoration = divider; _dividerDecoration = divider;
} else { } else {
_dividerDecoration = new VerticalSpaceItemDecoration(height); _dividerDecoration = new VerticalSpaceItemDecoration(height);
@ -518,7 +517,7 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
private VerticalSpaceItemDecoration(float dp) { private VerticalSpaceItemDecoration(float dp) {
// convert dp to pixels // convert dp to pixels
_height = MetricsHelper.convertDpToPixels(getContext(), dp); _height = MetricsHelper.convertDpToPixels(requireContext(), dp);
} }
@Override @Override

View file

@ -316,7 +316,7 @@ public class VaultManager {
e.printStackTrace(); e.printStackTrace();
if (isDocsAction(intent.getAction())) { if (isDocsAction(intent.getAction())) {
Dialogs.showErrorDialog(fragment.getContext(), R.string.documentsui_error, e); Dialogs.showErrorDialog(fragment.requireContext(), R.string.documentsui_error, e);
} else { } else {
throw e; throw e;
} }