2

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?

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

What I did is placing lateinit var binding: ActivityMainBinding outside the class but thanks for alternative solution.
@LabaDiena Don't do that. You are leaking your views outside your activity, keeping them in memory after the Activity is already destroyed.
@Tenfour04 Thanks. Sometimes I get answers but don't get suggestions.
@Tenfour04 So, MikkeIT's answer is also bad practice?
No, it’s fine as long as you aren’t copying the binding or view reference into another property.
0
private var callAPI: CallAPIAsyncTask = CallAPIAsyncTask() 

lite this

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.