Monday, January 19, 2015

how to make a application wide locale change in Andorid

Today, While testing on Arabic language I found that app cannot query data from the database due to Arabic numeral system being different from English. So, I decided to enforce English on whole language

In the Manifest,

 <application
        android:name="MyApplication" >

Code:

public class MyApplication extends Application {
  @Override
  public void onCreate()
  {
    switchLocale()
    super.onCreate();
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      switchLocale();
  }
}
public static void switchLocale(Context context) {
    try {
          Locale currentLocale = Locale.getDefault();
       
          if(currentLocale != null) {
              if (currentLocale != Locale.US || currentLocale != Locale.UK) {
                  final String languageToLoad  = "en";
                  Locale locale = new Locale(languageToLoad);
                  Locale.setDefault(locale);
               
                  Configuration config = new Configuration();
                  config.locale = locale;
                  context.getResources().updateConfiguration(config, null);
              }
          }
      } catch (Throwable e) {
       
      }
}

No comments:

Post a Comment