Android: replacing text in activity after click event on fragment button

60 views Asked by At

I got lots of NPEs and was wondering how you manage this common task.

  1. There is a button in my fragment, here the WelcomeFragment.

  2. The button will clicked and the event is handled in the MainActivity class.

  3. The fragment is a NPE, the view, too ...

Here is my code snippet of my MainActivity:

@Override
public void onClick(View v) { 
    switch (v.getId()) {
        case R.id.button1:
            ...
            WelcomeFragment welcomeFragment = (WelcomeFragment) getFragmentManager().findFragmentByTag(WelcomeFragment.WELCOME_FRAGMENT_TAG);
            if (welcomeFragment == null){
                welcomeFragment = new WelcomeFragment();
            }
            View view = welcomeFragment.getView();
            if (view == null){
                view = new View(this);
            }
            TextView text1 = (TextView) view.findViewById(R.id.welcomeFragmentHeader);
            text1.setText(newTextToShow + resStr);
            break;

...

1

There are 1 answers

0
Mehmet K On

I'm assuming your app crashes with an NPE the first time you click this button, when there is no WelcomeFragment instance:

(WelcomeFragment) getFragmentManager().findFragmentByTag(WelcomeFragment.WELCOME_FRAGMENT_TAG);

returns null, so you enter the if statement and construct a WelcomeFragment.

This is not the right way to make a fragment. It's contents are not inflated this way, thus it has no views in it. Therefore, your later call to (TextView) view.findViewById(R.id.welcomeFragmentHeader); also returns null. Therefore you are calling setText() on a null object in the next line, and getting an NPE.

You need to properly inflate add your fragment to your activity as outline in here, or change your app logic.