Why onResume is called when i open for the first time the tab of a tabhost?
Asked Answered
D

3

5

I have a tabhost with some tabs, and each tab have implemented the method onresume, because I need to reload all the data from a remote database each time the user enter again in a tabhost, not only the first time he opens it.

Ok, it works nice, but the problem is that when the user opens for the first time a tab, the two methods, onCreate and onResume are called, then, my app connect two times into the database to retrieve the info.... I want only to be called onCreate when the user enter for the first time into the tabhost.

How to avoid this rare problem?

Dromous answered 17/12, 2010 at 18:13 Comment(0)
H
15

As stated on the Activity lifecycle docs, onCreate and onResume will always both be called the first time an Activity is started. When going back to Activity, at least onResume will be called, but onCreate may be called again if Android needed to free up resources.

If you need the setup to occur every time you return to the activity, why not only put the logic in onResume?

Hennessey answered 17/12, 2010 at 18:33 Comment(3)
lol, great idea, if onresume is always called the firsttime...... then i dont need to fill oncreat!!!Dromous
btw are you 100% sure that onresume will be called ALWAYS THE FIRST TIME AN ACTIVITY IS CREATED?Dromous
Yes, please read the referred documentation. It is very important to fully understand the Activity Lifecycle.Hennessey
I
0

Since your tabs' contents are activities, then they both have to be created (and resumed) when you start the app.

One way to avoid this, is to use views instead of activities as the tab content. That way, you only have 1 onCreate() method because you only have 1 activity (the TabActivity).

Interclavicle answered 17/12, 2010 at 18:17 Comment(2)
impossible to me, i have my app designed with activities, i can't redo the code, it's a lot of codeDromous
does not exist another solution?Dromous
S
0

I agree with the other posters that you should re-factor your app. You can't just expect to stick a stand alone activity into a tab and have everything make sense.

That being said, you could have a flag somewhere that indicates if the DB needs initialization. in each activity's onResume(), you have something like,

synchronized (MyLock.class) {
    if (!initialized) {
      initDb();
      MyLock.initialized = true;
    }
}
Sada answered 17/12, 2010 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.