Search code examples
androidandroid-activityinner-classes

Android activity as inner class


I'm trying to declare an Android Activity as an inner class. This Activity should only be spawned by the containing class and needs access to some of its private methods (Methods I really don't want to make public.). When trying to spawn it though, I get this:

java.lang.InstantiationException: can't instantiate class com.foo.bar.baz$MyActivity; no empty constructor

The activity is properly declared in my manifest. Is this just not possible in Android?

EDIT: Some code

...
public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        // Do stuff that uses the parent class's functions
        ...
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (!forwardResultToParent(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
        } else {
            finish();
        }
    }
}

Solution

  • An instance of the inner class has a reference to the containing instance of the containing class. You can create an instance of the inner class only from a method (or constructor) of the containing class.

    Probably you can make the inner class static. It will be able to access the parent class fields only if you provide an explicit reference, but I think you can live with that.

    You should also consider creating a special package and using package visibility. (See the 2023 comment below)