-2

I have fatal exception in the method onBackPressed(): on a null object reference. How to handle the exception correctly? My code:

@Override
public void onBackPressed() {
    List fragments = getSupportFragmentManager().getFragments();
    BaseExampleFragment currentFragment = (BaseExampleFragment) fragments.get(fragments.size() - 1);

    if (fragments != null && !currentFragment.onActivityBackPress()) {
        super.onBackPressed();
    }
}
Roman
  • 1,045
  • 1
  • 12
  • 33
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – VishnuSP Jun 01 '17 at 08:51
  • *How to handle the exception correctly?* Fix it: 1. check what is null 2. do not use this null reference – Selvin Jun 01 '17 at 08:54
  • @VishnuSP Do you see that I'm trying to process non-existent data? But there is no interception. Have you ever read the answer that you post and my question? – Roman Jun 01 '17 at 08:55
  • @Selvin look at my question more closely. I check there is a list of fragments. If it exists then I try to take a fragment. Everything works fine on the simulator, on most devices, but sometimes this error appears. – Roman Jun 01 '17 at 09:15
  • 1
    @Roman it does change anything ... you do not check if `getSupportFragmentManager()` returns null, `getSupportFragmentManager().getFragments();` returns null nor `fragments.get(fragments.size() - 1);` ... obviously one of this can be null **please read more closely the question which is pointed as duplicate it's all there** – Selvin Jun 01 '17 at 09:17
  • @Roman Please try to find which object is null from the logs and try to handle it. It similar to NullPointerException. – VishnuSP Jun 01 '17 at 09:20
  • @Selvin thanks for answer. I really did not understand what could be null there, because I did check in the list of fragments. – Roman Jun 01 '17 at 09:21

1 Answers1

1

it would be much easier if you also gave the stack trace. However it is possible you are checking the wrong thing for null, change fragments to currentFragment

@Override
public void onBackPressed() {
    List fragments = getSupportFragmentManager().getFragments();
    BaseExampleFragment currentFragment = (BaseExampleFragment) fragments.get(fragments.size() - 1);

    if (currentFragment != null && !currentFragment.onActivityBackPress()) {
        super.onBackPressed();
    }
}
Matthew Shearer
  • 2,715
  • 3
  • 23
  • 32
  • thanks for answer. I realy do not understand why if there is a fragment, the current fragment does not exist. On the simulator, there is no mistake, only on devices sometimes there is this error. I get it from Fabric – Roman Jun 01 '17 at 09:04
  • maybe the list of fragments is null – Matthew Shearer Jun 01 '17 at 09:42