[否封装类型和QUOT的实例;错误而从另一个类在Android中调用方法实例、错误、类型、方法

2023-09-12 01:15:04 作者:纯情小火鸡

同事,我有这样的疑问: 1.在我的第一类我有

Colleagues, I have the such question: 1. In my first class I have the

public class parseYouTubeAndYahoo extends AsyncTask<String, Void, List<VideoDataDescription>>

从互联网分析数据。但我需要调用execute()这个类的方法从另一个类。虽然试图纠正这种code:

to parse data from internet. But I need to call execute() method of this class from another class. While trying to right such code:

new MainActivity.parseYouTubeAndYahoo().execute("someURL"); 

我从Eclipse中的一个错误信息

I have the next error message from Eclipse

型MainActivity没有封闭实例访问。必须符合分配与类型MainActivity(egxnew A()其中x是MainActivity的一个实例)的一个封闭的实例。

和真正的这个问题是笼罩在迷雾我。那么,如何调用来自另一类方法是什么?

and really this problem is shrouded in fog for me. So, how to call this method from another class?

推荐答案

在实际的错误的具体条款,如果 parseYouTubeAndYahoo 类是一个非静态内部类的内部你的活动,那么你以实例化内部类需要封闭类的一个实例。所以,你需要:

In terms of the actual error here, if parseYouTubeAndYahoo 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.parseYouTubeAndYahoo asyncTask = myActivity.new parseYouTubeAndYahoo();

不过......

However....

您真的不应该被实例化非静态内部类的活动从活动之外,因为为了实例化一个非静态肠子类,你有实际实例化封装类,其中,在这种情况下,是该活动。活动是为了启动,而不是通过实例化新。如果你有一个的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();

是获得一个静态嵌套类的一个实例的正确语法。

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