2

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);
    }
NBC
  • 1,606
  • 4
  • 18
  • 31

1 Answers1

3

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.

Community
  • 1
  • 1
Evin1_
  • 12,292
  • 9
  • 45
  • 47
  • Awesome, moving the code worked! I'm kind of confused though... I didn't have trouble inflating any other views from OnCreate, so why did it matter this time? – NBC May 08 '16 at 22:53
  • I changed the image so it's easier to check where the `onViewCreated` gets called. Your layout hasn't been inflated before the `onCreateView` returns something (the actual view with all the children in your layout). So the `onViewCreated` is guaranteed to be triggered after this View has been returned. – Evin1_ May 08 '16 at 22:59