diff options
author | Harsh Shandilya <me@msfjarvis.dev> | 2020-04-21 13:11:27 +0530 |
---|---|---|
committer | Harsh Shandilya <me@msfjarvis.dev> | 2020-04-21 15:55:25 +0530 |
commit | d505151662da1c9a9d9ce5434db2a370d4167e36 (patch) | |
tree | e0a3fdafc56c07dba5980ae92b1a76477992f97b /app/src/main | |
parent | e1921b26e0fdc9d4fdb9df2f31278aba051edf0f (diff) |
treewide: use edit extension and cleanup some deprecation
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
Diffstat (limited to 'app/src/main')
12 files changed, 139 insertions, 138 deletions
diff --git a/app/src/main/java/com/zeapo/pwdstore/PasswordStore.kt b/app/src/main/java/com/zeapo/pwdstore/PasswordStore.kt index ce5300c1..ac41246d 100644 --- a/app/src/main/java/com/zeapo/pwdstore/PasswordStore.kt +++ b/app/src/main/java/com/zeapo/pwdstore/PasswordStore.kt @@ -29,6 +29,7 @@ import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView.OnQueryTextListener import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat +import androidx.core.content.edit import androidx.fragment.app.FragmentManager import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.observe @@ -325,7 +326,7 @@ class PasswordStore : AppCompatActivity() { check(localDir.mkdir()) { "Failed to create directory!" } createRepository(localDir) if (File(localDir.absolutePath + "/.gpg-id").createNewFile()) { - settings.edit().putBoolean("repository_initialized", true).apply() + settings.edit { putBoolean("repository_initialized", true) } } else { throw IllegalStateException("Failed to initialize repository state.") } @@ -383,7 +384,7 @@ class PasswordStore : AppCompatActivity() { // do not push the fragment if we already have it if (fragmentManager.findFragmentByTag("PasswordsList") == null || settings.getBoolean("repo_changed", false)) { - settings.edit().putBoolean("repo_changed", false).apply() + settings.edit { putBoolean("repo_changed", false) } plist = PasswordFragment() val args = Bundle() args.putString(REQUEST_ARG_PATH, getRepositoryDirectory(applicationContext).absolutePath) @@ -589,7 +590,7 @@ class PasswordStore : AppCompatActivity() { if (resultCode == Activity.RESULT_OK) { when (requestCode) { // if we get here with a RESULT_OK then it's probably OK :) - BaseGitActivity.REQUEST_CLONE -> settings.edit().putBoolean("repository_initialized", true).apply() + BaseGitActivity.REQUEST_CLONE -> settings.edit { putBoolean("repository_initialized", true) } // if went from decrypt->edit and user saved changes or HOTP counter was // incremented, we need to commitChange REQUEST_CODE_DECRYPT_AND_VERIFY -> { @@ -721,7 +722,7 @@ class PasswordStore : AppCompatActivity() { .setTitle(this.resources.getString(R.string.location_dialog_title)) .setMessage(this.resources.getString(R.string.location_dialog_text)) .setPositiveButton(this.resources.getString(R.string.location_hidden)) { _, _ -> - settings.edit().putBoolean("git_external", false).apply() + settings.edit { putBoolean("git_external", false) } when (operation) { NEW_REPO_BUTTON -> initializeRepositoryInfo() CLONE_REPO_BUTTON -> { @@ -732,7 +733,7 @@ class PasswordStore : AppCompatActivity() { } } .setNegativeButton(this.resources.getString(R.string.location_sdcard)) { _, _ -> - settings.edit().putBoolean("git_external", true).apply() + settings.edit { putBoolean("git_external", true) } val externalRepo = settings.getString("git_external_repo", null) if (externalRepo == null) { val intent = Intent(activity, UserPreference::class.java) diff --git a/app/src/main/java/com/zeapo/pwdstore/UserPreference.kt b/app/src/main/java/com/zeapo/pwdstore/UserPreference.kt index 5756d477..3e15ba4e 100644 --- a/app/src/main/java/com/zeapo/pwdstore/UserPreference.kt +++ b/app/src/main/java/com/zeapo/pwdstore/UserPreference.kt @@ -33,6 +33,7 @@ import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager import androidx.preference.SwitchPreferenceCompat +import com.github.ajalt.timberkt.d import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import com.zeapo.pwdstore.autofill.AutofillPreferenceActivity @@ -173,7 +174,7 @@ class UserPreference : AppCompatActivity() { viewSshKeyPreference?.onPreferenceClickListener = ClickListener { val df = ShowSshKeyFragment() - df.show(requireFragmentManager(), "public_key") + df.show(parentFragmentManager, "public_key") true } @@ -189,13 +190,13 @@ class UserPreference : AppCompatActivity() { } clearHotpIncrementPreference?.onPreferenceClickListener = ClickListener { - sharedPreferences.edit().putBoolean("hotp_remember_check", false).apply() + sharedPreferences.edit { putBoolean("hotp_remember_check", false) } it.isVisible = false true } openkeystoreIdPreference?.onPreferenceClickListener = ClickListener { - sharedPreferences.edit().putString("ssh_openkeystore_keyid", null).apply() + sharedPreferences.edit { putString("ssh_openkeystore_keyid", null) } it.isVisible = false true } @@ -224,7 +225,7 @@ class UserPreference : AppCompatActivity() { // TODO Handle the different cases of exceptions } - sharedPreferences.edit().putBoolean("repository_initialized", false).apply() + sharedPreferences.edit { putBoolean("repository_initialized", false) } dialogInterface.cancel() callingActivity.finish() } @@ -244,7 +245,7 @@ class UserPreference : AppCompatActivity() { val resetRepo = Preference.OnPreferenceChangeListener { _, o -> deleteRepoPreference?.isVisible = !(o as Boolean) PasswordRepository.closeRepository() - sharedPreferences.edit().putBoolean("repo_changed", true).apply() + sharedPreferences.edit { putBoolean("repo_changed", true) } true } @@ -294,30 +295,30 @@ class UserPreference : AppCompatActivity() { } else { setOnPreferenceClickListener { isEnabled = false - val editor = sharedPreferences.edit() - val checked = isChecked - Authenticator(requireActivity()) { result -> - when (result) { - is AuthenticationResult.Success -> { - // Apply the changes - editor.putBoolean("biometric_auth", checked) - isEnabled = true + sharedPreferences.edit { + val checked = isChecked + Authenticator(requireActivity()) { result -> + when (result) { + is AuthenticationResult.Success -> { + // Apply the changes + putBoolean("biometric_auth", checked) + isEnabled = true + } + else -> { + // If any error occurs, revert back to the previous state. This + // catch-all clause includes the cancellation case. + putBoolean("biometric_auth", !checked) + isChecked = !checked + isEnabled = true + } } - else -> { - // If any error occurs, revert back to the previous state. This - // catch-all clause includes the cancellation case. - editor.putBoolean("biometric_auth", !checked) - isChecked = !checked - isEnabled = true + }.authenticate() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { + requireContext().getSystemService<ShortcutManager>()?.apply { + removeDynamicShortcuts(dynamicShortcuts.map { it.id }.toMutableList()) } } - }.authenticate() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { - requireContext().getSystemService<ShortcutManager>()?.apply { - removeDynamicShortcuts(dynamicShortcuts.map { it.id }.toMutableList()) - } } - editor.apply() true } } @@ -622,7 +623,7 @@ class UserPreference : AppCompatActivity() { ).show() val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext) - prefs.edit().putBoolean("use_generated_key", false).apply() + prefs.edit { putBoolean("use_generated_key", false) } // Delete the public key from generation File("""$filesDir/.ssh_key.pub""").delete() @@ -642,33 +643,27 @@ class UserPreference : AppCompatActivity() { SELECT_GIT_DIRECTORY -> { val uri = data.data - Timber.tag(TAG).d("Selected repository URI is $uri") + Timber.tag(TAG).d { "Selected repository URI is $uri" } // TODO: This is fragile. Workaround until PasswordItem is backed by DocumentFile val docId = DocumentsContract.getTreeDocumentId(uri) val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val path = if (split.isNotEmpty()) split[1] else split[0] val repoPath = "${Environment.getExternalStorageDirectory()}/$path" + val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext) - Timber.tag(TAG).d("Selected repository path is $repoPath") + Timber.tag(TAG).d {"Selected repository path is $repoPath" } if (Environment.getExternalStorageDirectory().path == repoPath) { MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.sdcard_root_warning_title)) .setMessage(getString(R.string.sdcard_root_warning_message)) .setPositiveButton("Remove everything") { _, _ -> - PreferenceManager.getDefaultSharedPreferences(applicationContext) - .edit() - .putString("git_external_repo", uri?.path) - .apply() + prefs.edit { putString("git_external_repo", uri?.path) } } .setNegativeButton(R.string.dialog_cancel, null) .show() } - - PreferenceManager.getDefaultSharedPreferences(applicationContext) - .edit() - .putString("git_external_repo", repoPath) - .apply() + prefs.edit { putString("git_external_repo", repoPath) } } EXPORT_PASSWORDS -> { val uri = data.data @@ -691,7 +686,7 @@ class UserPreference : AppCompatActivity() { ).show() val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext) - prefs.edit().putString("pref_key_custom_dict", uri.toString()).apply() + prefs.edit { putString("pref_key_custom_dict", uri.toString()) } val customDictPref = prefsFragment.findPreference<Preference>("pref_key_custom_dict") setCustomDictSummary(customDictPref, uri) @@ -719,7 +714,7 @@ class UserPreference : AppCompatActivity() { val repositoryDirectory = requireNotNull(PasswordRepository.getRepositoryDirectory(applicationContext)) val sourcePassDir = DocumentFile.fromFile(repositoryDirectory) - Timber.tag(TAG).d("Copying ${repositoryDirectory.path} to $targetDirectory") + Timber.tag(TAG).d { "Copying ${repositoryDirectory.path} to $targetDirectory" } val dateString = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { LocalDateTime diff --git a/app/src/main/java/com/zeapo/pwdstore/autofill/AutofillActivity.kt b/app/src/main/java/com/zeapo/pwdstore/autofill/AutofillActivity.kt index c3186db5..bd22f4a4 100644 --- a/app/src/main/java/com/zeapo/pwdstore/autofill/AutofillActivity.kt +++ b/app/src/main/java/com/zeapo/pwdstore/autofill/AutofillActivity.kt @@ -11,10 +11,9 @@ import android.content.IntentSender import android.content.SharedPreferences import android.os.Bundle import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.edit import com.zeapo.pwdstore.PasswordStore import com.zeapo.pwdstore.utils.splitLines -import java.util.ArrayList -import java.util.Arrays import org.eclipse.jgit.util.StringUtils import timber.log.Timber @@ -71,17 +70,17 @@ class AutofillActivity : AppCompatActivity() { } else { applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE) } - val editor = prefs.edit() - when (val preference = prefs.getString(packageName, "")) { - "", "/first", "/never" -> editor.putString(packageName, path) - else -> { - val matches = ArrayList(Arrays.asList(*preference!!.trim { it <= ' ' }.splitLines())) - matches.add(path) - val paths = StringUtils.join(matches, "\n") - editor.putString(packageName, paths) + prefs.edit { + when (val preference = prefs.getString(packageName, "")) { + "", "/first", "/never" -> putString(packageName, path) + else -> { + val matches = arrayListOf(*preference!!.trim { it <= ' ' }.splitLines()) + matches.add(path) + val paths = StringUtils.join(matches, "\n") + putString(packageName, paths) + } } } - editor.apply() } } super.onActivityResult(requestCode, resultCode, data) diff --git a/app/src/main/java/com/zeapo/pwdstore/autofill/AutofillFragment.kt b/app/src/main/java/com/zeapo/pwdstore/autofill/AutofillFragment.kt index a2d82097..1f69413c 100644 --- a/app/src/main/java/com/zeapo/pwdstore/autofill/AutofillFragment.kt +++ b/app/src/main/java/com/zeapo/pwdstore/autofill/AutofillFragment.kt @@ -23,6 +23,7 @@ import android.widget.RadioGroup import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatTextView +import androidx.core.content.edit import androidx.fragment.app.DialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.zeapo.pwdstore.PasswordStore @@ -118,14 +119,14 @@ class AutofillFragment : DialogFragment() { // write to preferences when OK clicked builder.setPositiveButton(R.string.dialog_ok) { _, _ -> } builder.setNegativeButton(R.string.dialog_cancel, null) - val editor = prefs.edit() if (isWeb) { builder.setNeutralButton(R.string.autofill_apps_delete) { _, _ -> if (callingActivity.recyclerAdapter != null && packageName != null && packageName != "") { - editor.remove(packageName) - callingActivity.recyclerAdapter?.removeWebsite(packageName) - editor.apply() + prefs.edit { + remove(packageName) + callingActivity.recyclerAdapter?.removeWebsite(packageName) + } } } } @@ -148,7 +149,6 @@ class AutofillFragment : DialogFragment() { } else { callingActivity.applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE) } - val editor = prefs.edit() var packageName = args.getString("packageName", "") if (isWeb) { @@ -169,27 +169,28 @@ class AutofillFragment : DialogFragment() { } // write to preferences accordingly - val radioGroup = dialog.findViewById<RadioGroup>(R.id.autofill_radiogroup) - when (radioGroup.checkedRadioButtonId) { - R.id.use_default -> if (!isWeb) { - editor.remove(packageName) - } else { - editor.putString(packageName, "") - } - R.id.first -> editor.putString(packageName, "/first") - R.id.never -> editor.putString(packageName, "/never") - else -> { - val paths = StringBuilder() - for (i in 0 until adapter!!.count) { - paths.append(adapter!!.getItem(i)) - if (i != adapter!!.count) { - paths.append("\n") + prefs.edit { + val radioGroup = dialog.findViewById<RadioGroup>(R.id.autofill_radiogroup) + when (radioGroup.checkedRadioButtonId) { + R.id.use_default -> if (!isWeb) { + remove(packageName) + } else { + putString(packageName, "") + } + R.id.first -> putString(packageName, "/first") + R.id.never -> putString(packageName, "/never") + else -> { + val paths = StringBuilder() + for (i in 0 until adapter!!.count) { + paths.append(adapter!!.getItem(i)) + if (i != adapter!!.count) { + paths.append("\n") + } } + putString(packageName, paths.toString()) } - editor.putString(packageName, paths.toString()) } } - editor.apply() // notify the recycler adapter if it is loaded callingActivity.recyclerAdapter?.apply { @@ -204,7 +205,7 @@ class AutofillFragment : DialogFragment() { packageName -> notifyItemChanged(position) "" -> addWebsite(packageName) else -> { - editor.remove(oldPackageName) + prefs.edit { remove(oldPackageName) } updateWebsite(oldPackageName, packageName) } } diff --git a/app/src/main/java/com/zeapo/pwdstore/crypto/PgpActivity.kt b/app/src/main/java/com/zeapo/pwdstore/crypto/PgpActivity.kt index 63e916d7..612169a1 100644 --- a/app/src/main/java/com/zeapo/pwdstore/crypto/PgpActivity.kt +++ b/app/src/main/java/com/zeapo/pwdstore/crypto/PgpActivity.kt @@ -32,6 +32,7 @@ import android.widget.CheckBox import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout +import androidx.core.content.edit import androidx.core.widget.doOnTextChanged import androidx.lifecycle.lifecycleScope import androidx.localbroadcastmanager.content.LocalBroadcastManager @@ -228,7 +229,7 @@ class PgpActivity : AppCompatActivity(), OpenPgpServiceConnection.OnBound { } } - fun updateEncryptUsernameState() { + private fun updateEncryptUsernameState() { encrypt_username.apply { if (visibility != View.VISIBLE) return @@ -489,20 +490,20 @@ class PgpActivity : AppCompatActivity(), OpenPgpServiceConnection.OnBound { run { calculateAndCommitHotp(entry) if (rememberCheck.isChecked) { - val editor = settings.edit() - editor.putBoolean("hotp_remember_check", true) - editor.putBoolean("hotp_remember_choice", true) - editor.apply() + settings.edit { + putBoolean("hotp_remember_check", true) + putBoolean("hotp_remember_choice", true) + } } } } .setNegativeButton(R.string.dialog_update_negative) { _, _ -> run { calculateHotp(entry) - val editor = settings.edit() - editor.putBoolean("hotp_remember_check", true) - editor.putBoolean("hotp_remember_choice", false) - editor.apply() + settings.edit { + putBoolean("hotp_remember_check", true) + putBoolean("hotp_remember_choice", false) + } } } val updateDialog = dialogBuilder.create() @@ -722,7 +723,7 @@ class PgpActivity : AppCompatActivity(), OpenPgpServiceConnection.OnBound { val keys = ids.map { it.toString() }.toSet() // use Long - settings.edit().putStringSet("openpgp_key_ids_set", keys).apply() + settings.edit { putStringSet("openpgp_key_ids_set", keys) } showSnackbar("PGP keys selected") diff --git a/app/src/main/java/com/zeapo/pwdstore/git/GitConfigActivity.kt b/app/src/main/java/com/zeapo/pwdstore/git/GitConfigActivity.kt index 8a05ca40..8ad19618 100644 --- a/app/src/main/java/com/zeapo/pwdstore/git/GitConfigActivity.kt +++ b/app/src/main/java/com/zeapo/pwdstore/git/GitConfigActivity.kt @@ -6,6 +6,7 @@ package com.zeapo.pwdstore.git import android.os.Bundle import android.util.Patterns +import androidx.core.content.edit import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.zeapo.pwdstore.R import com.zeapo.pwdstore.databinding.ActivityGitConfigBinding @@ -50,12 +51,12 @@ class GitConfigActivity : BaseGitActivity() { .setPositiveButton(getString(R.string.dialog_ok), null) .show() } else { - val editor = settings.edit() - editor.putString("git_config_user_email", email) - editor.putString("git_config_user_name", name) - PasswordRepository.setUserName(name) - PasswordRepository.setUserEmail(email) - editor.apply() + settings.edit { + putString("git_config_user_email", email) + putString("git_config_user_name", name) + } + PasswordRepository.setUserName(name) + PasswordRepository.setUserEmail(email) } } } diff --git a/app/src/main/java/com/zeapo/pwdstore/git/GitOperation.kt b/app/src/main/java/com/zeapo/pwdstore/git/GitOperation.kt index e115c482..817d9dca 100644 --- a/app/src/main/java/com/zeapo/pwdstore/git/GitOperation.kt +++ b/app/src/main/java/com/zeapo/pwdstore/git/GitOperation.kt @@ -189,7 +189,7 @@ abstract class GitOperation(fileDir: File, internal val callingActivity: Activit // Authenticate using the ssh-key and then execute the command setAuthentication(sshKey, username, passphrase.text.toString()).execute() } else { - encryptedSettings.edit().putString("ssh_key_local_passphrase", null).apply() + encryptedSettings.edit { putString("ssh_key_local_passphrase", null) } // call back the method executeAfterAuthentication(connectionMode, username, sshKey, identity, true) } diff --git a/app/src/main/java/com/zeapo/pwdstore/pwgen/PasswordGenerator.kt b/app/src/main/java/com/zeapo/pwdstore/pwgen/PasswordGenerator.kt index de9e1e7b..9f7faa56 100644 --- a/app/src/main/java/com/zeapo/pwdstore/pwgen/PasswordGenerator.kt +++ b/app/src/main/java/com/zeapo/pwdstore/pwgen/PasswordGenerator.kt @@ -5,6 +5,7 @@ package com.zeapo.pwdstore.pwgen import android.content.Context +import androidx.core.content.edit import com.zeapo.pwdstore.R import java.util.ArrayList @@ -50,28 +51,26 @@ object PasswordGenerator { */ @JvmStatic fun setPrefs(ctx: Context, argv: ArrayList<String>, vararg numArgv: Int): Boolean { - val prefs = ctx.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE) - val editor = prefs.edit() - - for (option in pwOptions.toCharArray()) { - if (argv.contains(option.toString())) { - editor.putBoolean(option.toString(), true) - argv.remove(option.toString()) - } else { - editor.putBoolean(option.toString(), false) + ctx.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE).edit { + for (option in pwOptions.toCharArray()) { + if (argv.contains(option.toString())) { + putBoolean(option.toString(), true) + argv.remove(option.toString()) + } else { + putBoolean(option.toString(), false) + } } - } - var i = 0 - while (i < numArgv.size && i < 2) { - if (numArgv[i] <= 0) { - // Invalid password length or number of passwords - return false + var i = 0 + while (i < numArgv.size && i < 2) { + if (numArgv[i] <= 0) { + // Invalid password length or number of passwords + return false + } + val name = if (i == 0) "length" else "num" + putInt(name, numArgv[i]) + i++ } - val name = if (i == 0) "length" else "num" - editor.putInt(name, numArgv[i]) - i++ } - editor.apply() return true } @@ -84,7 +83,7 @@ object PasswordGenerator { * @return list of generated passwords */ @JvmStatic - @Throws(PasswordGenerator.PasswordGeneratorExeption::class) + @Throws(PasswordGeneratorExeption::class) fun generate(ctx: Context): ArrayList<String> { val prefs = ctx.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE) diff --git a/app/src/main/java/com/zeapo/pwdstore/sshkeygen/SshKeygenTask.kt b/app/src/main/java/com/zeapo/pwdstore/sshkeygen/SshKeygenTask.kt index 0f28f7b4..169a1309 100644 --- a/app/src/main/java/com/zeapo/pwdstore/sshkeygen/SshKeygenTask.kt +++ b/app/src/main/java/com/zeapo/pwdstore/sshkeygen/SshKeygenTask.kt @@ -8,6 +8,7 @@ import android.app.ProgressDialog import android.os.AsyncTask import android.widget.Toast import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.edit import androidx.fragment.app.DialogFragment import androidx.preference.PreferenceManager import com.google.android.material.dialog.MaterialAlertDialogBuilder @@ -60,9 +61,7 @@ class KeyGenerateTask(activity: AppCompatActivity) : AsyncTask<String?, Void?, E val df: DialogFragment = ShowSshKeyFragment() df.show(activity.supportFragmentManager, "public_key") val prefs = PreferenceManager.getDefaultSharedPreferences(weakReference.get()) - val editor = prefs.edit() - editor.putBoolean("use_generated_key", true) - editor.apply() + prefs.edit { putBoolean("use_generated_key", true) } } else { MaterialAlertDialogBuilder(activity) .setTitle(activity.getString(R.string.error_generate_ssh_key)) diff --git a/app/src/main/java/com/zeapo/pwdstore/ui/dialogs/XkPasswordGeneratorDialogFragment.kt b/app/src/main/java/com/zeapo/pwdstore/ui/dialogs/XkPasswordGeneratorDialogFragment.kt index f42b6536..dbf8e7a9 100644 --- a/app/src/main/java/com/zeapo/pwdstore/ui/dialogs/XkPasswordGeneratorDialogFragment.kt +++ b/app/src/main/java/com/zeapo/pwdstore/ui/dialogs/XkPasswordGeneratorDialogFragment.kt @@ -16,6 +16,7 @@ import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.AppCompatEditText import androidx.appcompat.widget.AppCompatTextView +import androidx.core.content.edit import androidx.fragment.app.DialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.zeapo.pwdstore.R @@ -48,17 +49,17 @@ class XkPasswordGeneratorDialogFragment : DialogFragment() { prefs = callingActivity.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE) - cbNumbers = view.findViewById<CheckBox>(R.id.xknumerals) + cbNumbers = view.findViewById(R.id.xknumerals) cbNumbers.isChecked = prefs.getBoolean(PREF_KEY_USE_NUMERALS, false) - spinnerNumbersCount = view.findViewById<Spinner>(R.id.xk_numbers_count) + spinnerNumbersCount = view.findViewById(R.id.xk_numbers_count) val storedNumbersCount = prefs.getInt(PREF_KEY_NUMBERS_COUNT, 0) spinnerNumbersCount.setSelection(storedNumbersCount) - cbSymbols = view.findViewById<CheckBox>(R.id.xksymbols) + cbSymbols = view.findViewById(R.id.xksymbols) cbSymbols.isChecked = prefs.getBoolean(PREF_KEY_USE_SYMBOLS, false) != false - spinnerSymbolsCount = view.findViewById<Spinner>(R.id.xk_symbols_count) + spinnerSymbolsCount = view.findViewById(R.id.xk_symbols_count) val symbolsCount = prefs.getInt(PREF_KEY_SYMBOLS_COUNT, 0) spinnerSymbolsCount.setSelection(symbolsCount) @@ -68,7 +69,7 @@ class XkPasswordGeneratorDialogFragment : DialogFragment() { Timber.tag("xkpw").e(e) DEFAULT_CAPS_STYLE } - spinnerCapsType = view.findViewById<Spinner>(R.id.xkCapType) + spinnerCapsType = view.findViewById(R.id.xkCapType) val lastCapitalsStyleIndex: Int @@ -80,10 +81,10 @@ class XkPasswordGeneratorDialogFragment : DialogFragment() { } spinnerCapsType.setSelection(lastCapitalsStyleIndex) - editNumWords = view.findViewById<AppCompatEditText>(R.id.xk_num_words) + editNumWords = view.findViewById(R.id.xk_num_words) editNumWords.setText(prefs.getString(PREF_KEY_NUM_WORDS, DEFAULT_NUMBER_OF_WORDS)) - editSeparator = view.findViewById<AppCompatEditText>(R.id.xk_separator) + editSeparator = view.findViewById(R.id.xk_separator) editSeparator.setText(prefs.getString(PREF_KEY_SEPARATOR, DEFAULT_WORD_SEPARATOR)) val passwordText: AppCompatTextView = view.findViewById(R.id.xkPasswordText) @@ -131,14 +132,15 @@ class XkPasswordGeneratorDialogFragment : DialogFragment() { } private fun setPreferences() { - prefs.edit().putBoolean(PREF_KEY_USE_NUMERALS, cbNumbers.isChecked) - .putBoolean(PREF_KEY_USE_SYMBOLS, cbSymbols.isChecked) - .putString(PREF_KEY_CAPITALS_STYLE, spinnerCapsType.selectedItem.toString()) - .putString(PREF_KEY_NUM_WORDS, editNumWords.text.toString()) - .putString(PREF_KEY_SEPARATOR, editSeparator.text.toString()) - .putInt(PREF_KEY_NUMBERS_COUNT, Integer.parseInt(spinnerNumbersCount.selectedItem as String) - 1) - .putInt(PREF_KEY_SYMBOLS_COUNT, Integer.parseInt(spinnerSymbolsCount.selectedItem as String) - 1) - .apply() + prefs.edit { + putBoolean(PREF_KEY_USE_NUMERALS, cbNumbers.isChecked) + putBoolean(PREF_KEY_USE_SYMBOLS, cbSymbols.isChecked) + putString(PREF_KEY_CAPITALS_STYLE, spinnerCapsType.selectedItem.toString()) + putString(PREF_KEY_NUM_WORDS, editNumWords.text.toString()) + putString(PREF_KEY_SEPARATOR, editSeparator.text.toString()) + putInt(PREF_KEY_NUMBERS_COUNT, Integer.parseInt(spinnerNumbersCount.selectedItem as String) - 1) + putInt(PREF_KEY_SYMBOLS_COUNT, Integer.parseInt(spinnerSymbolsCount.selectedItem as String) - 1) + } } companion object { diff --git a/app/src/main/java/com/zeapo/pwdstore/utils/Extensions.kt b/app/src/main/java/com/zeapo/pwdstore/utils/Extensions.kt index 6f4ebab1..5e987f22 100644 --- a/app/src/main/java/com/zeapo/pwdstore/utils/Extensions.kt +++ b/app/src/main/java/com/zeapo/pwdstore/utils/Extensions.kt @@ -65,4 +65,4 @@ fun <T : View> AlertDialog.requestInputFocusOnView(@IdRes id: Int) { val Context.autofillManager: AutofillManager? @RequiresApi(Build.VERSION_CODES.O) - get() = getSystemService(AutofillManager::class.java) + get() = getSystemService() diff --git a/app/src/main/java/com/zeapo/pwdstore/utils/PasswordRepository.kt b/app/src/main/java/com/zeapo/pwdstore/utils/PasswordRepository.kt index 2cc19ae3..bfe101a5 100644 --- a/app/src/main/java/com/zeapo/pwdstore/utils/PasswordRepository.kt +++ b/app/src/main/java/com/zeapo/pwdstore/utils/PasswordRepository.kt @@ -6,6 +6,7 @@ package com.zeapo.pwdstore.utils import android.content.Context import android.content.SharedPreferences +import androidx.core.content.edit import androidx.preference.PreferenceManager import java.io.File import java.io.FileFilter @@ -170,10 +171,12 @@ open class PasswordRepository protected constructor() { } val dir = getRepositoryDirectory(context) // uninitialize the repo if the dir does not exist or is absolutely empty - if (!dir.exists() || !dir.isDirectory || dir.listFiles()!!.isEmpty()) { - settings.edit().putBoolean("repository_initialized", false).apply() - } else { - settings.edit().putBoolean("repository_initialized", true).apply() + settings.edit { + if (!dir.exists() || !dir.isDirectory || dir.listFiles()!!.isEmpty()) { + putBoolean("repository_initialized", false) + } else { + putBoolean("repository_initialized", true) + } } // create the repository static variable in PasswordRepository |