So I have created a Fragment for my app. In the fragment, I have an EditText
field created through the xml file (whose id is myText
). Now in my Java class of this fragment, I am creating a reference to this text field by using the command:
EditText myText = (EditText) getView().findViewById(R.id.myText);
However, I get a warning on this statement saying:
Method invocation `getView().findViewById(R.id.myText)' may produce 'java.lang.NullPointerException'.
Also, when I run the app, it terminates prematurely due to the same NullPointerException
. I did the exact same thing except without using a fragment (that is, I created an EditText
field in the xml file of my main activity) and created a reference to it in the Java file using the command:
EditText myText = (EditText) findViewById(R.id.myText);
and it works perfectly.
So my question is, why does this work in the second case and not in the first? How do I make it work in the first case?