Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Common Method to switch Activities

I am trying to find out whether we can create a common method to switch between activities and while doing so I thought to write code as:

private fun goToActivity(activity: AppCompatActivity){
    val intent = Intent(this, activity::class.java)
    startActivity(intent)
}

calling the method

    goToActivity(MainActivity2())

Is this the a good to do this thing or any other method that saves rewriting the piece of code again and again written in "goToActivity"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this. Below will handle all your needs.

/**
     * @param context          Context fromactivity or fragment
     * @param bundle           Bundle of values for next Activity
     * @param destinationClass Destination Activity
     * @param isFinish         Current activity need to finish or not
     */
    public void newIntent(Context context, Class destinationClass, Bundle bundle, boolean isFinish, boolean isFlags) {
        if (!isActivityRunning(context)) {
            return;
        }
        Intent intent = new Intent(context, destinationClass);
        intent.putExtras(bundle);
        if (isFlags) {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
        if (isFinish) {
            ((Activity) context).finish();
        }
    }

CommonFunctions.getInstance().newIntent(OrdersActivity.this, HomeActivity.class, Bundle.EMPTY, true,true);

Use bundle like this

Bundle bundle = new Bundle();
                bundle.putString("name", "");
CommonFunctions.getInstance().newIntent(this, CartViewActivity.class, bundle, false, false);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading