Skip to content Skip to sidebar Skip to footer

Is There A Way Around Doing 2000 Else If Statements In This?

I am creating a check in barcode app for my business in Android Studio. There are 2000 of these. A member types in their 6 digit membership number into editText, clicks Save, which

Solution 1:

You can write a function to retrieve a drawable's Int ID (the R.drawable.whatever values) using reflection.

funfindDrawableIdByName(name: String): Int? {
    returntry {
        R.drawable::class.java.getField(name).getInt(null)
    } catch (e: NoSuchFieldException){
        null
    }
}

Then assuming your message values are in a consecutive range, you could combine them all into one else block.

funsaveToMain(view: View) {
    val editText = findViewById<EditText>(R.id.editText)
    val message = editText.text.toString()
    val image2 = findViewById<View>(R.id.imageView2)

    if (message == "") {
        alertDiag() 
    } elseif (message.toIntOrNull() in100001..102000) {
        val name = message.replaceRange(0, 2, "a") // replace the beginning 10 with "a"val drawableId = findDrawableIdByName(name)
        if (drawableId == null) {
            image2.setBackgroundResource(R.drawable.notfound)
        } else {
            image2.setBackgroundResource(drawableId)
            saveToStorage(view)
            goToGallery(view)
        }
    } else {
        image2.setBackgroundResource(R.drawable.notfound)
    }
}

Post a Comment for "Is There A Way Around Doing 2000 Else If Statements In This?"