【问题标题】:WebView Reference is Null When Calling Parent Method From Child Class从子类调用父方法时,WebView 引用为空
【发布时间】:2015-05-04 06:18:44
【问题描述】:

当我从子类调用父方法时,WebView 引用为空,我不知道为什么或如何修复。提前感谢您的帮助!

示例父类:

public class ParentClass extends Activity {

public WebView MyWebView;

@Override
protected onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MyWebView = (WebView) findViewById(R.id.MyWebView);
};

public void MyParentMethod(String sURL) {
    //This "MyWebView" reference is null and nothing happens when called from child class???
    MyWebView.loadUrl(sURL);
};

};

示例子类:

public class ChildClass extends ParentClass {

    public void MyChildMethod() {
        super.MyParentMethod("...");
    };

};

【问题讨论】:

  • 你在哪里使用ChildClass类?
  • 检查是否可以在 Child 类中直接调用 MyParentMethod()。(没有 super)
  • 当我直接调用该方法MyParentMethod()(没有超级)时,我得到一个 NPE 错误。我正在使用ChildClass,因为我有 2 个已编译的 jar 库,用于 2 个不同的集成硬件,需要注意的是这两个库都使用具有重复名称的处理方法。子类允许我将这些方法分开。

标签: java android inheritance webview parent-child


【解决方案1】:

你为什么用 super 关键字调用 ParentClassMyParentMethod()

super 关键字通常在ChildClass 成员和ParentClass 成员(方法/变量)具有相同名称时使用。

您可以只使用 方法名称 调用 ParentClass 方法(如果 ChildClass 没有相同的方法),因为该方法也属于 ChildClass,例如methodName(arguments).

因此,您应该将此 super.MyParentMethod("..."); 替换为 new ParentClass().MyParentMethod("...");MyParentMethod("...");

【讨论】:

  • 我尝试以new ParentClass().MyParentMethod("...");MyParentMethod("..."); 两种推荐的方式调用父方法。两者都返回 NPE。同样,当我使用“super”调用该方法时,该方法有效,但原始引用为空。
猜你喜欢
  • 2019-11-12
  • 1970-01-01
  • 2017-11-09
  • 2012-02-22
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多