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"?
>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);