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