1

I have an Activity QuestScreen, which at its creation holds the Fragment FragmentQuest. If i press at the Button, this triggers the next() Method of the Screen activity, leading to replace the FragmentQuest with FragmentAction.

The replacing works so far. The problem is, that after the replace i want to set a TextView in the FragmentAction, to avalue which is generated in the QuestScreen Activity.

My first attempt was to set the TextView outside the onCreatView of FragmentAction. This lead to a Nullpointer exception adressing the TextView.

So far I have looked at: This, That, This and That

The attempt seen below leads to an NullpointerException marked in the code.

In The QuestScreen Class

 private void next(){

    //The needed value for the TextView is stored in nextTransition
    Transition nextTransition;
    //Check if an entry is in the list
    if(quest.getTransitionsAbleToFire().size() > 0){
        nextTransition = quest.getTransitionsAbleToFire().get(0);

        fragmentAction = (FragmentAction) fm.findFragmentByTag(TAG_FRAGMENT_ACTION);

        // create the fragment and data the first time
        if (fragmentAction == null) {
            Log.d("QuestScreen onCreate" , "create fAction for first time");
            // add the fragment
            fragmentAction = (FragmentAction) Fragment.instantiate(this, FragmentAction.class.getName(), null);

            fm.beginTransaction().add(fragmentAction, TAG_FRAGMENT_ACTION).commit();
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.flFragmentContainer, fragmentAction);
            fragmentTransaction.commit();
        }

        //Triggers the corresponding activity in fragmentAction, to set the TextView to a value which is stored in nextTransition
        fragmentAction.nextAction(nextTransition);
        nextTransition.fire();

    }
    else{
        CharSequence text = "Quest END";
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(getApplicationContext(), text, duration);
        toast.show();
    }
}

In the FragmentAction Class

public class FragmentAction extends Fragment {

private TextView txtYourQuest;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // CREATE VIEWS HERE

    View layout = inflater.inflate(R.layout.content_action_fragment, container, false);
    txtYourQuest = (TextView) layout.findViewById(R.id.txtV_Your_Quest);
    return layout;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

public void nextAction(Transition prmTransition){

    // --> Here in the enxt Line comes the NPE :  java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference

    FrameLayout container = (FrameLayout) getActivity().findViewById(R.id.flFragmentContainer);
    LayoutInflater.from(getActivity())
            .inflate(R.layout.content_action_fragment, container, false);

    txtYourQuest.setText("Your " + prmTransition.getAction().getPosition() + ". is to:\n "
    + prmTransition.getAction().getActionName());
}
Sebastian
  • 27
  • 2
  • @Rotwang - OP basically asks how to pass data to a Fragment and says that previous attempts resulted in various NPEs (one is supposed to demonstrate own effort after all). But as the solution is not "do a null check", IMO if it's a duplicate at all, then rather of the question to which the last link is referring. Please note this is not about wanting to reopen, I posted the answer because it was too long for a comment, and I upvoted because it's a well asked question for a newbie on SO. And if I got it right, good duplicates may help others by pointing to the needle in the haystack. – Bö macht Blau Jun 30 '17 at 17:11
  • @0X0nosugar `The attempt seen below leads to an NullpointerException marked in the code.` Enoug to be arked as `Yust Another NPE-Related Duplicate Question`. – Phantômaxx Jun 30 '17 at 17:16
  • @Rotwang - all right, so if this was my question I should add null checks where necessary and then ask "why is this code not working"? – Bö macht Blau Jun 30 '17 at 17:26
  • @0X0nosugar I'm expecting you to be an expert developer. Then you're not supposed to fall into an NPE trap. Or if you accidentally do, that you can easily get rid of it. Therefore, you would not need to ask a question. – Phantômaxx Jun 30 '17 at 17:30
  • 1
    @Rotwang - thank you for trusting me to avoid/ handle NPEs ;-) and thank you for your patience. Maybe this is just the point: for me, this is a question about android mechanics, thinly veiled by some NPEs. With null checks the app won't crash. But I suppose "won't crash" is not "mission accomplished". – Bö macht Blau Jun 30 '17 at 17:49
  • 1
    Sorry for duplicating, I didn't know. Played a bit with the code and created a workaround. Instead of using the _getActivity_ Method, which returns null. (I think because the _nextAction()_ is executed before onCreate, onCreateView, onAttach etc.) I now store the submitted data in an local object, and use this object to fill the TextView after the _nextAction()_ Method, using it in the _onCreateView_. – Sebastian Jun 30 '17 at 23:56

1 Answers1

0

Activity.findViewById(int)' on a null object reference

This means your getActivity() somehow returns null. To find out, why does this happen, google something like "getActivity() returns null". Here is a good example of this kind of question on stackoverflow.

And this a workaround to get rid of the crash.

  • Add activity field to your fragment.

    Activity activity;

  • Override onAttach() method and set the value to your activity field.

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
    }
    
  • Replace getActivity() method with your activity variable.

FrameLayout container = (FrameLayout) activity.findViewById(R.id.flFragmentContainer);

Dmitry Smolyaninov
  • 2,159
  • 1
  • 18
  • 32
  • Thanks for your suggestion. I have tried to set an global variable as you suggested and stumbled upon [this](https://stackoverflow.com/questions/32083053/android-fragment-onattach-deprecated). But it is not working. It seems like the code of nextAction() is executed before the onAttach() method. (At least in my case, all outputs in onAttach are not displayed in the console.) – Sebastian Jun 30 '17 at 23:37