1

I am having trouble implementing a method to edit the root view of a fragment. Here is the code in question

public class CanvasFragment extends Fragment {
View rootView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    rootView = inflater.inflate(R.layout.canvas_layout, container, false);
    return rootView;
}

public void updateColor(String color){
    rootView.setBackgroundColor(Color.parseColor(color));
}

My problem arises in conjunction with some code in my main activity:

    @Override
public void sendColor(String color) {
    FragmentManager fragmentSwitchManager = getFragmentManager();
    FragmentTransaction fragmentSwitchTransaction = fragmentSwitchManager.beginTransaction();
    CanvasFragment canvasFragment = new CanvasFragment();

    fragmentSwitchTransaction.replace(R.id.paletteFrame, canvasFragment);
    fragmentSwitchTransaction.addToBackStack(null);
    fragmentSwitchTransaction.commit();

    canvasFragment.updateColor(color);
}

As you can see, in my main activity I replace a PaletteFragment within paletteFrame, a frame layout, with a CanvasFragment. I have tested this and it works fine, however when attempting to call updateColor(), I get an error.

The error claims that rootView is a null object reference, and as such, I cannot call setBackgroundColor() on it. I'm not sure as to why this is the case as I had tested similar code before (In which I did not replace the fragment) and it worked fine. Any help would be appreciated. Thanks!

Jeb
  • 33
  • 6
  • `fragmentSwitchTransaction.commit();` is an asynchronous operation, even if you use `commitNow` there is no guarantee `onCreateView` in your `Fragment` has been called . Use `CanvasFragment::setArguments` and add a `Bundle` with your `String` use `getArguments` in your `Fragment` to get the `Bundle` and `String` color. https://stackoverflow.com/a/17436739/4252352 – Mark Mar 22 '18 at 00:57
  • The method still obtains the correct `String` regardless of if it is received from the method parameters or the `Bundle`. Isn't the problem associated with the fact that `setBackgroundColor` still can't be called since rootView is `null`? How would I set the background color of the fragment without referencing `rootView`? – Jeb Mar 22 '18 at 01:14
  • Just because you have instantiated a new instance of your `Fragment` it doesn't mean that it's lifecycle callback methods have been called by the Android framework after your called `commit()` meaning you don't control when `onCreateView` is called. I suggest you look at the link I provided, and don't use `updateColor` method. – Mark Mar 22 '18 at 01:34

0 Answers0