MrEngineer13
MrEngineer13

Reputation: 38856

Custom listener always null

This is my main activity:

public class MainActivity extends BaseGameActivity implements  GameFragment.Listener {

    GameFragment mGameFragment;

    @Override
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGameFragment = new GameFragment();
        mGameFragment.setListener(this);

    }

    @Override
    public void onGameEnded(int score) {
       ...
    }

}

And this is just a fragment to host my game.

public class GameFragment extends Fragment implements View.OnClickListener {

    public interface Listener {
        public void onGameEnded(int score);
    }

    Listener mListener = null;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.game_layout, container, false);

        checkSequence();

        return view;
    }

    public void setListener(Listener l) {
         mListener = l;
    }


    private void checkSequence() {
            if (mListener != null)
                 mListener.onGameEnded(score);
    }


 } 

For some reason mListener is always null. I've tried other questions on SO but none of them have worked. What am I doing wrong?

Upvotes: 2

Views: 2372

Answers (1)

Dixit Patel
Dixit Patel

Reputation: 3192

I think you have to Override this two Methods in GameFragment

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (activity instanceof Listener ) {
      mListener = (Listener) activity;
    } else {
      throw new ClassCastException(activity.toString()
          + " must implemenet GameFragment.Listener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener= null;
  }

for more detail Read this Tutorial

EDIT

And Don't Forget to Initialize Fragment in Activity

      // Create an instance of GameFragment
        GameFragment mGameFragment= new GameFragment();


        // Add the fragment to the 'fragment_container' Layout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, mGameFragment).commit();

Upvotes: 1

Related Questions