android – view binding isn’t working on Button setOnClickListner… [*ERROR = Variable ‘getOTPButton’ is never used] (KOTLIN)

Code for the Activity:

class RegisterSelection : AppCompatActivity() {

     private lateinit var binding: ActivityRegisterSelectionBinding
     private lateinit var database: DatabaseReference

     @SuppressLint("SetTextI18n")
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         binding = ActivityRegisterSelectionBinding.inflate(layoutInflater)
         setContentView(binding.root)
         setContentView(R.layout.activity_register_selection)


         val checkPasswordTwo = findViewById<CheckBox>(R.id.checkPasswordTwo)
         val passwordText = findViewById<EditText>(R.id.passwordText)
         val confirmPassText = findViewById<EditText>(R.id.confirmPassText)
         val fullName=findViewById<EditText>(R.id.fullName).text.toString()
         val phoneNumberEdit=findViewById<EditText>(R.id.phoneNumberEdit).text.toString()
         val getOTPButton = findViewById<Button>(R.id.getOTPButton)

         binding.getOTPButton.setOnClickListener {

             if(fullName.isEmpty() && phoneNumberEdit.isEmpty()){
                 Toast.makeText(applicationContext,"Fill all the Fields!",Toast.LENGTH_LONG).show()
             }
             else{
                 database = FirebaseDatabase.getInstance().getReference("UserDataClass")
                 val users = UserDataClass(fullName, phoneNumberEdit)
                 database.child(fullName).setValue(users).addOnSuccessListener {
                     binding.fullName.text.clear()
                     binding.phoneNumberEdit.text.clear()

                     Toast.makeText(applicationContext,"Success!",Toast.LENGTH_SHORT).show()
                 }.addOnFailureListener {
                     Toast.makeText(applicationContext,"Failed to Save!",Toast.LENGTH_SHORT).show()
                 }
                 val intent = Intent(this, getOTP::class.java)
                 startActivity(intent)

             }
         }

         checkPasswordTwo.setOnClickListener {
             if (checkPasswordTwo.text.toString() == "Show Password"){
                 passwordText.transformationMethod = HideReturnsTransformationMethod.getInstance()
                 confirmPassText.transformationMethod = HideReturnsTransformationMethod.getInstance()
                 checkPasswordTwo.text = "Hide Password"
             } else{
                 passwordText.transformationMethod = PasswordTransformationMethod.getInstance()
                 confirmPassText.transformationMethod = PasswordTransformationMethod.getInstance()
                 checkPasswordTwo.text = "Show Password"
             }
         }

     }

 }

android – ¿Cómo puedo programar notificaciones locales con Kotlin desde variables?

buenas tardes.
Feliz domingo a todos.

Me estoy iniciando en la programación de apps para Android con kotlin y me gustaría poder programar notificaciones locales pero en vez de usar un DatePickerDialog y TimePickerDialog quisiera programarlas desde dos variables en las que tengo guardadas la fecha y la hora, estas variables están en String.

Encontré este tutorial pero lo hacen desde los pickers para la fecha y el horario

Código: https://github.com/sriharsha1507/set_repetitive_exact_alarm

¿Conocen algún tutorial o material en el que expliquen como se pueden programar las notificaciones desde variables y no desde los pickers?

Ojalá puedan ayudarme.
Saludos

android studio – Menu lateral en Kotlin no funciona (onNavigationItemSelected)

muy buenas, queria comentar mi problema, me compre una plantilla base, la cual tiene un menu lateral, pero no tenia ningun boton del mismo (el configurado en el xml) configurado en la parte de kotlin, luego de varias investigando encontre como poder añadir la funcion, pero no logre hacerlo funcionar, este es mi codigo:
en onCreate:

binding.drawerLayout.addDrawerListener(actionBarDrawerToggle);
binding.navView.setNavigationItemSelectedListener(this)
actionBarDrawerToggle.syncState()

fuera:

private fun closeDrawer() {
    binding.drawerLayout.closeDrawer(GravityCompat.START)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id = item.itemId
    return super.onOptionsItemSelected(item)

}

override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
    closeDrawer()
        when (menuItem.getItemId()) {
            R.id.ic_instagram -> {
                val intent = Intent("android.intent.action.VIEW",
                    Uri.parse("https://www.instagram.com/"))
                val b = Bundle()
                b.putBoolean("new_window", true) //sets new window
                intent.putExtras(b)
                startActivity(intent)
                true
            }
            else -> false

        }

    return true
}  

Me gustaria saber en que estoy fallando, porque al hacer click en el id ic_instagram por ejemplo, no cumple ninguna funcion y solo cierra el menu.

java – Nome da variável em looping -> Kotlin [AJUDA]

poderiam me ajudar com a seguinte dúvida?

Preciso exibir o nome da variável na qual contém o valor que está dentro do range… no caso o nome da variável ‘valor2’.

Existe uma maneira de conseguir buscar o nome dessa variável para exibição ao invés do valor contido nela?

Exibir qual é a variável que está no range.

fun verificaRange(valor1: Int, valor2: Int, valor3: Int){
    var valores = intArrayOf(valor1, valor2, valor3)
    for (valor in valores){
        if (valor in 100..1000){ // Verificar se alguma delas é maior do que 1000 ou menor do que 100...
            println("A ${::valores(valor).name} está no range!")} // Tentei algo assim, mas sem sucesso!
        else{
            println("Nenhuma outra variável está dentro do range.")
        }
    }
}

fun main(){
    var valor1: Int = 99
    var valor2: Int = 100
    var valor3: Int = 10001
    verificaRange(valor1, valor2, valor3)
}

Aceito sugestões, quem poder ajudar agradeço. 🙂

kotlin – Factory method with repeated constructor parameters in implementations

I’m developing the Factory method pattern, and I’m wondering if this is the best course of action.

Basically, the method is this:

class CommandFactory(private val discord: Kord) {
    fun called(message: Message) =
        when (message.message.substringBefore(' ')) {
            "welp" -> WelpCommand()
            "notify" -> NotifyCommand()
            else -> null
        }
}

But the discord param is being repeated throughout Command and its implementations, with a lot of clutter:

abstract class Command(private val discord: Kord) {
    abstract fun handleMessage(message: Message)
}

class WelpCommand(private val discord: Kord) : Command(discord) {
    override fun handleMessage(message: Message) {
        println("WELP!")
    }
}

Placing it in the handleMessage method isn’t an option, since I plan to make use of it in future ones.

android studio – Cómo puedo trabajar un date picker con room database y kotlin?

verán más que código estoy buscando que me ayuden a resolver la duda de cómo puedo implementar un datepicker en un edittext que funcione con room y como debo definir este dato, es decir si es un string, int, long etc. Ya he implementado varios datepicker pero todos ellos me crashean la app y en última instancia me gustaría que me pudieran ayudar con una alternativa en caso de que añadir un datepicker con room sea inútil. Muchas gracias
Pd: room usa fragments y navigation component por lo que no es tan sencillo implementar este datepicker

kotlin – Activity como start destination en navigation component Android

Me preguntaba si existe alguna manera de utilizar el navigation component de android jetpack con una activity como start destination, ya que la pantalla principal de mi app utiliza la cámara y me es más fácil mantenerla como activity que convertirla en el nav host fragment.

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/livePreviewActivity2">

<action
    android:id="@+id/action_global_tracking_mileChronometer"
    app:destination="@+id/chooseLiftDialogFragment2"
    app:launchSingleTop="true" />

<dialog
    android:id="@+id/chooseLiftDialogFragment2"
    android:name="com.ivandlrapp.virtualenconder.ui.main.ChooseLiftDialogFragment"
    android:label="fragment_choose_lift_dialog"
    tools:layout="@layout/fragment_choose_lift_dialog" />
<activity
    android:id="@+id/livePreviewActivity2"
    android:name="com.ivandlrapp.virtualenconder.ui.main.LivePreviewActivity"
    android:label="LivePreviewActivity" />

Activity layout con fragment container:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true">

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"

    app:defaultNavHost="true"
    app:navGraph="@navigation/nav_graph" />

<!- otras views -->

</androidx.constraintlayout.widget.ConstraintLayout>

kotlin – Files just creating once on Android 11

i have an app that take some pictures and print some logs with the logback-android library, this pictures and logs was saved in a folder in the root directory storage/emulated/0/my-directory/
But we are updating to Android 11 and the new storage policy dont let me save files in that route, so my pictures and logs are now stored in documents in this way:

val directory = File(getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "pictures")
if(directory.exists()) directory.deleteRecursively()                                                
fileName = this.getFileName(c);
File file = new File(directory, fileName);
OutputStream output = new FileOutputStream(file);
output.write(data);
output.flush();
LOGGER.debug("File {} written", fileName);
output.close();

And the logback configuration looks like this:

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
        
    <file>/storage/emulated/0/documents/logs_proyect/log_proyect.txt</file>
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{40} - %msg%n</pattern>
        </encoder>
</appender>

The problem is that the files get saved correctly just once, if i delete the log file it stops writting logs forever, and even if i dont delete the file sometimes tops writting in it, and the same pass with the pictures, if i delete files it stop saving them.
I cant use the all files acces permission for the google policy, my manifest have this permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.MANAGE_INTERNAL_STORAGE"/>

Thanks in advance for any help