Java Code Examples for android.text.TextUtils#split()

The following examples show how to use android.text.TextUtils#split() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SsaStyle.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the format info from a 'Format:' line in the [V4+ Styles] section.
 *
 * @return the parsed info, or null if {@code styleFormatLine} doesn't contain 'name'.
 */
@Nullable
public static Format fromFormatLine(String styleFormatLine) {
  int nameIndex = C.INDEX_UNSET;
  int alignmentIndex = C.INDEX_UNSET;
  String[] keys =
      TextUtils.split(styleFormatLine.substring(SsaDecoder.FORMAT_LINE_PREFIX.length()), ",");
  for (int i = 0; i < keys.length; i++) {
    switch (Util.toLowerInvariant(keys[i].trim())) {
      case "name":
        nameIndex = i;
        break;
      case "alignment":
        alignmentIndex = i;
        break;
    }
  }
  return nameIndex != C.INDEX_UNSET ? new Format(nameIndex, alignmentIndex, keys.length) : null;
}
 
Example 2
Source File: PersistentCookieStore.java    From hipda with GNU General Public License v2.0 6 votes vote down vote up
public PersistentCookieStore(Context context, String domain) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
    cookies = new HashMap<>();
    persistentDomain = domain;
    //将持久化的cookies缓存到内存中 即map cookies
    Map<String, ?> prefsMap = cookiePrefs.getAll();
    for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
        String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
        for (String name : cookieNames) {
            String encodedCookie = cookiePrefs.getString(name, null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    if (!cookies.containsKey(entry.getKey())) {
                        cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
                    }
                    cookies.get(entry.getKey()).put(name, decodedCookie);
                }
            }
        }
    }
}
 
Example 3
Source File: PersistentCookieStore.java    From ESeal with Apache License 2.0 6 votes vote down vote up
public PersistentCookieStore(Context context) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
    cookies = new HashMap<>();

    //将持久化的cookies缓存到内存中 即map cookies
    Map<String, ?> prefsMap = cookiePrefs.getAll();
    for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
        String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
        for (String name : cookieNames) {
            String encodedCookie = cookiePrefs.getString(name, null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    if (!cookies.containsKey(entry.getKey())) {
                        cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
                    }
                    cookies.get(entry.getKey()).put(name, decodedCookie);
                }
            }
        }
    }
}
 
Example 4
Source File: PreferencesCookieStore.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a persistent cookie store.
 */
public PreferencesCookieStore(Context context) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);
    cookies = new ConcurrentHashMap<String, Cookie>();

    // Load any previously stored cookies into the store
    String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
    if (storedCookieNames != null) {
        String[] cookieNames = TextUtils.split(storedCookieNames, ",");
        for (String name : cookieNames) {
            String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
            if (encodedCookie != null) {
                Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null) {
                    cookies.put(name, decodedCookie);
                }
            }
        }

        // Clear out expired cookies
        clearExpired(new Date());
    }
}
 
Example 5
Source File: PersistentCookieStore.java    From SmartChart with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a persistent cookie store.
 *
 * @param context Context to attach cookie store to
 */
public PersistentCookieStore(Context context) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
    cookies = new HashMap<>();

    // Load any previously stored cookies into the store
    Map<String, ?> prefsMap = cookiePrefs.getAll();
    for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
        if (entry.getValue() != null && !((String) entry.getValue()).startsWith(COOKIE_NAME_PREFIX)) {
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        if (!cookies.containsKey(entry.getKey()))
                            cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
                        cookies.get(entry.getKey()).put(name, decodedCookie);
                    }
                }
            }

        }
    }
}
 
Example 6
Source File: KnifeText.java    From Knife with Apache License 2.0 5 votes vote down vote up
protected void bulletInvalid() {
    String[] lines = TextUtils.split(getEditableText().toString(), "\n");

    for (int i = 0; i < lines.length; i++) {
        if (!containBullet(i)) {
            continue;
        }

        int lineStart = 0;
        for (int j = 0; j < i; j++) {
            lineStart = lineStart + lines[j].length() + 1;
        }

        int lineEnd = lineStart + lines[i].length();
        if (lineStart >= lineEnd) {
            continue;
        }

        int bulletStart = 0;
        int bulletEnd = 0;
        if (lineStart <= getSelectionStart() && getSelectionEnd() <= lineEnd) {
            bulletStart = lineStart;
            bulletEnd = lineEnd;
        } else if (getSelectionStart() <= lineStart && lineEnd <= getSelectionEnd()) {
            bulletStart = lineStart;
            bulletEnd = lineEnd;
        }

        if (bulletStart < bulletEnd) {
            BulletSpan[] spans = getEditableText().getSpans(bulletStart, bulletEnd, BulletSpan.class);
            for (BulletSpan span : spans) {
                getEditableText().removeSpan(span);
            }
        }
    }
}
 
Example 7
Source File: PickerFragment.java    From HypFacebook with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
void readSelectionFromBundle(Bundle inBundle, String key) {
    if (inBundle != null) {
        String ids = inBundle.getString(key);
        if (ids != null) {
            String[] splitIds = TextUtils.split(ids, ",");
            selectedIds.clear();
            Collections.addAll(selectedIds, splitIds);
        }
    }
}
 
Example 8
Source File: DynamicLanguage.java    From deltachat-android with GNU General Public License v3.0 5 votes vote down vote up
public static Locale getSelectedLocale(Context context) {
  String language[] = TextUtils.split(Prefs.getLanguage(context), "_");

  if (language[0].equals(DEFAULT)) {
    return getDefaultLocale();
  } else if (language.length == 2) {
    return new Locale(language[0], language[1]);
  } else {
    return new Locale(language[0]);
  }
}
 
Example 9
Source File: AppRestrictionEnforcerFragment.java    From android-AppRestrictionEnforcer with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the restrictions for the AppRestrictionSchema sample.
 *
 * @param activity The activity
 */
private void loadRestrictions(Activity activity) {
    RestrictionsManager manager =
            (RestrictionsManager) activity.getSystemService(Context.RESTRICTIONS_SERVICE);
    List<RestrictionEntry> restrictions =
            manager.getManifestRestrictions(Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA);
    SharedPreferences prefs = activity.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
    for (RestrictionEntry restriction : restrictions) {
        String key = restriction.getKey();
        if (RESTRICTION_KEY_SAY_HELLO.equals(key)) {
            updateCanSayHello(prefs.getBoolean(RESTRICTION_KEY_SAY_HELLO,
                    restriction.getSelectedState()));
        } else if (RESTRICTION_KEY_MESSAGE.equals(key)) {
            updateMessage(prefs.getString(RESTRICTION_KEY_MESSAGE,
                    restriction.getSelectedString()));
        } else if (RESTRICTION_KEY_NUMBER.equals(key)) {
            updateNumber(prefs.getInt(RESTRICTION_KEY_NUMBER,
                    restriction.getIntValue()));
        } else if (RESTRICTION_KEY_RANK.equals(key)) {
            updateRank(activity, restriction.getChoiceValues(),
                    prefs.getString(RESTRICTION_KEY_RANK, restriction.getSelectedString()));
        } else if (RESTRICTION_KEY_APPROVALS.equals(key)) {
            updateApprovals(activity, restriction.getChoiceValues(),
                    TextUtils.split(prefs.getString(RESTRICTION_KEY_APPROVALS,
                                    TextUtils.join(DELIMETER,
                                            restriction.getAllSelectedStrings())),
                            DELIMETER));
        } else if (BUNDLE_SUPPORTED && RESTRICTION_KEY_ITEMS.equals(key)) {
            String itemsString = prefs.getString(RESTRICTION_KEY_ITEMS, "");
            HashMap<String, String> items = new HashMap<>();
            for (String itemString : TextUtils.split(itemsString, DELIMETER)) {
                String[] strings = itemString.split(SEPARATOR, 2);
                items.put(strings[0], strings[1]);
            }
            updateItems(activity, items);
        }
    }
}
 
Example 10
Source File: ResponseData.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Parses response string into ResponseData.
 *
 * @param responseData response data string
 * @return ResponseData object
 * @throws IllegalArgumentException upon parsing error
 */
public static ResponseData parse(String responseData) {
    // Must parse out main response data and response-specific data.
    int index = responseData.indexOf(':');
    String mainData, extraData;
    if (-1 == index) {
        mainData = responseData;
        extraData = "";
    } else {
        mainData = responseData.substring(0, index);
        extraData = index >= responseData.length() ? "" : responseData.substring(index + 1);
    }

    String[] fields = TextUtils.split(mainData, Pattern.quote("|"));
    if (fields.length < 6) {
        throw new IllegalArgumentException("Wrong number of fields.");
    }

    ResponseData data = new ResponseData();
    data.extra = extraData;
    data.responseCode = Integer.parseInt(fields[0]);
    data.nonce = Integer.parseInt(fields[1]);
    data.packageName = fields[2];
    data.versionCode = fields[3];
    // Application-specific user identifier.
    data.userId = fields[4];
    data.timestamp = Long.parseLong(fields[5]);

    return data;
}
 
Example 11
Source File: AppRestrictionEnforcerFragment.java    From enterprise-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the restrictions for the AppRestrictionSchema sample.
 *
 * @param activity The activity
 */
private void loadRestrictions(Activity activity) {
    RestrictionsManager manager =
            (RestrictionsManager) activity.getSystemService(Context.RESTRICTIONS_SERVICE);
    List<RestrictionEntry> restrictions =
            manager.getManifestRestrictions(Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA);
    SharedPreferences prefs = activity.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
    for (RestrictionEntry restriction : restrictions) {
        String key = restriction.getKey();
        if (RESTRICTION_KEY_SAY_HELLO.equals(key)) {
            updateCanSayHello(prefs.getBoolean(RESTRICTION_KEY_SAY_HELLO,
                    restriction.getSelectedState()));
        } else if (RESTRICTION_KEY_MESSAGE.equals(key)) {
            updateMessage(prefs.getString(RESTRICTION_KEY_MESSAGE,
                    restriction.getSelectedString()));
        } else if (RESTRICTION_KEY_NUMBER.equals(key)) {
            updateNumber(prefs.getInt(RESTRICTION_KEY_NUMBER,
                    restriction.getIntValue()));
        } else if (RESTRICTION_KEY_RANK.equals(key)) {
            updateRank(activity, restriction.getChoiceValues(),
                    prefs.getString(RESTRICTION_KEY_RANK, restriction.getSelectedString()));
        } else if (RESTRICTION_KEY_APPROVALS.equals(key)) {
            updateApprovals(activity, restriction.getChoiceValues(),
                    TextUtils.split(prefs.getString(RESTRICTION_KEY_APPROVALS,
                                    TextUtils.join(DELIMETER,
                                            restriction.getAllSelectedStrings())),
                            DELIMETER));
        } else if (BUNDLE_SUPPORTED && RESTRICTION_KEY_ITEMS.equals(key)) {
            String itemsString = prefs.getString(RESTRICTION_KEY_ITEMS, "");
            HashMap<String, String> items = new HashMap<>();
            for (String itemString : TextUtils.split(itemsString, DELIMETER)) {
                String[] strings = itemString.split(SEPARATOR, 2);
                items.put(strings[0], strings[1]);
            }
            updateItems(activity, items);
        }
    }
}
 
Example 12
Source File: ResponseData.java    From play-licensing with Apache License 2.0 5 votes vote down vote up
/**
 * Parses response string into ResponseData.
 *
 * @param responseData response data string
 * @throws IllegalArgumentException upon parsing error
 * @return ResponseData object
 */
public static ResponseData parse(String responseData) {
    // Must parse out main response data and response-specific data.
    int index = responseData.indexOf(':');
    String mainData, extraData;
    if (-1 == index) {
        mainData = responseData;
        extraData = "";
    } else {
        mainData = responseData.substring(0, index);
        extraData = index >= responseData.length() ? "" : responseData.substring(index + 1);
    }

    String[] fields = TextUtils.split(mainData, Pattern.quote("|"));
    if (fields.length < 6) {
        throw new IllegalArgumentException("Wrong number of fields.");
    }

    ResponseData data = new ResponseData();
    data.extra = extraData;
    data.responseCode = Integer.parseInt(fields[0]);
    data.nonce = Integer.parseInt(fields[1]);
    data.packageName = fields[2];
    data.versionCode = fields[3];
    // Application-specific user identifier.
    data.userId = fields[4];
    data.timestamp = Long.parseLong(fields[5]);

    return data;
}
 
Example 13
Source File: AppPreferences.java    From Chorus-RF-Laptimer with MIT License 5 votes vote down vote up
private static String[] getArrayFromStringPreference(String prefName) {
    String value = AppState.getInstance().preferences.getString(prefName, "");
    if (value.equals("")) {
        return new String[0];
    }
    return TextUtils.split(value, STRING_ITEMS_DELIMITER);
}
 
Example 14
Source File: KnifeText.java    From Knife with Apache License 2.0 5 votes vote down vote up
protected void quoteValid() {
    String[] lines = TextUtils.split(getEditableText().toString(), "\n");

    for (int i = 0; i < lines.length; i++) {
        if (containQuote(i)) {
            continue;
        }

        int lineStart = 0;
        for (int j = 0; j < i; j++) {
            lineStart = lineStart + lines[j].length() + 1; // \n
        }

        int lineEnd = lineStart + lines[i].length();
        if (lineStart >= lineEnd) {
            continue;
        }

        int quoteStart = 0;
        int quoteEnd = 0;
        if (lineStart <= getSelectionStart() && getSelectionEnd() <= lineEnd) {
            quoteStart = lineStart;
            quoteEnd = lineEnd;
        } else if (getSelectionStart() <= lineStart && lineEnd <= getSelectionEnd()) {
            quoteStart = lineStart;
            quoteEnd = lineEnd;
        }

        if (quoteStart < quoteEnd) {
            getEditableText().setSpan(new KnifeQuoteSpan(quoteColor, quoteStripeWidth, quoteGapWidth), quoteStart, quoteEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}
 
Example 15
Source File: ResponseData.java    From Klyph with MIT License 5 votes vote down vote up
/**
 * Parses response string into ResponseData.
 *
 * @param responseData response data string
 * @throws IllegalArgumentException upon parsing error
 * @return ResponseData object
 */
public static ResponseData parse(String responseData) {
    // Must parse out main response data and response-specific data.
	int index = responseData.indexOf(':');
	String mainData, extraData;
	if ( -1 == index ) {
		mainData = responseData;
		extraData = "";
	} else {
		mainData = responseData.substring(0, index);
		extraData = index >= responseData.length() ? "" : responseData.substring(index+1);
	}

    String [] fields = TextUtils.split(mainData, Pattern.quote("|"));
    if (fields.length < 6) {
        throw new IllegalArgumentException("Wrong number of fields.");
    }

    ResponseData data = new ResponseData();
    data.extra = extraData;
    data.responseCode = Integer.parseInt(fields[0]);
    data.nonce = Integer.parseInt(fields[1]);
    data.packageName = fields[2];
    data.versionCode = fields[3];
    // Application-specific user identifier.
    data.userId = fields[4];
    data.timestamp = Long.parseLong(fields[5]);

    return data;
}
 
Example 16
Source File: MessageHeaderParent.java    From zulip-android with Apache License 2.0 5 votes vote down vote up
public Person[] getRecipients(ZulipApp app) {
    Person[] recipientsCache;
    String[] ids = TextUtils.split(this.getId(), ",");
    recipientsCache = new Person[ids.length];
    for (int i = 0; i < ids.length; i++) {
        try {
            recipientsCache[i] = Person.getById(app,
                    Integer.parseInt(ids[i]));
        } catch (NumberFormatException e) {
            ZLog.logException(e);
        }
    }
    return recipientsCache;
}
 
Example 17
Source File: TinyDB.java    From IdeaTrackerPlus with MIT License 5 votes vote down vote up
/**
 * Get parsed ArrayList of Double from SharedPreferences at 'key'
 *
 * @param key SharedPreferences key
 * @return ArrayList of Double
 */
public ArrayList<Double> getListDouble(String key) {
    String[] myList = TextUtils.split(preferences.getString(key, ""), "‚‗‚");
    ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
    ArrayList<Double> newList = new ArrayList<Double>();

    for (String item : arrayToList)
        newList.add(Double.parseDouble(item));

    return newList;
}
 
Example 18
Source File: DictionaryProvider.java    From Android-Keyboard with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the metadata and returns the collection of dictionaries for a given locale.
 *
 * Word list IDs are expected to be in the form category:manual_id. This method
 * will select only one word list for each category: the one with the most specific
 * locale matching the locale specified in the URI. The manual id serves only to
 * distinguish a word list from another for the purpose of updating, and is arbitrary
 * but may not contain a colon.
 *
 * @param clientId the ID of the client requesting the list
 * @param locale the locale for which we want the list, as a String
 * @return a collection of ids. It is guaranteed to be non-null, but may be empty.
 */
private Collection<WordListInfo> getDictionaryWordListsForLocale(final String clientId,
        final String locale) {
    final Context context = getContext();
    final Cursor results =
            MetadataDbHelper.queryInstalledOrDeletingOrAvailableDictionaryMetadata(context,
                    clientId);
    if (null == results) {
        return Collections.<WordListInfo>emptyList();
    }
    try {
        final HashMap<String, WordListInfo> dicts = new HashMap<>();
        final int idIndex = results.getColumnIndex(MetadataDbHelper.WORDLISTID_COLUMN);
        final int localeIndex = results.getColumnIndex(MetadataDbHelper.LOCALE_COLUMN);
        final int localFileNameIndex =
                results.getColumnIndex(MetadataDbHelper.LOCAL_FILENAME_COLUMN);
        final int rawChecksumIndex =
                results.getColumnIndex(MetadataDbHelper.RAW_CHECKSUM_COLUMN);
        final int statusIndex = results.getColumnIndex(MetadataDbHelper.STATUS_COLUMN);
        if (results.moveToFirst()) {
            do {
                final String wordListId = results.getString(idIndex);
                if (TextUtils.isEmpty(wordListId)) continue;
                final String[] wordListIdArray =
                        TextUtils.split(wordListId, ID_CATEGORY_SEPARATOR);
                final String wordListCategory;
                if (2 == wordListIdArray.length) {
                    // This is at the category:manual_id format.
                    wordListCategory = wordListIdArray[0];
                    // We don't need to read wordListIdArray[1] here, because it's irrelevant to
                    // word list selection - it's just a name we use to identify which data file
                    // is a newer version of which word list. We do however return the full id
                    // string for each selected word list, so in this sense we are 'using' it.
                } else {
                    // This does not contain a colon, like the old format does. Old-format IDs
                    // always point to main dictionaries, so we force the main category upon it.
                    wordListCategory = UpdateHandler.MAIN_DICTIONARY_CATEGORY;
                }
                final String wordListLocale = results.getString(localeIndex);
                final String wordListLocalFilename = results.getString(localFileNameIndex);
                final String wordListRawChecksum = results.getString(rawChecksumIndex);
                final int wordListStatus = results.getInt(statusIndex);
                // Test the requested locale against this wordlist locale. The requested locale
                // has to either match exactly or be more specific than the dictionary - a
                // dictionary for "en" would match both a request for "en" or for "en_US", but a
                // dictionary for "en_GB" would not match a request for "en_US". Thus if all
                // three of "en" "en_US" and "en_GB" dictionaries are installed, a request for
                // "en_US" would match "en" and "en_US", and a request for "en" only would only
                // match the generic "en" dictionary. For more details, see the documentation
                // for LocaleUtils#getMatchLevel.
                final int matchLevel = LocaleUtils.getMatchLevel(wordListLocale, locale);
                if (!LocaleUtils.isMatch(matchLevel)) {
                    // The locale of this wordlist does not match the required locale.
                    // Skip this wordlist and go to the next.
                    continue;
                }
                if (MetadataDbHelper.STATUS_INSTALLED == wordListStatus) {
                    // If the file does not exist, it has been deleted and the IME should
                    // already have it. Do not return it. However, this only applies if the
                    // word list is INSTALLED, for if it is DELETING we should return it always
                    // so that Android Keyboard can perform the actual deletion.
                    final File f = getContext().getFileStreamPath(wordListLocalFilename);
                    if (!f.isFile()) {
                        continue;
                    }
                } else if (MetadataDbHelper.STATUS_AVAILABLE == wordListStatus) {
                    // The locale is the id for the main dictionary.
                    UpdateHandler.installIfNeverRequested(context, clientId, wordListId);
                    continue;
                }
                final WordListInfo currentBestMatch = dicts.get(wordListCategory);
                if (null == currentBestMatch
                        || currentBestMatch.mMatchLevel < matchLevel) {
                    dicts.put(wordListCategory, new WordListInfo(wordListId, wordListLocale,
                            wordListRawChecksum, matchLevel));
                }
            } while (results.moveToNext());
        }
        return Collections.unmodifiableCollection(dicts.values());
    } finally {
        results.close();
    }
}
 
Example 19
Source File: DictionaryProvider.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the metadata and returns the collection of dictionaries for a given locale.
 *
 * Word list IDs are expected to be in the form category:manual_id. This method
 * will select only one word list for each category: the one with the most specific
 * locale matching the locale specified in the URI. The manual id serves only to
 * distinguish a word list from another for the purpose of updating, and is arbitrary
 * but may not contain a colon.
 *
 * @param clientId the ID of the client requesting the list
 * @param locale the locale for which we want the list, as a String
 * @return a collection of ids. It is guaranteed to be non-null, but may be empty.
 */
private Collection<WordListInfo> getDictionaryWordListsForLocale(final String clientId,
        final String locale) {
    final Context context = getContext();
    final Cursor results =
            MetadataDbHelper.queryInstalledOrDeletingOrAvailableDictionaryMetadata(context,
                    clientId);
    if (null == results) {
        return Collections.<WordListInfo>emptyList();
    }
    try {
        final HashMap<String, WordListInfo> dicts = new HashMap<>();
        final int idIndex = results.getColumnIndex(MetadataDbHelper.WORDLISTID_COLUMN);
        final int localeIndex = results.getColumnIndex(MetadataDbHelper.LOCALE_COLUMN);
        final int localFileNameIndex =
                results.getColumnIndex(MetadataDbHelper.LOCAL_FILENAME_COLUMN);
        final int rawChecksumIndex =
                results.getColumnIndex(MetadataDbHelper.RAW_CHECKSUM_COLUMN);
        final int statusIndex = results.getColumnIndex(MetadataDbHelper.STATUS_COLUMN);
        if (results.moveToFirst()) {
            do {
                final String wordListId = results.getString(idIndex);
                if (TextUtils.isEmpty(wordListId)) continue;
                final String[] wordListIdArray =
                        TextUtils.split(wordListId, ID_CATEGORY_SEPARATOR);
                final String wordListCategory;
                if (2 == wordListIdArray.length) {
                    // This is at the category:manual_id format.
                    wordListCategory = wordListIdArray[0];
                    // We don't need to read wordListIdArray[1] here, because it's irrelevant to
                    // word list selection - it's just a name we use to identify which data file
                    // is a newer version of which word list. We do however return the full id
                    // string for each selected word list, so in this sense we are 'using' it.
                } else {
                    // This does not contain a colon, like the old format does. Old-format IDs
                    // always point to main dictionaries, so we force the main category upon it.
                    wordListCategory = UpdateHandler.MAIN_DICTIONARY_CATEGORY;
                }
                final String wordListLocale = results.getString(localeIndex);
                final String wordListLocalFilename = results.getString(localFileNameIndex);
                final String wordListRawChecksum = results.getString(rawChecksumIndex);
                final int wordListStatus = results.getInt(statusIndex);
                // Test the requested locale against this wordlist locale. The requested locale
                // has to either match exactly or be more specific than the dictionary - a
                // dictionary for "en" would match both a request for "en" or for "en_US", but a
                // dictionary for "en_GB" would not match a request for "en_US". Thus if all
                // three of "en" "en_US" and "en_GB" dictionaries are installed, a request for
                // "en_US" would match "en" and "en_US", and a request for "en" only would only
                // match the generic "en" dictionary. For more details, see the documentation
                // for LocaleUtils#getMatchLevel.
                final int matchLevel = LocaleUtils.getMatchLevel(wordListLocale, locale);
                if (!LocaleUtils.isMatch(matchLevel)) {
                    // The locale of this wordlist does not match the required locale.
                    // Skip this wordlist and go to the next.
                    continue;
                }
                if (MetadataDbHelper.STATUS_INSTALLED == wordListStatus) {
                    // If the file does not exist, it has been deleted and the IME should
                    // already have it. Do not return it. However, this only applies if the
                    // word list is INSTALLED, for if it is DELETING we should return it always
                    // so that Android Keyboard can perform the actual deletion.
                    final File f = getContext().getFileStreamPath(wordListLocalFilename);
                    if (!f.isFile()) {
                        continue;
                    }
                } else if (MetadataDbHelper.STATUS_AVAILABLE == wordListStatus) {
                    // The locale is the id for the main dictionary.
                    UpdateHandler.installIfNeverRequested(context, clientId, wordListId);
                    continue;
                }
                final WordListInfo currentBestMatch = dicts.get(wordListCategory);
                if (null == currentBestMatch
                        || currentBestMatch.mMatchLevel < matchLevel) {
                    dicts.put(wordListCategory, new WordListInfo(wordListId, wordListLocale,
                            wordListRawChecksum, matchLevel));
                }
            } while (results.moveToNext());
        }
        return Collections.unmodifiableCollection(dicts.values());
    } finally {
        results.close();
    }
}
 
Example 20
Source File: CreditCardBaseTextWatcher.java    From credit_card_lib with MIT License 4 votes vote down vote up
protected void insertSpace(Editable editable, int index, char ch) {
    if (Character.isDigit(ch) && TextUtils.split(editable.toString(), String.valueOf(SPACE)).length <= 3) {
        mIsChangedInside = true;
        editable.insert(index, String.valueOf(SPACE));
    }
}