abdelrhman abdelrhman - 2 months ago 17
Android Question

Cannot create a default constructor from a class that extends Dialog

I have a class that extends Dialog. When I tried to generate my app, I got a message

Error: This class should provide a default constructor (a public constructor with no arguments)


I have tried
public myclass(){}
, but it doesn't work. How can I define a default constructor?

Answer

FIRST WAY

private static Context context;

public static void setContext(Context context_) {
    context = context_;
}

public myclass() {
    super(context);
}

Note : Don't forget to call setContext method before going to call Constructor of this class.

SECOND WAY

1) Create Application class in your project

public class MyApplication extends Application {

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getContext() {
        return mContext;
    }
}

2) Declare this Application in Manifest like below

<application
    android:name=".MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >

3) And class super method in your class like

public myclass() {
    super(MyApplication.getContext());
}

Hope it'll help.

Comments