Difference Between Oncreate() and Onstart()

Difference between onCreate() and onStart()?

Take a look on life cycle of Activity
Sample Image

Where

***onCreate()***

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
Always followed by onStart().

***onStart()***

Called when the activity is becoming visible to the user.
Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

And you can write your simple class to take a look when these methods call

public class TestActivity extends Activity {
/** Called when the activity is first created. */

private final static String TAG = "TestActivity";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "On Create .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}

/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}

/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}

/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
}

Hope this will clear your confusion.

And take a look here for details.

Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.

Where is the difference between onCreate and onStart if both are called upon Activity change anyway? What's the purpose?

onCreate() is called when the activity is first created. onStart() is called whenever the activity becomes visible, which includes when it is first created (after onCreate()) and after it is coming back to the screen from being stopped (e.g., another activity took over the screen).

So:

  • Put code in onCreate() that needs to happen when the activity is created (and use onDestroy() to clean it up)

  • Put code in onStart() that needs to happen either when the activity is created or when the activity returns to the foreground (and use onStop() to clean it up)

Frequently, we do not do anything special when the activity returns to the foreground, in which case you do not need to worry about onStart() or onStop().

OnCreate() vs OnStart()

As long as your device does not kill the activity, for example due to low system resources, then any time you leave your app and go back, onStart is called. If however the application process is killed, then when you return onCreate will be called again, because all of your resources will have been released.

What is the performance impact of onCreate() and onStart() on activity startup

In the method onCreate the activity actually gets created and then second method onStart gets call at the time of onStart the UI actually get visible to user, for better understanding of activity you need to understand the Activity Life cycle. Sample Image

Difference between onStart() and onResume()

Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()? What is its purpose?

OK, as my first answer was pretty long I won't extend it further so let's try this...

public DriveToWorkActivity extends Activity
implements onReachedGroceryStoreListener {
}

public GroceryStoreActivity extends Activity {}

PLEASE NOTE: I've deliberately left out the calls to things like super.onCreate(...) etc. This is pseudo-code so give me some artistic licence here. ;)

The methods for DriveToWorkActivity follow...

protected void onCreate(...) {
openGarageDoor();
unlockCarAndGetIn();
closeCarDoorAndPutOnSeatBelt();
putKeyInIgnition();
}

protected void onStart() {
startEngine();
changeRadioStation();
switchOnLightsIfNeeded();
switchOnWipersIfNeeded();
}

protected void onResume() {
applyFootbrake();
releaseHandbrake();
putCarInGear();
drive();
}

protected void onPause() {
putCarInNeutral();
applyHandbrake();
}

protected void onStop() {
switchEveryThingOff();
turnOffEngine();
removeSeatBeltAndGetOutOfCar();
lockCar();
}

protected void onDestroy() {
enterOfficeBuilding();
}

protected void onReachedGroceryStore(...) {
Intent i = new Intent(ACTION_GET_GROCERIES, ..., this, GroceryStoreActivity.class);
}

protected void onRestart() {
unlockCarAndGetIn();
closeDoorAndPutOnSeatBelt();
putKeyInIgnition();
}

OK, so it's another long one (sorry folks). But here's my explanation...

onResume() is when I start driving and onPause() is when I come to a temporary stop. So I drive then reach a red light so I pause...the light goes green and I resume. Another red light and I pause, then green so I resume. The onPause() -> onResume() -> onPause() -> onResume() loop is a tight one and occurs many times through my journey.

The loop from being stopped back through a restart (preparing to carry on my journey) to starting again is perhaps less common. In one case, I spot the Grocery Store and the GroceryStoreActivity is started (forcing my DriveToWorkActivity to the point of onStop()). When I return from the store, I go through onRestart() and onStart() then resume my journey.

I could put the code that's in onStart() into both onCreate() and onRestart() and not bother to override onStart() at all but the more that needs to be done between onCreate() -> onResume() and onRestart() -> onResume(), the more I'm duplicating things.

So, to requote once more...

Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()?

If you don't override onStart() then this is effectively what happens. Although the onStart() method of Activity will be called implicitly, the effect in your code is effectively onCreate() -> onResume() or onRestart() -> onResume().

why does onStart() method run before onCreate in my android project?

FACT CHECK

Fact of the matter is, onCreate() is called first then onStart() follows. But because you are making a firebase call to get your dataset, your onStart() is not waiting for this to complete, meaning your list inside onStart is still not populated. Remember when onCreate is called, whatever code is executed there, it does not pause onStart from being called. Likewise, onStart is not waiting for all the code inside onCreate to finish before exeuting it's own code.

YOUR PROBLEM

Seems you want to do something inside onStart after you get your dataset from firebase eventlisteners inside onCreate. I

A SUGGESTION MAYBE?

You can use LiveData to let your code inside onStart know that firebase event listeners are done, and have prepared the data you need to use in onStart.

WHAT IS LIVEDATA YOU ASK?

LiveData is an observable data holder class. Unlike a regular
observable, LiveData is lifecycle-aware, meaning it respects the
lifecycle of other app components, such as activities, fragments, or
services. This awareness ensures LiveData only updates app component
observers that are in an active lifecycle state.

See more here

HOW WILL IT LOOK LIKE:

//just add dependency into the app/build.gradle .def lifecycle_version = "1.1.1"implementation "android.arch.lifecycle:extensions:$lifecycle_version"annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"

// Create an instance of LiveData to hold your firebase dataset eg List of Gig objectprivate MutableLiveData<List<Gig>> myGigLiveData;
.......//initialize inside onCreate()myGigLiveData = new MutableLiveData<>();
.......
mRef.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Gig thisGig = dataSnapshot.getValue(Gig.class);
loadedGigs.add(thisGig); Log.w("onCreate", "There are " + loadedGigs.size() + "Gigs loaded in the array.");

arrayAdapter.notifyDataSetChanged(); //set the dataset value to livedata myGigLiveData.setValue(loadedGigs); } ............... //observe the livedata in onStart like so: @Override protected void onStart() { super.onStart(); myGigLiveData.observe(this, gigsList ->{Log.w("onStart", "There are " + gigsList.size() + "Gigs loaded in the array.");});
}

What does onStart() really do? - Android

onStart() is called when activity resumes from stopped state. For example, if you have activity A and starts activity B from it, then activity A will be paused (onPause()) and then stopped (onStop()) and moved to back stack. After this, if you press Back into your activity B, B will be paused(onPause()), stopped (onStop()) and destroyed(onDestroy()), and activity A will be restored from back stack, started (onStart()) and resumed(onResume()). As you can see, system will not call onCreate() for A again.

How to use onStart()? For example, you should unregister listeners for GPS, sensors, etc in onStop() and register again in onStart(). If you register it in onCreate() and unregister in onDestroy(), then GPS service will work always and it will drain battery.

Is onStart called when the screen is already visible or becoming visible?

The chances of onStart() can be called multiple times.

onCreate() : Called when the activity is first created.

onStart() : Called when the activity is becoming visible to the user.

Now look into the graph given to Difference between onCreate() and onStart()? post. onStart() can be called multiple times, in case if process is not killed (if activity has been called again.)

So if you set view at onStart(), you will need to initialize view into onStart() or later (i.e. onResume() ). This will be a repetitive process. Is not it a bad practice to initialize view again and again?

Hope I am clear here.



Related Topics



Leave a reply



Submit