NBC NBC - 7 months ago 106
Java Question

EditText View returns null

I have two activities - a Home fragment activity, and a normal Options activity.

In my home fragment activity, I'm trying to update an EditText View using data retrieved from the Options activity.

Unfortunately, for some reason, the fragment activity cannot detect my view for updating. I'm not entirely sure why. Here is my function:

//update text box
public void updateUserData (String[] userArray){

Log.d("User Update:", "beginning...");
//get username
EditText et=(EditText)getActivity().findViewById(R.id.Input_Name);

if (et == null) {
Log.d("ERROR:", "View returning null");
}

if (userArray[0] != null) {
Log.d("Updating name:", userArray[0]);
et.setText(userArray[0]); }

}


The weird thing is... that formula for retrieving the EditText View works perfectly fine in other parts of my code. But here it always returns null. Any suggestions?

edit: here is where I call the function in OnCreateView:

if(getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
String[] prelimUserArray = getActivity().getIntent().getExtras().getStringArray("userArray");
updateUserData(prelimUserArray);
}

Answer

Edit:

Move this snippet:

if (getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
    String[] prelimUserArray = getActivity().getIntent().getExtras().getStringArray("userArray");
    updateUserData(prelimUserArray);
}

to the onViewCreated method, which will be called after the view has been inflated.

public void onViewCreated(View view, @Nullable Bundle savedInstanceState){
    // Your code here
}

Check this image for more information about the Fragment's lifecycle.

Fragment's lifecycle


Make sure that you are calling your updateUserData method after the Fragment's onCreateView() callback has been triggered.


Try using getView() instead of getActivity() as mentioned in this answer.

getActivity() returns the Activity hosting the Fragment, while getView() returns the view you inflated and returned by onCreateView. The latter returns a value != null only after onCreateView returns.


Also, as mentioned in the comments, check if you indeed have the EditText with an id Input_Name.