Aditya Patel
Aditya Patel

Reputation: 69

Create new Instance Of activity by Intent every time android?

How to prevent to create every time Instance of Store activity?

When I call startActivity(new Intent(this,StoreActivity.class)), it will create new instance and call OnCreate Method in StoreActivity. I want to call one time Oncreate.

Is this Possible ?

Upvotes: 2

Views: 3512

Answers (4)

Devendra
Devendra

Reputation: 3454

Start your activity like this:

Intent storeIntent = new Intent(this, StoreActivity.class);
storeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(storeIntent);

It will call onCreate() only once on first launch of activity, if activity is already running it calls only onNewIntent() instead of create new instance of activity or calling onCreate.

Upvotes: 1

Samuel
Samuel

Reputation: 65

try to finish the first activity after starting the new one, add this code after the Intent command.

finish();

like that:

startActivity(new Intent(this, newActivity.class));
finish();

check this link Finish an activity from another activity

Upvotes: 0

Muhammad Ibrahim
Muhammad Ibrahim

Reputation: 317

This is not possible since each time you press back button, onBackPressed() method is called which actually destroys your StoreActivity.

If you want this method to not destroy your activity, just remove or comment out super.onBackPressed() line in this method.

In this case your activity will not be destroyed when back button is pressed, but then you will have to use any other logic to bring your MainActivity to top of the stack.

Upvotes: 0

Rohit5k2
Rohit5k2

Reputation: 18112

Do this

startActivity(new Intent(
       this,StoreActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));

From Android Documentation

public static final int FLAG_ACTIVITY_SINGLE_TOP

If set, the activity will not be launched if it is already running at the top of the history stack.

Constant Value: 536870912 (0x20000000)

Upvotes: 1

Related Questions