Laba Diena
Laba Diena

Reputation: 87

lateinit property binding has not been initialized when using from other class

In the MainActivity class I use this snippet:

lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

And I'm trying to access textView from other class like this

MainActivity().binding.textView.text

but I'm getting lateinit property binding has not been initialized error on this line? Anyone knows how to solve it?

Upvotes: 2

Views: 2129

Answers (2)

isa
isa

Reputation: 784

private var callAPI: CallAPIAsyncTask = CallAPIAsyncTask()

lite this

Upvotes: 0

MikkelT
MikkelT

Reputation: 815

When you you're calling MainActivity(), you're effectively creating a new instance of MainActivity, but it hasn't been bound to any lifecycle (thus not calling onCreate(), thus not inflating your layout).

If you're trying to access the activity from a fragment, call:

(requireActivity() as MainActivity).binding.textView.text

Edit: do note that this approach will throw an error if your fragment is hosted by a different activity than MainActivity

Upvotes: 4

Related Questions