java parameter Android how to pass an Activity.class as an argument for a function

java accept class as argument (6)

I recently moved to Android from python and am stuck here.

This is my class declaration to create a common function for an Alert Dialog which accepts necessary parameters

public static AlertDialog.Builder getAlertDialog(String strArray[],
        String strTitle, Activity v) {

    return new AlertDialog.Builder(v)
            new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

But I cannot call this function via this piece of code which gives me an error

  getAlertDialog(strArray, strTitle, MakeCall.class).show();

The error is

the method getAlertDialog(String[], String, Activity) in the type   MakeCallAlertDialog is not applicable for the arguments (String[], String, Class<TestActivity>)

Can anyone tell me how to get this correctly? Thank you in advance.

Answer #1

If you just want to pass a reference to your Activity use: MakeCall.this (or maybe just this.)

Answer #2

This works for me:

private void switchActivity(Class cls){
    Intent intent = new Intent(HomeActivity.this, cls);

Call the function like this: switchActivity(DestinationActivity.class)

Answer #3

I think you want to pass this. If this doesn't work, use MakeCall.this.

 getAlertDialog(strArray, strTitle, this).show();

Answer #4

Just create an activity object/instance like new YourActivity().

public static void Redirect(Context context,Activity page) {

..... //code

context.startActivity(new Intent(context,page.getClass()));

((Activity) context).finish();

and use this method as

Redirect(Registration.this, new YourActivity());

Answer #5

call like this:

ButtonClickBySani(, sehrabandiActivity.class);


private void ButtonClickBySani(int ButtonId, final Class<? extends Activity> ActivityToOpen)
    Button btn;
    // Locate the button in activity_main.xml
    btn = (Button) findViewById(ButtonId);

    // Capture button clicks
    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            startActivity(new Intent(getBaseContext(), ActivityToOpen));
            // Start NewActivity.class
            //Intent myIntent = new Intent(getBaseContext(), ActivityToOpen);
           // startActivity(myIntent);

Answer #6

In Java, each class you write will also have a Class class attached to it. The Class class will be used by the classloader etc.

As others have said you should use MakeCall.this instead of MakeCall.class because MakeCall.this will point to itself which is an Activity whilst MakeCall.class will point to MakeCall's attached Class class.