1

I am trying to reverse a fragment transaction to bring the user back to the previous fragment when the user hits the back button. Problem is, there is a media controller and so, the back button event will be handled by dispatchKeyEvent.I've tried to manually call onBackPressed as follows but I receive a null pointer exception.

MainActivity obj;

  public boolean dispatchKeyEvent(KeyEvent event) {
        obj = new MainActivity();
        int keyCode = event.getKeyCode();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            System.out.println(obj);
            obj.onBackPressed();
        }
        return super.dispatchKeyEvent(event);
    }

In my main activity, my fragment transaction is as follows:

            transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);
            transaction.commit();

What is the best way that I can handle the back button to involve reversing the fragment transaction and the MediaController?

Thanks

Lew Wei Hao
  • 763
  • 1
  • 13
  • 25

1 Answers1

1

Override this method of fragment to get the reference of the activity object

MainActivity obj;
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    obj = (MainActivity) obj;    
}

Remove the object creation in dispatchKeyEvent().

Nigam Patro
  • 2,760
  • 1
  • 18
  • 33