Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

"No enclosing instance of type" error while calling method from another class in Android

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

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

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"); 

I have the next error message from Eclipse

No enclosing instance of type MainActivity is accessible. Must qualify the allocation with an enclosing instance of type MainActivity (e.g. x.new A() where x is an instance of MainActivity).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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....

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.

(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...