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

Eugene Shmorgun picture Eugene Shmorgun · Jan 29, 2012 · Viewed 38.9k times · Source

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?

Answer

LuxuryMode picture LuxuryMode · Jan 29, 2012

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.