且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“没有封闭的类型实例"从 Android 中的另一个类调用方法时出错

更新时间:2023-11-20 22:30:58

就这里的实际错误而言,如果 parse***AndYahoo 类是您的 Activity 内部的非静态内部类,那么您需要封闭类的实例,以便实例化内部类.所以,你需要:

In terms of the actual error here, if parse***AndYahoo class is a non-static inner class inside of your Activity, then you need an instance of the enclosing class in order to instantiate the inner class. So, you'll need:

MainActivity myActivity = new MainActivity();
MainActivity.parse***AndYahoo asyncTask = myActivity.new parse***AndYahoo();

不过……

您真的不应该从 Activity 外部实例化您的活动的非静态内部类,因为为了实例化非静态内部类,您必须实际实例化封闭类,在这种情况下,是活动.活动旨在启动,而不是通过 new 实例化.如果您有一个 AsyncTask 想要在不同的地方使用,那么创建一个从 AsyncTask 扩展的新***类.

You really shouldn't be instantiating non-static inner classes of your Activities from outside of the Activity because in order to instantiate a non-static innner class, you have to actually instantiate the enclosing class, which, in this case, is the Activity. Activities are meant to be started, not instantiated via new. If you have an AsyncTask that you'd like to use in different places, then create a new top-level class that extends from AsyncTask.

(有关创建可重用 AsyncTasks 的示例,请参阅:https://github.com/levinotik/ReusableAsyncTask)

(For an example of creating reusable AsyncTasks, see: https://github.com/levinotik/ReusableAsyncTask)

请注意,如果您需要获取 静态 嵌套类,则您尝试使用的语法将起作用.这是因为在这种情况下,外部类实际上只是充当命名空间,而嵌套类,因为它是静态的,实际上并不需要对外部类的实例的引用.因此:

Note that the syntax you've tried to use WOULD work if you needed to grab a static nested class. This is because in such a case, the outer class is really just acting as a namespace, but the nested class, because its static, does not actually need a reference to an instance of the outer class. Thus:

OuterClass.StaticNestedClass nestedObject =
     new OuterClass.StaticNestedClass();

是获取 static 嵌套类实例的正确语法.

is the proper syntax for getting an instance of a static nested class.