我使用一个带有实例引用的自定义视图类,它充当编辑器。视图仅在片段中使用。我需要实例引用,这样我就可以始终获得自定义视图的自定义参数。
public static StoryView instance;
private Story story;
public static Story getCurrentStory(){
if(instance == null) return null;
else return instance.story;
}但是,当我使用这个getter方法更改导航抽屉的内容时,我会收到一个警告:

在这里:
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)是一种基本格式化i18n字符串的静态方法。
我的猜测是,在函数作用域的末尾,引用s正在被破坏,可能是通过分配s = null来实现的?也许这会破坏我的自定义视图中的实际instance.story?
发布于 2017-04-30 09:53:30
这只是对可能的NPE (NullPointerException)的一个警告。您应该做的是在取消引用之前为s编写一个空检查。就这样。
if(s != null){
// Call to s.method();
}最终,您必须确保所获得的任何引用都不能在为NULL时被取消引用。
就我个人而言,我遇到过几种情况,在取消引用之前不进行检查,这些情况大多数情况下都是错误。谷歌开发时,番石榴将NPE问题考虑在内,并将其纳入到他们的稳健设计中。
https://stackoverflow.com/questions/43705083
复制相似问题