Dereference may produce NullPointerException when using getter

user7401478 :

I'm using a custom View class with an instance reference which serves as an Editor. View is only used in a fragment. I need the instance reference so I can always get custom parameters of the custom View.

public static StoryView instance;
private Story story;

public static Story getCurrentStory(){
    if(instance == null) return null;
    else return instance.story;
}

However, when I'm using this getter method to change the contents of Navigation Drawer, I'm getting a warning:

enter image description here

In here:

private static IDrawerItem[] drawerEditorItems(){
    Story s = StoryView.getCurrentStory();
    SectionDrawerItem section_editor = new SectionDrawerItem()
         .withName(str("placeholder_story_by", s.name, s.author))
         .withDivider(false);
    return new IDrawerItem[]{ section_editor };
}

str(String id, Object... args) is a static method that basically formats i18n strings.


My guess is that the reference s is getting destroyed at the end of the function scope maybe by assigning s = null? And maybe that might destroy the actual instance.story from my custom View?

Zoe :

When you call

public static Story getCurrentStory(){
    if(instance == null) return null;
    else return instance.story;
}

You check to make sure instance isn't null. If it is, you return null. What may be the case here is that instance is always null(never initialized). Meaning you have to ensure instance is initialized before calling it if you want to get the current story.

Also, this is technically not necessary. Returning a null instance is equivalent to checking if it's null, then returning null. you can also use @NotNull and @Nullable to help both the compiler, yourself, and anyone else working on the code/interacting with it.

Further, it may still return null in some cases, so you want to add a check to ensure it isn't null. This can be done using an if-statement:

if(s != null){
    //Do whatever
}

But the reason you are getting that warning is (in my experience) when it is almost guaranteed you will get an exception. take this for an instance:

View v = null;
v.setText("");

That shows the exact same warning as you are getting. So, most likely, your method will return null no matter what. So you have to make sure instance is initialized, and have an if-statement to make sure the app doesn't crash if it is null. Initializing instance is a way to ensure you get a reference that isn't null

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466434&siteId=1