0
0
mirror of https://github.com/ankidroid/Anki-Android.git synced 2024-09-19 19:42:17 +02:00

[Clean up]: Fix Android studio warnings (#14521)

* [Clean up]: Fix Android studio warnings

* [Clean up]: Fix Kdoc issues
This commit is contained in:
Ruben Quadros 2023-10-11 21:32:33 +05:30 committed by GitHub
parent d2077c7597
commit cca7bfac95
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 88 additions and 79 deletions

View File

@ -26,10 +26,10 @@ fun DeckPicker.handleDatabaseCheck() {
if (progress.hasDatabaseCheck()) {
progress.databaseCheck.let {
text = it.stage
if (it.stageTotal > 0) {
amount = Pair(it.stageCurrent, it.stageTotal)
amount = if (it.stageTotal > 0) {
Pair(it.stageCurrent, it.stageTotal)
} else {
amount = null
null
}
}
}

View File

@ -90,8 +90,6 @@ abstract class Onboarding<Feature>(
* Contains the logic for iterating through various tutorials of a screen and displaying the first one
* in the list which is not visited yet and condition (if any) also holds true for it.
*
* @param mContext Context of the Activity
* @param mTutorials List of tutorials for the Activity
*/
fun onCreate() {
tutorials.forEach {

View File

@ -289,7 +289,7 @@ class StudyOptionsFragment : Fragment(), Toolbar.OnMenuItemClickListener {
}
}
suspend fun rebuildCram() {
private suspend fun rebuildCram() {
val result = requireActivity().withProgress(resources.getString(R.string.rebuild_filtered_deck)) {
withCol {
Timber.d("doInBackground - RebuildCram")
@ -312,7 +312,7 @@ class StudyOptionsFragment : Fragment(), Toolbar.OnMenuItemClickListener {
rebuildUi(result, true)
}
fun configureToolbar() {
private fun configureToolbar() {
configureToolbarInternal(true)
}
@ -389,7 +389,7 @@ class StudyOptionsFragment : Fragment(), Toolbar.OnMenuItemClickListener {
}
}
var onRequestReviewActivityResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
private var onRequestReviewActivityResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
Timber.i("StudyOptionsFragment::mOnRequestReviewActivityResult")
Timber.d("Handling onActivityResult for StudyOptionsFragment (openReview, resultCode = %d)", result.resultCode)
if (mToolbar != null) {
@ -443,13 +443,14 @@ class StudyOptionsFragment : Fragment(), Toolbar.OnMenuItemClickListener {
}
}
private var updateValuesFromDeckJob: Job? = null
/**
* Rebuild the fragment's interface to reflect the status of the currently selected deck.
*
* @param resetDecklist Indicates whether to call back to the parent activity in order to
* also refresh the deck list.
*/
private var updateValuesFromDeckJob: Job? = null
fun refreshInterface(resetDecklist: Boolean = false) {
Timber.d("Refreshing StudyOptionsFragment")
updateValuesFromDeckJob?.cancel()

View File

@ -71,7 +71,7 @@ object UsageAnalytics {
AndroidDefaultRequest()
.setAndroidRequestParameters(context)
.applicationName(context.getString(R.string.app_name))
.applicationVersion(Integer.toString(BuildConfig.VERSION_CODE))
.applicationVersion(BuildConfig.VERSION_CODE.toString())
.applicationId(BuildConfig.APPLICATION_ID)
.trackingId(getAnalyticsTag(context))
.clientId(Installation.id(context))

View File

@ -127,7 +127,7 @@ open class OnRenderProcessGoneDelegate(val target: AbstractFlashcardViewer) {
@TargetApi(Build.VERSION_CODES.O)
protected open fun displayRenderLoopDialog(currentCardId: CardId, detail: RenderProcessGoneDetail) {
val cardInformation = java.lang.Long.toString(currentCardId)
val cardInformation = currentCardId.toString()
val res = target.resources
val errorDetails = if (detail.didCrash()) res.getString(R.string.webview_crash_unknwon_detailed) else res.getString(R.string.webview_crash_oom_details)
AlertDialog.Builder(target).show {

View File

@ -18,7 +18,6 @@ package com.ichi2.anki.dialogs.tags
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentResultListener
import com.ichi2.utils.KotlinCleanup
import java.util.ArrayList
@ -31,21 +30,22 @@ interface TagsDialogListener {
* @param indeterminateTags a list of tags which can checked or unchecked, should be ignored if not expected
* determining if tags in this list is checked or not is done by looking at the list of
* previous tags. if the tag is found in both previous and indeterminate, it should be kept
* otherwise it should be removed @see [TagsUtil.getUpdatedTags]
* otherwise it should be removed @see [com.ichi2.utils.TagsUtil.getUpdatedTags]
* @param option selection radio option, should be ignored if not expected
*/
fun onSelectedTags(selectedTags: List<String>, indeterminateTags: List<String>, option: Int)
fun <F> F.registerFragmentResultReceiver() where F : Fragment, F : TagsDialogListener {
parentFragmentManager.setFragmentResultListener(
ON_SELECTED_TAGS_KEY,
this,
FragmentResultListener { _: String?, bundle: Bundle ->
val selectedTags: List<String> = bundle.getStringArrayList(ON_SELECTED_TAGS__SELECTED_TAGS)!!
val indeterminateTags: List<String> = bundle.getStringArrayList(ON_SELECTED_TAGS__INDETERMINATE_TAGS)!!
val option = bundle.getInt(ON_SELECTED_TAGS__OPTION)
onSelectedTags(selectedTags, indeterminateTags, option)
}
)
this
) { _: String?, bundle: Bundle ->
val selectedTags: List<String> =
bundle.getStringArrayList(ON_SELECTED_TAGS__SELECTED_TAGS)!!
val indeterminateTags: List<String> =
bundle.getStringArrayList(ON_SELECTED_TAGS__INDETERMINATE_TAGS)!!
val option = bundle.getInt(ON_SELECTED_TAGS__OPTION)
onSelectedTags(selectedTags, indeterminateTags, option)
}
}
companion object {

View File

@ -39,7 +39,7 @@ class Directory private constructor(val directory: File) {
* @return Whether the directory has file.
* @throws [SecurityException] If a security manager exists and its SecurityManager.checkRead(String)
* method denies read access to the directory
* @throws [FileNotFoundException] if the file do not exists
* @throws [java.io.FileNotFoundException] if the file do not exists
* @throws [NotDirectoryException] if the file could not otherwise be opened because it is not
* a directory (optional specific exception), (starting at API 26)
* @throws [IOException] if an I/O error occurs.

View File

@ -31,7 +31,7 @@ class CustomToolbarButton(var index: Int, var buttonText: ButtonText, val prefix
companion object {
const val KEEP_EMPTY_ENTRIES = -1
fun fromString(s: String?): CustomToolbarButton? {
if (s == null || s.isEmpty()) {
if (s.isNullOrEmpty()) {
return null
}
val fields = s.split(Consts.FIELD_SEPARATOR.toRegex(), KEEP_EMPTY_ENTRIES.coerceAtLeast(0)).toTypedArray()

View File

@ -61,11 +61,7 @@ class SyncSettingsFragment : SettingsFragment() {
val preferences = requireContext().sharedPrefs()
val url = customSyncBase(preferences)
if (url == null) {
getString(R.string.custom_sync_server_summary_none_of_the_two_servers_used)
} else {
url
}
url ?: getString(R.string.custom_sync_server_summary_none_of_the_two_servers_used)
}
}

View File

@ -29,7 +29,7 @@ class ActionButtonStatus(private val reviewerUi: ReviewerUi) {
/**
* Custom button allocation
*/
protected val mCustomButtons: MutableMap<Int, Int> = hashMapInit(25) // setup's size
private val mCustomButtons: MutableMap<Int, Int> = hashMapInit(25) // setup's size
fun setup(preferences: SharedPreferences) {
// NOTE: the default values below should be in sync with preferences_custom_buttons.xml and reviewer.xml
@ -57,7 +57,10 @@ class ActionButtonStatus(private val reviewerUi: ReviewerUi) {
}
private fun setupButton(preferences: SharedPreferences, @IdRes resourceId: Int, preferenceName: String, showAsActionType: Int) {
mCustomButtons[resourceId] = preferences.getString(preferenceName, Integer.toString(showAsActionType))!!.toInt()
mCustomButtons[resourceId] = preferences.getString(
preferenceName,
showAsActionType.toString()
)!!.toInt()
}
fun setCustomButtons(menu: Menu) {

View File

@ -48,7 +48,6 @@ class PreviousAnswerIndicator(private val chosenAnswerText: TextView) {
* in SchedV1, button 2 could be hard or good
*
* @param ease The ordinal of the button answered
* @param buttonCount The number of buttons
*/
fun displayAnswerIndicator(ease: Int) {
when (ease) {

View File

@ -26,7 +26,7 @@ import org.acra.util.Installation
object DebugInfoService {
fun getDebugInfo(info: Context): String {
var dbV2Enabled = true
val dbV2Enabled = true
val webviewUserAgent = getWebviewUserAgent(info)
return """
AnkiDroid Version = $pkgVersionName (${BuildConfig.GIT_COMMIT_HASH})

View File

@ -85,7 +85,7 @@ class BootService : BroadcastReceiver() {
// Don't schedule a notification if the due reminders setting is not enabled
if (sp.getString(
Preferences.MINIMUM_CARDS_DUE_FOR_NOTIFICATION,
Integer.toString(Preferences.PENDING_NOTIFICATIONS_ONLY)
Preferences.PENDING_NOTIFICATIONS_ONLY.toString()
)!!.toInt() >= Preferences.PENDING_NOTIFICATIONS_ONLY
) {
return
@ -112,7 +112,7 @@ class BootService : BroadcastReceiver() {
}
/** Returns the hour of day when rollover to the next day occurs */
protected fun getRolloverHourOfDay(context: Context): Int {
private fun getRolloverHourOfDay(context: Context): Int {
// TODO; We might want to use the BootService retry code here when called from preferences.
val defValue = 4
return try {

View File

@ -43,7 +43,7 @@ class NotificationService : BroadcastReceiver() {
val preferences = context.sharedPrefs()
val minCardsDue = preferences.getString(
Preferences.MINIMUM_CARDS_DUE_FOR_NOTIFICATION,
Integer.toString(Preferences.PENDING_NOTIFICATIONS_ONLY)
Preferences.PENDING_NOTIFICATIONS_ONLY.toString()
)!!.toInt()
val dueCardsCount = WidgetStatus.fetchDue(context)
if (dueCardsCount >= minCardsDue) {

View File

@ -27,7 +27,7 @@ open class CompatV31 : CompatV29(), Compat {
override fun vibrate(context: Context, durationMillis: Long) {
val vibratorManager = context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
val effect = VibrationEffect.createOneShot(durationMillis, VibrationEffect.DEFAULT_AMPLITUDE)
val vibrator = vibratorManager.getDefaultVibrator()
val vibrator = vibratorManager.defaultVibrator
vibrator.vibrate(effect)
}

View File

@ -219,7 +219,6 @@ class Sound(private val soundPlayer: SoundPlayer, private val soundDir: String)
* expandSounds takes content with embedded sound file placeholders and expands them to reference the actual media
* file
*
* @param soundDir -- the base path of the media files
* @param content -- card content to be rendered that may contain embedded audio
* @return -- the same content but in a format that will render working play buttons when audio was embedded
*/

View File

@ -46,7 +46,7 @@ data class DeckNode(
* part that does not belong to its parents. E.g. for deck
* "A::B::C", returns "C".
*/
val lastDeckNameComponent = node.name
val lastDeckNameComponent: String = node.name
/**
* @return The depth of a deck. Top level decks have depth 0,

View File

@ -49,7 +49,15 @@ class OnGestureListener(
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
val dx = e2.x - e1.x
val dy = e2.y - e1.y
val gesture = gestureMapper.gesture(dx, dy, velocityX, velocityY, false, false, false)
val gesture = gestureMapper.gesture(
dx,
dy,
velocityX,
velocityY,
isSelecting = false,
isXScrolling = false,
isYScrolling = false
)
if (gesture != null) {
consumer.accept(gesture)
}

View File

@ -49,8 +49,7 @@ object AssetHelper {
* @return MIME type guessed from file extension or "text/plain".
*/
fun guessMimeType(path: String?): String {
val extension = MimeTypeMap.getFileExtensionFromUrl(path)
return when (extension) {
return when (val extension = MimeTypeMap.getFileExtensionFromUrl(path)) {
"js" -> "text/javascript"
"mjs" -> "text/javascript"
"json" -> "application/json"

View File

@ -28,9 +28,12 @@ import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.lang.Exception
import kotlin.math.ln
import kotlin.math.pow
import kotlin.math.roundToInt
object BitmapUtil {
fun decodeFile(theFile: File, IMAGE_MAX_SIZE: Int): Bitmap? {
fun decodeFile(theFile: File, imageMaxSize: Int): Bitmap? {
var bmp: Bitmap? = null
try {
if (!theFile.exists()) {
@ -48,13 +51,12 @@ object BitmapUtil {
fis?.close()
}
var scale = 1
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = Math.pow(
2.0,
Math.round(
Math.log(IMAGE_MAX_SIZE / Math.max(o.outHeight, o.outWidth).toDouble()) /
Math.log(0.5)
).toDouble()
if (o.outHeight > imageMaxSize || o.outWidth > imageMaxSize) {
scale = 2.0.pow(
(
ln(imageMaxSize / o.outHeight.coerceAtLeast(o.outWidth).toDouble()) /
ln(0.5)
).roundToInt().toDouble()
).toInt()
}

View File

@ -23,13 +23,13 @@ class DeckNameComparator : Comparator<String> {
override fun compare(lhs: String, rhs: String): Int {
val o1 = Decks.path(lhs)
val o2 = Decks.path(rhs)
for (i in 0 until Math.min(o1.size, o2.size)) {
for (i in 0 until o1.size.coerceAtMost(o2.size)) {
val result = o1[i].compareTo(o2[i], ignoreCase = true)
if (result != 0) {
return result
}
}
return Integer.compare(o1.size, o2.size)
return o1.size.compareTo(o2.size)
}
companion object {

View File

@ -27,18 +27,22 @@ import java.io.File
import java.lang.Exception
object ExifUtil {
fun rotateFromCamera(theFile: File, _bmp: Bitmap): Bitmap {
var bmp = _bmp
fun rotateFromCamera(theFile: File, bitmap: Bitmap): Bitmap {
var bmp = bitmap
return try {
val exif = ExifInterface(theFile.path)
val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
var angle = 0
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270
when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> {
angle = 90
}
ExifInterface.ORIENTATION_ROTATE_180 -> {
angle = 180
}
ExifInterface.ORIENTATION_ROTATE_270 -> {
angle = 270
}
}
val mat = Matrix()
mat.postRotate(angle.toFloat())

View File

@ -24,7 +24,7 @@ object HashUtil {
* @return Initial capacity for the hash structure. Copied from HashMap code
*/
private fun capacity(size: Int): Int {
return Math.max((size / .75f).toInt() + 1, 16)
return ((size / .75f).toInt() + 1).coerceAtLeast(16)
}
fun <T> hashSetInit(size: Int): HashSet<T> {

View File

@ -194,7 +194,7 @@ object ImportUtils {
var colpkgCount = 0
for (data in dataList) {
var fileName = getFileNameFromContentProvider(context, data)
val fileName = getFileNameFromContentProvider(context, data)
when {
isDeckPackage(fileName) -> {
apkgCount += 1
@ -282,17 +282,13 @@ object ImportUtils {
*/
protected open fun copyFileToCache(context: Context, data: Uri?, tempPath: String): Boolean {
// Get an input stream to the data in ContentProvider
val inputStream: InputStream? = try {
val inputStream: InputStream = try {
context.contentResolver.openInputStream(data!!)
} catch (e: FileNotFoundException) {
Timber.e(e, "Could not open input stream to intent data")
return false
}
} ?: return false
// Check non-null
@Suppress("FoldInitializerAndIfToElvis")
if (inputStream == null) {
return false
}
try {
CompatHelper.compat.copyFile(inputStream, tempPath)
} catch (e: IOException) {

View File

@ -34,7 +34,6 @@ fun MaterialDialog.contentNullable(message: CharSequence?): MaterialDialog {
* Method to display keyboard when dialog is shown.
*
* @param editText EditText present in the dialog.
* @param materialDialog Dialog which contains the EditText and needs the keyboard to be displayed.
*/
fun MaterialDialog.displayKeyboard(editText: EditText) {
AndroidUiUtils.setFocusAndOpenKeyboard(editText, window!!)

View File

@ -78,19 +78,24 @@ object NoteFieldDecorator {
}
private fun huevoRevuelto(huevo: String?): String? {
if (huevo == null || huevo.length == 0) {
if (huevo.isNullOrEmpty()) {
return huevo
}
val revuelto = StringBuilder()
for (i in 0 until huevo.length) {
var c = huevo[i]
if (c >= 'a' && c <= 'm') {
c += 13.toChar().code
} else if (c >= 'A' && c <= 'M') {
c += 13.toChar().code
} else if (c >= 'n' && c <= 'z') {
c -= 13.toChar().code
} else if (c >= 'N' && c <= 'Z') c -= 13.toChar().code
for (element in huevo) {
var c = element
when (c) {
in 'a'..'m' -> {
c += 13.toChar().code
}
in 'A'..'M' -> {
c += 13.toChar().code
}
in 'n'..'z' -> {
c -= 13.toChar().code
}
in 'N'..'Z' -> c -= 13.toChar().code
}
revuelto.append(c)
}
return revuelto.toString()

View File

@ -46,7 +46,7 @@ internal object Utils {
}
fun joinTags(tags: Set<String?>?): String {
if (tags == null || tags.isEmpty()) {
if (tags.isNullOrEmpty()) {
return ""
}
for (t in tags) {