简体   繁体   中英

Android - getActivity and Activity life cycle

If I have the following code in a Fragment:

public void doSomething() {
    if (getActivity() == null)
        return; // no null pointer exceptions here!
    // ...
    // do bunch of stuff here
    // ...

    getActivity().setTitle("done something"); // just whatever
}

As you can see, at the beginning of the method I check if getActivity() is null and return if it is. However, if it is not null, the method continues executing. At the end, I call getActivity() again to set title, however I don't check if getActivity() is null. Theoretically, it's possible at this point the Fragment has been detached from the Activity so it's possible getActivity() could be null and therefore the last line will throw a NullPointerException. What is the solution for this? Check if getActivity() is null every time I want to call it?

Edit: Even if we try this, it's possible to get a NPE - I just called getActivity() each time to simplify the example:

public void doSomething() {
    Activity activity = getActivity();
    if (activity == null)
        return; // no null pointer exceptions here!
    // ...
    // do bunch of stuff here
    // ...

    activity.setTitle("done something"); // just whatever
}

The problem is not that the Activity hasn't finished loading yet - this can happen minutes after load for instance, as a response to any event. The problem is not the FIRST call to getActivity, it's that in the 15 lines or so from the time we check if activity is null to the last time we reference it, it can no longer exist.

I don't have a logcat right now, but this is what is happening. We haven't really seen this ourselves, but this is for an app where this function is being called thousands of times a day, so it's possible to happen once in a while to someone.

Edit 2: What I'm currently doing is trying and catching for NPEs and just not doing something if it fails. However it seems like an ugly way to solve the problem - I'm wondering if there's a better solution!

Call getActivity once at the top and save it in a variable. Why call it 20 times when it won't change in between (and if it did, using a mix of the old and new could be really bad anyway).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM