Ertürk Öztürk Ertürk Öztürk - 6 months ago 35
Android Question

Dynamic intent parameter for start activity

I want to create a method for starting activities. I don't want to write this every time:

Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);


Instead I want to use it like this: (Using 1 line instead of 2 lines)

ShowActivity(LoginActivity);


By using a custom method like this:

public void ShowActivity(Activity act)
{
Intent intent = new Intent(this, act.class);
startActivity(intent);
}


and maybe overloading further:

public void ShowActivity(Activity act, boolean finish)
{
Intent intent = new Intent(this, act.class);
startActivity(intent);

if(finish)
CurrentActivity.this.finish();
}


Anyway, it's giving cannot find symbol error (I don't know why it's cannot instead of can not by the way). Is it possible to do so, if yes is it reasonable to do so? (Last one) If yes why not there is a 1-line method embedded to do this?

Do I think too much "C#ish" with this approach as a Java noob?

Thanks in advance.

P.S. I'm an Java and Android noob such that I'm not even sure about the question's title. I don't know how to ask better, therefore I couldn't search properly if this question is duplicated or not. If it's so, apologies.

Answer

define a util class, like following:

public class AcitivtyUtil {
    public static void showActivity(Activity from, Class<?> to, boolean finish) {
        Intent intent = new Intent(from, to);
        from.startActivity(intent);
        if (finish) {
            from.finish();
        }
    }
}

then you can call ActivityUtil.showActivity(this, TargetActivity.class, true|false) at any Activity.

some error in your code:

public void ShowActivity(Activity act)  // here you can't pass a Activity object as parameter, you should pass Class<?>, so it should be act.class
{
    Intent intent = new Intent(this, act.class);
    startActivity(intent);
}

If you don't want use util class, you can also define the showActivity() in your Activity class as member method, recommend define it in BaseActivity, so you need not duplicate it in all Activity.

public void showActivity(Class<?> to, boolean finish) {
    Intent intent = new Intent(this, to);
    startActivity(intent);
    if (finish) {
        finish();
    }
}
Comments