-1

I want to declare 3 private global variables, inside my MainActivity.kt . This is what I'm trying to do, but it doesn't work: the app crashes every time I open it on the emulator.

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var getTextBtn = Button(this)
    private var edtTxtName = EditText(this)
    private var textViewHello = TextView(this)
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        
        getTextBtn = binding.getRecipeBtn
        edtTxtName = binding.edtTxtName
        textViewHello = binding.textViewHello
    }
}

I'm a newbie in Kotlin/Android Studio, so probably what I'm doing it's totally wrong, but I can't figure out how to do it

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
zupus
  • 79
  • 1
  • 6
  • Does this answer your question? [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – a_local_nobody Feb 18 '22 at 10:08
  • you're trying to solve a problem but you're not trying to identify the cause of it. instead of writing this code, having your app crashing and then asking here how to fix it, take a moment to learn about stack traces and how to debug your app from the link i've sent you, then you will learn how to fix your own problems without having to ask here – a_local_nobody Feb 18 '22 at 10:10

1 Answers1

1

You should use private lateinit var for those variables as well:

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var getTextBtn: Button
    private lateinit var edtTxtName: EditText
    private lateinit var textViewHello: TextView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        
        getTextBtn = binding.getRecipeBtn
        edtTxtName = binding.edtTxtName
        textViewHello = binding.textViewHello
    }
}

Though, I'd advocate against it - you can access them from your binding anyway. The less references to maintain, the better.

romtsn
  • 11,704
  • 2
  • 31
  • 49