Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application class onCreate method not running on starting app 2nd time

Tags:

android

I am using Application class to share global variables across activites and I am setting them in onCreate method of application class. When I start app variables values are set in onCreate and while using app in activities I am changing values of varables. When I exit app and start it again I am getting old values, the last values of variables set in activities. Thats mean onCreate of Application not running on starting app again. This is code in onCreate method of Application class.

@Override
    public void onCreate() {
        super.onCreate();
        application = this;
        category = 12;
        subCategory =22;
    }

It looks like old application object is still in memory and it is not calling onCreate on starting app 2nd time.

What is need to be done so that onCreate of application class run again or where to initialize variables in application class so that code runs everytime.

like image 270
anujprashar Avatar asked Nov 13 '22 11:11

anujprashar


2 Answers

please declare your application class name in manifest file. like below

<application
    android:name="com.tt.app.TTApplication"
    android:label="@string/app_name"
like image 82
Narender Gusain Avatar answered Nov 16 '22 04:11

Narender Gusain


In the Application class, the onCreate() method is called only if the process was ended when you exited the application. Usually the process is stopped when the system needs memory or if you exit the app using the back button instead of the home button. However, you cannot rely on it being terminated.

However, the right way of passing parameters between activities are intents or preferences. In your case, I have the feeling that preferences is the way to go.

If you really want to kill your process when exiting the application, you can call System.exit(0); when the user presses the back key on your first activity. This is definitely not recommended since it means fighting against the way the Android OS works and might cause problems.

More on this here: Is quitting an application frowned upon?

like image 38
Daniel Avatar answered Nov 16 '22 02:11

Daniel