Sameer Noor
Sameer Noor

Reputation: 1

my if statement is never happening true in kotlin android

if staemnt never happening true. so please help me. i tried changing some stuff and hope it will work but it never did and only else staement is working.

package com.example.managemntsystem

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var input = editText.text
        var empList = arrayListOf<String>("jacob", "raf", "boss", "john")


        button.setOnClickListener {

            if (input == emplist) {

                textView2.setText("WORKING")

            }else{

                textView2.setText("Not working")

            }
        }


    }
}

Upvotes: 0

Views: 96

Answers (4)

Adib Faramarzi
Adib Faramarzi

Reputation: 4060

The reason is your var input = editText.text never gets set again (even though it is a var), so in this case, It's not different from a val. You either need to reassign it or use .text directly:

  1. Set it again:

var input = editText.text var empList = arrayListOf("jacob", "raf", "boss", "john")

button.setOnClickListener {

input = editText.text // add this line

f (input == emplist) {

        textView2.setText("WORKING")

    }else{

        textView2.setText("Not working")

    }
}
  1. Or not use input at all and use text itself:

    button.setOnClickListener {
    
    if (editText.text == emplist) {
    
        textView2.setText("WORKING")
    
    }else{
    
        textView2.setText("Not working")
    
            }
    }
    

Upvotes: 0

Shanto George
Shanto George

Reputation: 994

if(empList.contains(input))

I think this will resolve your issue

Upvotes: 0

mhdtouban
mhdtouban

Reputation: 881

You can also use the in operator:

if (input in empList)

Upvotes: 3

Luciano Ferruzzi
Luciano Ferruzzi

Reputation: 1112

use this instead:

if (empList.contains(input.toString()))

This will check if the content of the EditText is equal to any of the list items. Remember to call toString() method when you want the EditText content.

Upvotes: 4

Related Questions