Search code examples
javaandroidandroid-activitylocaleoncreate

onCreate is ran twice because I set locale at app launch?


I have been wondering for a while why my onCreate method is run twice and have now found out that it has to do with me setting the locale of the app at launch... My question is, is it necessary for it to run twice or not?

This is the code that makes onCreate run twice:

 /*Sets the language of the application and also returns the integer value of selected language*/
protected Integer setLanguage() {
    String lang = prefs.getString("language-key","0");
    Integer language = Integer.parseInt(lang);
    Configuration config = context.getResources().getConfiguration();

    if (!decideLang(language).equals("") && !config.locale.getLanguage().equals(decideLang(language))) {
        setLocale(decideLang(language));
    }
    return language;
}

/*Sets the locale*/
private void setLocale(String lang) {
    ((Activity) context).recreate();
    Locale myLocale = new Locale(lang);
    Resources res = context.getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
}

The integer that the setLanguage method returns is later used to determine what URL to use in a later stage but I have come to realize that is not important for my question.

My question is, WHY does onCreate need to run twice because of this code?


Solution

  • ((Activity) context).recreate();, as it states on the tin, recreates the Activity, so onCreate() is, of course, going to be called twice.

    (From comments)