Java Code Examples for java.util.Locale.getLanguage()

The following are Jave code examples for showing how to use getLanguage() of the java.util.Locale class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: MyResourcesAsia.java   View Source Code Vote up 6 votes
@Override
protected String toBundleName(String baseName, Locale locale) {
    // Convert baseName to its properties resource name for the given locale
    // e.g., jdk.test.resources.MyResources -> jdk/test/resources/asia/MyResources_zh_TW
    StringBuilder sb = new StringBuilder();
    int index = baseName.lastIndexOf('.');
    sb.append(baseName.substring(0, index))
        .append(".asia")
        .append(baseName.substring(index));
    String lang = locale.getLanguage();
    if (!lang.isEmpty()) {
        sb.append('_').append(lang);
        String country = locale.getCountry();
        if (!country.isEmpty()) {
            sb.append('_').append(country);
        }
    }
    return sb.toString();
}
 
Example 2
Project: PlusGram   File: LocaleController.java   View Source Code Vote up 6 votes
public void recreateFormatters() {
    Locale locale = currentLocale;
    if (locale == null) {
        locale = Locale.getDefault();
    }
    String lang = locale.getLanguage();
    if (lang == null) {
        lang = "en";
    }
    isRTL = (lang.toLowerCase().equals("ar") || lang.equalsIgnoreCase("fa") || lang.equalsIgnoreCase("fa_Fa")) ;


    nameDisplayOrder = lang.toLowerCase().equals("ko") ? 2 : 1;

    formatterMonth = createFormatter(locale, getStringInternal("formatterMonth", R.string.formatterMonth), "dd MMM");
    formatterYear = createFormatter(locale, getStringInternal("formatterYear", R.string.formatterYear), "dd.MM.yy");
    formatterYearMax = createFormatter(locale, getStringInternal("formatterYearMax", R.string.formatterYearMax), "dd.MM.yyyy");
    chatDate = createFormatter(locale, getStringInternal("chatDate", R.string.chatDate), "d MMMM");
    chatFullDate = createFormatter(locale, getStringInternal("chatFullDate", R.string.chatFullDate), "d MMMM yyyy");
    formatterWeek = createFormatter(locale, getStringInternal("formatterWeek", R.string.formatterWeek), "EEE");
    formatterMonthYear = createFormatter(locale, getStringInternal("formatterMonthYear", R.string.formatterMonthYear), "MMMM yyyy");
    formatterDay = createFormatter(lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko") ? locale : Locale.US, is24HourFormat ? getStringInternal("formatterDay24H", R.string.formatterDay24H) : getStringInternal("formatterDay12H", R.string.formatterDay12H), is24HourFormat ? "HH:mm" : "h:mm a");
}
 
Example 3
Project: lazycat   File: Response.java   View Source Code Vote up 6 votes
/**
 * Called explicitly by user to set the Content-Language and the default
 * encoding
 */
public void setLocale(Locale locale) {

	if (locale == null) {
		return; // throw an exception?
	}

	// Save the locale for use by getLocale()
	this.locale = locale;

	// Set the contentLanguage for header output
	contentLanguage = locale.getLanguage();
	if ((contentLanguage != null) && (contentLanguage.length() > 0)) {
		String country = locale.getCountry();
		StringBuilder value = new StringBuilder(contentLanguage);
		if ((country != null) && (country.length() > 0)) {
			value.append('-');
			value.append(country);
		}
		contentLanguage = value.toString();
	}

}
 
Example 4
Project: jdk8u-jdk   File: LocaleDataTest.java   View Source Code Vote up 6 votes
/**
 * Changes baseName to its per-language package name and
 * calls the super class implementation. For example,
 * if the baseName is "sun.text.resources.FormatData" and locale is ja_JP,
 * the baseName is changed to "sun.text.resources.ja.FormatData". If
 * baseName contains "cldr", such as "sun.text.resources.cldr.FormatData",
 * the name is changed to "sun.text.resources.cldr.jp.FormatData".
 */
@Override
public String toBundleName(String baseName, Locale locale) {
    String newBaseName = baseName;
    String lang = locale.getLanguage();
    if (lang.length() > 0) {
        if (baseName.startsWith(UTIL_RESOURCES_PACKAGE)
            || baseName.startsWith(TEXT_RESOURCES_PACKAGE)) {
            // Assume the lengths are the same.
            if (UTIL_RESOURCES_PACKAGE.length()
                != TEXT_RESOURCES_PACKAGE.length()) {
                throw new InternalError("The resources package names have different lengths.");
            }
            int index = TEXT_RESOURCES_PACKAGE.length();
            if (baseName.indexOf(CLDR, index) > 0) {
                index += CLDR.length();
            }
            newBaseName = baseName.substring(0, index + 1) + lang
                              + baseName.substring(index);
        }
    }
    return super.toBundleName(newBaseName, locale);
}
 
Example 5
Project: fitnotifications   File: LocaleUtility.java   View Source Code Vote up 6 votes
/**
 * Fallback from the given locale name by removing the rightmost _-delimited
 * element. If there is none, return the root locale ("", "", ""). If this
 * is the root locale, return null. NOTE: The string "root" is not
 * recognized; do not use it.
 * 
 * @return a new Locale that is a fallback from the given locale, or null.
 */
public static Locale fallback(Locale loc) {

    // Split the locale into parts and remove the rightmost part
    String[] parts = new String[]
        { loc.getLanguage(), loc.getCountry(), loc.getVariant() };
    int i;
    for (i=2; i>=0; --i) {
        if (parts[i].length() != 0) {
            parts[i] = "";
            break;
        }
    }
    if (i<0) {
        return null; // All parts were empty
    }
    return new Locale(parts[0], parts[1], parts[2]);
}
 
Example 6
Project: letv   File: bt.java   View Source Code Vote up 6 votes
public static String[] n(Context context) {
    String[] strArr = new String[2];
    try {
        Locale y = y(context);
        if (y != null) {
            strArr[0] = y.getCountry();
            strArr[1] = y.getLanguage();
        }
        if (TextUtils.isEmpty(strArr[0])) {
            strArr[0] = "Unknown";
        }
        if (TextUtils.isEmpty(strArr[1])) {
            strArr[1] = "Unknown";
        }
    } catch (Throwable e) {
        bv.e(a, "error in getLocaleInfo", e);
    }
    return strArr;
}
 
Example 7
Project: Yapilcek   File: MonoPackageManager.java   View Source Code Vote up 5 votes
public static void LoadApplication (Context context, ApplicationInfo runtimePackage, String[] apks)
{
	synchronized (lock) {
		if (context instanceof android.app.Application) {
			Context = context;
		}
		if (!initialized) {
			android.content.IntentFilter timezoneChangedFilter  = new android.content.IntentFilter (
					android.content.Intent.ACTION_TIMEZONE_CHANGED
			);
			context.registerReceiver (new mono.android.app.NotifyTimeZoneChanges (), timezoneChangedFilter);
			
			System.loadLibrary("monodroid");
			Locale locale       = Locale.getDefault ();
			String language     = locale.getLanguage () + "-" + locale.getCountry ();
			String filesDir     = context.getFilesDir ().getAbsolutePath ();
			String cacheDir     = context.getCacheDir ().getAbsolutePath ();
			String dataDir      = getNativeLibraryPath (context);
			ClassLoader loader  = context.getClassLoader ();

			Runtime.init (
					language,
					apks,
					getNativeLibraryPath (runtimePackage),
					new String[]{
						filesDir,
						cacheDir,
						dataDir,
					},
					loader,
					new java.io.File (
						android.os.Environment.getExternalStorageDirectory (),
						"Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath (),
					MonoPackageManager_Resources.Assemblies,
					context.getPackageName ());
			
			mono.android.app.ApplicationRegistration.registerApplications ();
			
			initialized = true;
		}
	}
}
 
Example 8
Project: openjdk-jdk10   File: MyResourcesProvider.java   View Source Code Vote up 5 votes
private String toXMLName(String baseName, Locale locale) {
    StringBuilder sb = new StringBuilder(baseName.replace('.', '/'));
    String lang = locale.getLanguage();
    if (!lang.isEmpty()) {
        sb.append('_').append(lang);
        String country = locale.getCountry();
        if (!country.isEmpty()) {
            sb.append('_').append(country);
        }
    }
    return sb.append(".xml").toString();
}
 
Example 9
Project: oscm   File: LocalizedBillingResourceAssembler.java   View Source Code Vote up 5 votes
public static LocalizedBillingResource createPriceModelTag(Locale locale,
        UUID objectID, String priceModelTag) {
    LocalizedBillingResource localizedBillingresource = new LocalizedBillingResource(
            objectID, locale.getLanguage(),
            LocalizedBillingResourceType.PRICEMODEL_TAG);
    localizedBillingresource.setDataType(MediaType.TEXT_PLAIN);
    localizedBillingresource.setValue(priceModelTag.getBytes());
    if (priceModelTag.length() > 30) {
        logger.logWarn(
                Log4jLogger.SYSTEM_LOG,
                LogMessageIdentifier.WARN_TOO_MANY_CHARACTERS_FOR_PRICE_FROM_TAG);
    }
    return localizedBillingresource;
}
 
Example 10
Project: esup-ecandidat   File: I18nController.java   View Source Code Vote up 5 votes
/**
 * Renvoi la valeur d'un traduction (langue default si plus d'une traduction)
 * 
 * @param i18n
 * @param locale
 * @return la valeur d'un traduction par une locale
 */
public String getI18nTraduction(I18n i18n, Locale locale) {
	String codLangue = null;
	if (locale != null) {
		codLangue = locale.getLanguage();
	}
	return getI18nTraduction(i18n, codLangue);
}
 
Example 11
Project: OpenDiabetes   File: RefCapablePropertyResourceBundle.java   View Source Code Vote up 5 votes
private RefCapablePropertyResourceBundle(String baseName,
        PropertyResourceBundle wrappedBundle, ClassLoader loader) {
    this.baseName = baseName;
    this.wrappedBundle = wrappedBundle;
    Locale locale = wrappedBundle.getLocale();
    this.loader = loader;
    language = locale.getLanguage();
    country = locale.getCountry();
    variant = locale.getVariant();
    if (language.length() < 1) language = null;
    if (country.length() < 1) country = null;
    if (variant.length() < 1) variant = null;
}
 
Example 12
Project: smarti   File: StopwordlistConfiguration.java   View Source Code Vote up 5 votes
/**
 * The stopwords for the parsed language or <code>null</code> if none are defined
 * @param lang the {@link Local} representing the language or <code>null</code> to get the default stopwords
 * @return the stopwords or <code>null</code> if none are configured for this language
 */
public Map<String,Collection<String>> getStopwords(Locale lang){
    final String key = lang == null ? "default" : lang.getLanguage();
    final Map<String,Collection<String>> stopwords;
    if(stopwordLists.containsKey(key)){
        stopwords = stopwordLists.get(key);
    } else {
        stopwords = parseStopwords(stopword.get(key), lang);
        stopwordLists.put(key, stopwords); //no list for this language present
    }
    return stopwords;
}
 
Example 13
Project: AOSP-Kayboard-7.1.2   File: LanguageOnSpacebarUtils.java   View Source Code Vote up 5 votes
public static int getLanguageOnSpacebarFormatType(
        @Nonnull final RichInputMethodSubtype subtype) {
    if (subtype.isNoLanguage()) {
        return FORMAT_TYPE_FULL_LOCALE;
    }
    // Only this subtype is enabled and equals to the system locale.
    if (sEnabledSubtypes.size() < 2 && sIsSystemLanguageSameAsInputLanguage) {
        return FORMAT_TYPE_NONE;
    }
    final Locale locale = subtype.getLocale();
    if (locale == null) {
        return FORMAT_TYPE_NONE;
    }
    final String keyboardLanguage = locale.getLanguage();
    final String keyboardLayout = subtype.getKeyboardLayoutSetName();
    int sameLanguageAndLayoutCount = 0;
    for (final InputMethodSubtype ims : sEnabledSubtypes) {
        final String language = SubtypeLocaleUtils.getSubtypeLocale(ims).getLanguage();
        if (keyboardLanguage.equals(language) && keyboardLayout.equals(
                SubtypeLocaleUtils.getKeyboardLayoutSetName(ims))) {
            sameLanguageAndLayoutCount++;
        }
    }
    // Display full locale name only when there are multiple subtypes that have the same
    // locale and keyboard layout. Otherwise displaying language name is enough.
    return sameLanguageAndLayoutCount > 1 ? FORMAT_TYPE_FULL_LOCALE
            : FORMAT_TYPE_LANGUAGE_ONLY;
}
 
Example 14
Project: xlight_android_native   File: ShareMainFragment.java   View Source Code Vote up 5 votes
public boolean isZh() {
    Locale locale = getResources().getConfiguration().locale;
    String language = locale.getLanguage();
    if (language.endsWith("zh"))
        return true;
    else
        return false;
}
 
Example 15
Project: chromium-for-android-56-debug-video   File: PwsClientImpl.java   View Source Code Vote up 5 votes
/**
 * Get the language code for the default locales and prepend it to the Accept-Language string
 * if it isn't already present. The logic should match PrependToAcceptLanguagesIfNecessary in
 * chrome/browser/android/preferences/pref_service_bridge.cc
 * @param locales A comma separated string that represents a list of default locales.
 * @param acceptLanguages The default language list for the language of the user's locales.
 * @return An updated language list.
 */
@VisibleForTesting
static String prependToAcceptLanguagesIfNecessary(String locales, String acceptLanguages) {
    String localeStrings = locales + "," + acceptLanguages;
    String[] localeList = localeStrings.split(",");

    ArrayList<Locale> uniqueList = new ArrayList<>();
    for (String localeString : localeList) {
        Locale locale = LocaleUtils.forLanguageTag(localeString);
        if (uniqueList.contains(locale) || locale.getLanguage().isEmpty()) {
            continue;
        }
        uniqueList.add(locale);
    }

    // If language is not in the accept languages list, also add language code.
    // A language code should only be inserted after the last languageTag that
    // contains that language.
    // This will work with the IDS_ACCEPT_LANGUAGE localized strings bundled
    // with Chrome but may fail on arbitrary lists of language tags due to
    // differences in case and whitespace.
    HashSet<String> seenLanguages = new HashSet<>();
    ArrayList<String> outputList = new ArrayList<>();
    for (int i = uniqueList.size() - 1; i >= 0; i--) {
        Locale localeAdd = uniqueList.get(i);
        String languageAdd = localeAdd.getLanguage();
        String countryAdd = localeAdd.getCountry();

        if (!seenLanguages.contains(languageAdd)) {
            seenLanguages.add(languageAdd);
            outputList.add(languageAdd);
        }
        if (!countryAdd.isEmpty()) {
            outputList.add(LocaleUtils.toLanguageTag(localeAdd));
        }
    }
    Collections.reverse(outputList);
    return TextUtils.join(",", outputList);
}
 
Example 16
Project: oscm   File: SkinBean.java   View Source Code Vote up 5 votes
/**
 * Retrieves the content of the mpl stage from the brand service. If there
 * was no localized resource defined for the stage content, a default will
 * be returned. The locale used to retrieve the content is the locale of the
 * currently login user. If the access happens anonymously the browser
 * locale will be used.
 * 
 * @return returns the stage content for the current marketplace from the
 *         brand service depending on the local of the current user or
 *         browser locale.
 */
public String getMarketplaceStage() {
    String localeString = null;

    FacesContext fc = getFacesContext();

    VOUserDetails voUserDetails = BaseBean
            .getUserFromSessionWithoutException(fc);
    if (voUserDetails != null) {
        localeString = voUserDetails.getLocale();
    }

    if (localeString == null) {
        Locale locale = fc.getViewRoot().getLocale();
        localeString = locale.getLanguage();
    }

    marketplaceStage = getBrandManagementService().getMarketplaceStage(
            getMarketplaceId(), localeString);

    if (isEmpty(marketplaceStage)) {
        // No localized resource found for the mpl stage
        marketplaceStage = MessageFormat.format(MARKETPLACE_STAGE_DEFAULT,
                getRequestContextPath());
    }
    return marketplaceStage;
}
 
Example 17
Project: react-native-webrtc   File: WebRTCModule.java   View Source Code Vote up 4 votes
private String getCurrentLanguage(){
    Locale current = getReactApplicationContext().getResources().getConfiguration().locale;
    return current.getLanguage();
}
 
Example 18
Project: xlight_android_native   File: SplashActivity.java   View Source Code Vote up 4 votes
public void initView() {
        //实例化各个界面的布局对象
        LayoutInflater mLi = LayoutInflater.from(this);
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        view1 = mLi.inflate(R.layout.guide_page1, null);
        ImageView iv_one = (ImageView) view1.findViewById(R.id.iv_one);
        view2 = mLi.inflate(R.layout.guide_page2, null);
        ImageView iv_two = (ImageView) view2.findViewById(R.id.iv_two);
//      view3 = mLi.inflate(R.layout.guide_page3, null);
        view4 = mLi.inflate(R.layout.guide_page4, null);
        startBtn = (Button) view4.findViewById(R.id.startBtn);
        ImageView iv_three = (ImageView) view4.findViewById(R.id.iv_three);

        if (language.endsWith("zh")) {
            iv_one.setImageResource(R.drawable.xlight_zh_one);
            iv_two.setImageResource(R.drawable.xlight_zh_two);
            iv_three.setImageResource(R.drawable.xlight_zh_three);
            startBtn.setBackgroundResource(R.drawable.zh_go);
        } else {
            iv_one.setImageResource(R.drawable.xlight_en_one);
            iv_two.setImageResource(R.drawable.xlight_en_two);
            iv_three.setImageResource(R.drawable.xlight_en_three);
            startBtn.setBackgroundResource(R.drawable.go);
        }
//        Logger.e("language", language);
//    其中languag为语言码:
//    zh:汉语
//    en:英语
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转到主页面
//                Intent intent = new Intent(SplashActivity.this,MainActivity.class);
                startActivity(new Intent(SplashActivity.this, SlidingMenuMainActivity.class));
                SplashActivity.this.finish();
            }
        });

        // 实例化ViewPager
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        // 实例化ArrayList对象
        views = new ArrayList<View>();
        //将要分页显示的View装入数组中
        views.add(view1);
        views.add(view2);
//        views.add(view3);
        views.add(view4);
        // 实例化ViewPager适配器
        vpAdapter = new ViewPagerAdapter(views);
    }
 
Example 19
Project: Locator-CrossPlatform   File: MonoPackageManager.java   View Source Code Vote up 4 votes
public static void LoadApplication (Context context, ApplicationInfo runtimePackage, String[] apks)
{
	synchronized (lock) {
		if (context instanceof android.app.Application) {
			Context = context;
		}
		if (!initialized) {
			android.content.IntentFilter timezoneChangedFilter  = new android.content.IntentFilter (
					android.content.Intent.ACTION_TIMEZONE_CHANGED
			);
			context.registerReceiver (new mono.android.app.NotifyTimeZoneChanges (), timezoneChangedFilter);
			
			System.loadLibrary("monodroid");
			Locale locale       = Locale.getDefault ();
			String language     = locale.getLanguage () + "-" + locale.getCountry ();
			String filesDir     = context.getFilesDir ().getAbsolutePath ();
			String cacheDir     = context.getCacheDir ().getAbsolutePath ();
			String dataDir      = getNativeLibraryPath (context);
			ClassLoader loader  = context.getClassLoader ();

			Runtime.init (
					language,
					apks,
					getNativeLibraryPath (runtimePackage),
					new String[]{
						filesDir,
						cacheDir,
						dataDir,
					},
					loader,
					new java.io.File (
						android.os.Environment.getExternalStorageDirectory (),
						"Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath (),
					MonoPackageManager_Resources.Assemblies,
					context.getPackageName ());
			
			mono.android.app.ApplicationRegistration.registerApplications ();
			
			initialized = true;
		}
	}
}
 
Example 20
Project: oscm   File: LocalizerServiceBean.java   View Source Code Vote up 3 votes
/**
 * Construct a parent locale for the given locale in the following order (:
 * 
 * language, country, variant
 * 
 * language, country
 * 
 * language
 * 
 * defaultLanguage
 * 
 * @param locale
 *            The start locale.
 * @return The parent locale.
 */
private Locale getParentLocale(Locale locale) {
    if (locale.getVariant().length() == 0) {
        if (locale.getCountry().length() == 0) {
            if (locale.getLanguage().equals(defaultLocale.getLanguage())) {
                return new Locale("");
            }
            return new Locale(defaultLocale.getLanguage());
        } else {
            return new Locale(locale.getLanguage());
        }
    } else {
        return new Locale(locale.getLanguage(), locale.getCountry());
    }
}