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

The following examples show how to use android.text.TextUtils#join() . 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: SelectEntriesActivity.java    From Aegis with GNU General Public License v3.0 6 votes vote down vote up
private void showDetailedErrorDialog(List<DatabaseImporterEntryException> errors) {
    List<String> messages = new ArrayList<>();
    for (DatabaseImporterEntryException e : errors) {
        messages.add(e.getMessage());
    }

    String message = TextUtils.join("\n\n", messages);
    Dialogs.showSecureDialog(new AlertDialog.Builder(this)
            .setTitle(R.string.import_error_title)
            .setMessage(message)
            .setPositiveButton(android.R.string.ok, null)
            .setNeutralButton(android.R.string.copy, (dialog2, which2) -> {
                ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("text/plain", message);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(this, R.string.errors_copied, Toast.LENGTH_SHORT).show();
            })
            .create());
}
 
Example 2
Source File: WebPlayerView.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
private String extractFunction(String funcName) {
    try {
        String quote = Pattern.quote(funcName);
        Pattern funcPattern = Pattern.compile(String.format(Locale.US, "(?x)(?:function\\s+%s|[{;,]\\s*%s\\s*=\\s*function|var\\s+%s\\s*=\\s*function)\\s*\\(([^)]*)\\)\\s*\\{([^}]+)\\}", quote, quote, quote));
        Matcher matcher = funcPattern.matcher(jsCode);
        if (matcher.find()) {
            String group = matcher.group();
            if (!codeLines.contains(group)) {
                codeLines.add(group + ";");
            }
            buildFunction(matcher.group(1).split(","), matcher.group(2));
        }
    } catch (Exception e) {
        codeLines.clear();
        FileLog.e(e);
    }
    return TextUtils.join("", codeLines);
}
 
Example 3
Source File: AdditionalSubtypeUtils.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the subtype ID that is supposed to be compatible between different version of OSes.
 * <p>
 * From the compatibility point of view, it is important to keep subtype id predictable and
 * stable between different OSes. For this purpose, the calculation code in this method is
 * carefully chosen and then fixed. Treat the following code as no more or less than a
 * hash function. Each component to be hashed can be different from the corresponding value
 * that is used to instantiate {@link InputMethodSubtype} actually.
 * For example, you don't need to update <code>compatibilityExtraValueItems</code> in this
 * method even when we need to add some new extra values for the actual instance of
 * {@link InputMethodSubtype}.
 * </p>
 * @param localeString the locale string (e.g., "en_US").
 * @param keyboardLayoutSetName the keyboard layout set name (e.g., "dvorak").
 * @return a platform-version independent subtype ID.
 * @see #getPlatformVersionDependentExtraValue(String, String, boolean, boolean)
 */
private static int getPlatformVersionIndependentSubtypeId(final String localeString,
        final String keyboardLayoutSetName) {
    // For compatibility reasons, we concatenate the extra values in the following order.
    // - KeyboardLayoutSet
    // - AsciiCapable
    // - UntranslatableReplacementStringInSubtypeName
    // - EmojiCapable
    // - isAdditionalSubtype
    final ArrayList<String> compatibilityExtraValueItems = new ArrayList<>();
    compatibilityExtraValueItems.add(KEYBOARD_LAYOUT_SET + "=" + keyboardLayoutSetName);
    compatibilityExtraValueItems.add(ASCII_CAPABLE);
    if (SubtypeLocaleUtils.isExceptionalLocale(localeString)) {
        compatibilityExtraValueItems.add(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME + "=" +
                SubtypeLocaleUtils.getKeyboardLayoutSetDisplayName(keyboardLayoutSetName));
    }
    compatibilityExtraValueItems.add(EMOJI_CAPABLE);
    compatibilityExtraValueItems.add(IS_ADDITIONAL_SUBTYPE);
    final String compatibilityExtraValues = TextUtils.join(",", compatibilityExtraValueItems);
    return Arrays.hashCode(new Object[] {
            localeString,
            KEYBOARD_MODE,
            compatibilityExtraValues,
            false /* isAuxiliary */,
            false /* overrideImplicitlyEnabledSubtype */ });
}
 
Example 4
Source File: FirebaseApp.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the instance identified by the unique name, or throws if it does not exist.
 *
 * @param name represents the name of the {@link FirebaseApp} instance.
 * @throws IllegalStateException if the {@link FirebaseApp} was not initialized, either via {@link
 *     #initializeApp(Context, FirebaseOptions, String)}.
 */
@NonNull
public static FirebaseApp getInstance(@NonNull String name) {
  synchronized (LOCK) {
    FirebaseApp firebaseApp = INSTANCES.get(normalize(name));
    if (firebaseApp != null) {
      return firebaseApp;
    }

    List<String> availableAppNames = getAllAppNames();
    String availableAppNamesMessage;
    if (availableAppNames.isEmpty()) {
      availableAppNamesMessage = "";
    } else {
      availableAppNamesMessage =
          "Available app names: " + TextUtils.join(", ", availableAppNames);
    }
    String errorMessage =
        String.format(
            "FirebaseApp with name %s doesn't exist. %s", name, availableAppNamesMessage);
    throw new IllegalStateException(errorMessage);
  }
}
 
Example 5
Source File: BaseCompRouter.java    From JIMU with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verifyUri(Uri uri) {
    if (UIRouter.getLogger().isMonitorMode()) { // monitor log for developer
        UIRouter.getLogger().monitor("verify for: " + UriUtils.toSafeString(uri) +
                " in " + getClass().getSimpleName() + " ;host is: " + getHost());
    }

    if (uri == null)
        return false;
    String host = uri.getHost();
    if (!getHost().equals(host)) {
        return false;
    }
    if (!hasInitMap) {
        initMap();
    }
    List<String> pathSegments = uri.getPathSegments();
    String path = "/" + TextUtils.join("/", pathSegments);
    return routeMapper.containsKey(path);
}
 
Example 6
Source File: DetailActivity.java    From android-popular-movies-app with Apache License 2.0 5 votes vote down vote up
/**
 * Define the behavior for onInformationSelected
 * @param movieDetails The movie details contains information, such as budget, genre, runtime,
 *                    revenue, status, vote count, credits.
 */
@Override
public void onInformationSelected(MovieDetails movieDetails) {
    // Hide the loading indicator
    mDetailBinding.pbDetailLoadingIndicator.setVisibility(View.GONE);

    // As soon as the loading indicator is gone, show release year
    showReleaseYear();

    // Get the runtime of the movie from MovieDetails object
    int runtime = movieDetails.getRuntime();
    // Convert Minutes to Hours and Minutes (e.g. "118" -> "1h 58m") and set the runtime to the TextView
    mDetailBinding.tvRuntime.setText(FormatUtils.formatTime(this, runtime));

    // Get the genre of the movie from MovieDetails
    List<Genre> genres = movieDetails.getGenres();
    // Create an empty arrayList
    List<String> genresStrList = new ArrayList<>();
    // Iterate through the list of genres, and add genre name to the list of strings
    for (int i = 0; i < genres.size(); i++) {
        Genre genre = genres.get(i);
        // Get the genre name from the genre at ith position
        String genreName = genre.getGenreName();
        // Add genre name to the list of strings
        genresStrList.add(genreName);
    }
    // Join a string using a delimiter
    String genreStr = TextUtils.join(getString(R.string.delimiter_comma), genresStrList);
    // Display the genre
    mDetailBinding.tvGenre.setText(genreStr);
}
 
Example 7
Source File: VKHttpClient.java    From cordova-social-vk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns prepared http query like k1=v1&k2=v2...
 *
 * @return string presentation of http query
 * @throws UnsupportedEncodingException
 */
public String getQuery() throws UnsupportedEncodingException {
    if (this.parameters == null) {
        return null;
    }

    ArrayList<String> params = new ArrayList<>(this.parameters.size());
    for (Pair<String, String> pair : this.parameters) {
        if (pair.first == null || pair.second == null) {
            continue;
        }
        params.add(String.format("%s=%s", URLEncoder.encode(pair.first, sDefaultStringEncoding), URLEncoder.encode(pair.second, sDefaultStringEncoding)));
    }
    return TextUtils.join("&", params);
}
 
Example 8
Source File: AccountFilter.java    From fingen with Apache License 2.0 5 votes vote down vote up
@Override
public String saveToString() {
    if (!mAccountIdSet.isEmpty()) {
        return TextUtils.join("@", mAccountIdSet);
    } else {
        return "empty";
    }
}
 
Example 9
Source File: SqliteDatabaseImpl.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
void onFinishMaintain() {
    c.close();

    if (!needRemoveId.isEmpty()) {
        String args = TextUtils.join(", ", needRemoveId);
        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.d(this, "delete %s", args);
        }
        //noinspection ThrowFromFinallyBlock
        db.execSQL(FileDownloadUtils.formatString("DELETE FROM %s WHERE %s IN (%s);",
                TABLE_NAME, FileDownloadModel.ID, args));
        db.execSQL(FileDownloadUtils.formatString("DELETE FROM %s WHERE %s IN (%s);",
                CONNECTION_TABLE_NAME, ConnectionModel.ID, args));
    }
}
 
Example 10
Source File: ResponseData.java    From play-licensing with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    return TextUtils.join("|", new Object[] {
            responseCode, nonce, packageName, versionCode,
            userId, timestamp
    });
}
 
Example 11
Source File: SimpleWeibo.java    From SimpleWeibo with Apache License 2.0 5 votes vote down vote up
public SimpleWeibo initialize(Activity activity) {
    this.activity = activity;
    this.context = activity;
    this.appId = getMetaData(activity, APPLICATION_ID_PROPERTY);
    // null ? throw new IllegalArgumentException()
    this.redirectUrl = getMetaData(activity, REDIRECT_URL_PROPERTY);
    if (this.redirectUrl == null || "".equals(this.redirectUrl)) this.redirectUrl = DEFAULT_REDIRECT_URL;
    this.authInfo = new AuthInfo(context, appId, redirectUrl, TextUtils.join(",", Arrays.asList("email")));
    this.accessToken = AccessTokenPreferences.create(activity);

    ssoHandler = new SsoHandler(activity, authInfo);
    return this;
}
 
Example 12
Source File: PreferenceParser.java    From SearchPreference with MIT License 5 votes vote down vote up
private String readStringArray(@Nullable String s) {
    if (s == null) {
        return null;
    }
    if (s.startsWith("@")) {
        try {
            int id = Integer.parseInt(s.substring(1));
            String[] elements = context.getResources().getStringArray(id);
            return TextUtils.join(",", elements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return s;
}
 
Example 13
Source File: PerMessageDeflateExtension.java    From WebSocket-for-Android with Apache License 2.0 5 votes vote down vote up
public PerMessageDeflateExtension() {
    if (Build.VERSION.SDK_INT < 19) {
        _parameters = TextUtils.join("; ", new String[]{ EXTENSION, CLIENT_NO_CONTEXT_TAKEOVER });
    } else {
        _parameters = EXTENSION;
    }
    _compressed = false;
}
 
Example 14
Source File: NetworkSpace.java    From android with GNU General Public License v3.0 5 votes vote down vote up
String getIPv6Address() {
    if (BuildConfig.DEBUG) Assert.assertTrue (!isV4);
    BigInteger r = netAddress;
    if (r.compareTo(BigInteger.ZERO)==0 && networkMask==0)
        return "::";

    Vector<String> parts = new Vector<String>();
    while (r.compareTo(BigInteger.ZERO) == 1) {
        parts.add(0, String.format(Locale.US, "%x", r.mod(BigInteger.valueOf(0x10000)).longValue()));
        r = r.shiftRight(16);
    }

    return TextUtils.join(":", parts);
}
 
Example 15
Source File: Tracker.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
@NonNull
public String toString() {
    List sortedHosts = getSortedHosts();
    String hosts = "\n• " + TextUtils.join("\n• ", sortedHosts);

    if (TrackerList.necessaryTrackers.contains(name))
        return name + " (Unblocked)" + hosts;
    else {
        return name + hosts;
    }
}
 
Example 16
Source File: AuthorizationClient.java    From facebook-api-android-maven with Apache License 2.0 4 votes vote down vote up
static Result createErrorResult(AuthorizationRequest request, String errorType, String errorDescription,
        String errorCode) {
    String message = TextUtils.join(": ", Utility.asListNoNulls(errorType, errorDescription));
    return new Result(request, Code.ERROR, null, message, errorCode);
}
 
Example 17
Source File: BillingCache.java    From RxIAPv3 with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
	return TextUtils.join(", ", productIds);
}
 
Example 18
Source File: InCallCard.java    From CSipSimple with GNU General Public License v3.0 4 votes vote down vote up
private void updateElapsedTimer() {

        if (callInfo == null) {
            elapsedTime.stop();
            elapsedTime.setVisibility(VISIBLE);
            return;
        }

        elapsedTime.setBase(callInfo.getConnectStart());
        
        int sigSecureLevel = callInfo.getTransportSecureLevel();
        boolean isSecure = (callInfo.isMediaSecure() || sigSecureLevel > 0); 
        setVisibleWithFade(callSecureBar, isSecure);
        String secureMsg = "";
        if (isSecure) {
            List<String> secureTxtList = new ArrayList<String>();
            if(sigSecureLevel == SipCallSession.TRANSPORT_SECURE_TO_SERVER) {
                secureTxtList.add(getContext().getString(R.string.transport_secure_to_server));
            }else if(sigSecureLevel == SipCallSession.TRANSPORT_SECURE_FULL) {
                secureTxtList.add(getContext().getString(R.string.transport_secure_full));
            }
            if(callInfo.isMediaSecure()) {
                secureTxtList.add(callInfo.getMediaSecureInfo());
            }
            secureMsg = TextUtils.join("\r\n", secureTxtList);
        }
        callSecureText.setText(secureMsg);
        
        int state = callInfo.getCallState();
        switch (state) {
            case SipCallSession.InvState.INCOMING:
            case SipCallSession.InvState.CALLING:
            case SipCallSession.InvState.EARLY:
            case SipCallSession.InvState.CONNECTING:
                elapsedTime.setVisibility(GONE);
                break;
            case SipCallSession.InvState.CONFIRMED:
                Log.v(THIS_FILE, "we start the timer now ");
                if(callInfo.isLocalHeld()) {
                    elapsedTime.stop();
                    elapsedTime.setVisibility(View.GONE);
                }else {
                    elapsedTime.start();
                    elapsedTime.setVisibility(View.VISIBLE);
                }
                break;
            case SipCallSession.InvState.NULL:
            case SipCallSession.InvState.DISCONNECTED:
                elapsedTime.stop();
                elapsedTime.setVisibility(VISIBLE);
                break;
            default:
                break;
        }

    }
 
Example 19
Source File: ServiceSinkhole.java    From NetGuard with GNU General Public License v3.0 4 votes vote down vote up
public void notifyNewApplication(int uid) {
    if (uid < 0)
        return;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    try {
        // Get application name
        String name = TextUtils.join(", ", Util.getApplicationNames(uid, this));

        // Get application info
        PackageManager pm = getPackageManager();
        String[] packages = pm.getPackagesForUid(uid);
        if (packages == null || packages.length < 1)
            throw new PackageManager.NameNotFoundException(Integer.toString(uid));
        boolean internet = Util.hasInternet(uid, this);

        // Build notification
        Intent main = new Intent(this, ActivityMain.class);
        main.putExtra(ActivityMain.EXTRA_REFRESH, true);
        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
        PendingIntent pi = PendingIntent.getActivity(this, uid, main, PendingIntent.FLAG_UPDATE_CURRENT);

        TypedValue tv = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimary, tv, true);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "notify");
        builder.setSmallIcon(R.drawable.ic_security_white_24dp)
                .setContentIntent(pi)
                .setColor(tv.data)
                .setAutoCancel(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            builder.setContentTitle(name)
                    .setContentText(getString(R.string.msg_installed_n));
        else
            builder.setContentTitle(getString(R.string.app_name))
                    .setContentText(getString(R.string.msg_installed, name));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            builder.setCategory(NotificationCompat.CATEGORY_STATUS)
                    .setVisibility(NotificationCompat.VISIBILITY_SECRET);

        // Get defaults
        SharedPreferences prefs_wifi = getSharedPreferences("wifi", Context.MODE_PRIVATE);
        SharedPreferences prefs_other = getSharedPreferences("other", Context.MODE_PRIVATE);
        boolean wifi = prefs_wifi.getBoolean(packages[0], prefs.getBoolean("whitelist_wifi", true));
        boolean other = prefs_other.getBoolean(packages[0], prefs.getBoolean("whitelist_other", true));

        // Build Wi-Fi action
        Intent riWifi = new Intent(this, ServiceSinkhole.class);
        riWifi.putExtra(ServiceSinkhole.EXTRA_COMMAND, ServiceSinkhole.Command.set);
        riWifi.putExtra(ServiceSinkhole.EXTRA_NETWORK, "wifi");
        riWifi.putExtra(ServiceSinkhole.EXTRA_UID, uid);
        riWifi.putExtra(ServiceSinkhole.EXTRA_PACKAGE, packages[0]);
        riWifi.putExtra(ServiceSinkhole.EXTRA_BLOCKED, !wifi);

        PendingIntent piWifi = PendingIntent.getService(this, uid, riWifi, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action wAction = new NotificationCompat.Action.Builder(
                wifi ? R.drawable.wifi_on : R.drawable.wifi_off,
                getString(wifi ? R.string.title_allow_wifi : R.string.title_block_wifi),
                piWifi
        ).build();
        builder.addAction(wAction);

        // Build mobile action
        Intent riOther = new Intent(this, ServiceSinkhole.class);
        riOther.putExtra(ServiceSinkhole.EXTRA_COMMAND, ServiceSinkhole.Command.set);
        riOther.putExtra(ServiceSinkhole.EXTRA_NETWORK, "other");
        riOther.putExtra(ServiceSinkhole.EXTRA_UID, uid);
        riOther.putExtra(ServiceSinkhole.EXTRA_PACKAGE, packages[0]);
        riOther.putExtra(ServiceSinkhole.EXTRA_BLOCKED, !other);
        PendingIntent piOther = PendingIntent.getService(this, uid + 10000, riOther, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action oAction = new NotificationCompat.Action.Builder(
                other ? R.drawable.other_on : R.drawable.other_off,
                getString(other ? R.string.title_allow_other : R.string.title_block_other),
                piOther
        ).build();
        builder.addAction(oAction);

        // Show notification
        if (internet)
            NotificationManagerCompat.from(this).notify(uid, builder.build());
        else {
            NotificationCompat.BigTextStyle expanded = new NotificationCompat.BigTextStyle(builder);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                expanded.bigText(getString(R.string.msg_installed_n));
            else
                expanded.bigText(getString(R.string.msg_installed, name));
            expanded.setSummaryText(getString(R.string.title_internet));
            NotificationManagerCompat.from(this).notify(uid, expanded.build());
        }

    } catch (PackageManager.NameNotFoundException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}
 
Example 20
Source File: QRCodeGenerator.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private String setAttrData(TrackedEntityAttributeValue attrValue) {
    List<String> data = new ArrayList<>();
    data.add(attrValue.trackedEntityAttribute());
    data.add(attrValue.value());
    return TextUtils.join("|", data);
}