Skip to content
Advertisement

How to access views added programmatically to a custom view?

I have created a custom class that extends from the MaterialCardView class, to which I add a TextView programmatically like this:

JavaScript

I create an instance of the CustomQuestionView in the onViewCreated() method of my fragment like this:

JavaScript

And my XML code for my fragment where the custom view is looks like this:

JavaScript

The CustomQuestionView is created, and I get the initial text on the TextView showing on screen if I don’t make a call to the setQuestion() method, but the problem is that when I try to change the text by calling the setQuestion() method (when I uncomment the commented line on my onViewCreated() method), the app crashes and gives me the following error:

JavaScript

Why is my TextView null at the moment of invocation of this method, if I assign a value to it in the constructor? How do I need to access this TextView so that I can modify it after the CustomQuestionView is created?

Advertisement

Answer

The problem here is that the constructor where you are initializing the TextView is not invoked but rather the other constructor. So the timeTextView is null and when you try to invoke customQuestionView.setQuestion it causes a NullPointerException and crashes.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement