Example usage for android.text TextUtils join

List of usage examples for android.text TextUtils join

Introduction

In this page you can find the example usage for android.text TextUtils join.

Prototype

public static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens) 

Source Link

Document

Returns a string containing the tokens joined by delimiters.

Usage

From source file:org.alfresco.mobile.android.api.services.impl.onpremise.OnPremiseDocumentFolderServiceImpl.java

private void favoriteNode(Node node, boolean addFavorite) {
    if (isObjectNull(node)) {
        throw new IllegalArgumentException(
                String.format(Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "node"));
    }//  w  ww .ja  va 2 s.  c om

    try {
        String cleanIdentifier = NodeRefUtils.getCleanIdentifier(node.getIdentifier());
        String joined = cleanIdentifier;

        String link = OnPremiseUrlRegistry.getUserPreferenceUrl(session, session.getPersonIdentifier());
        UrlBuilder url = new UrlBuilder(link);

        List<String> favoriteIdentifier = null;
        String filter = OnPremiseUrlRegistry.PREFERENCE_FAVOURITES_DOCUMENTS;
        if (node.isFolder()) {
            filter = OnPremiseUrlRegistry.PREFERENCE_FAVOURITES_FOLDERS;
        }

        String[] favs = parsePreferenceResponse(session, session.getPersonIdentifier(), filter);
        if (favs != null) {
            favoriteIdentifier = new ArrayList<String>(Arrays.asList(favs));
            Set<String> index = new HashSet<String>(favoriteIdentifier);

            boolean hasIdentifier = index.contains(cleanIdentifier);

            if (addFavorite && !hasIdentifier) {
                favoriteIdentifier.add(cleanIdentifier);
                joined = TextUtils.join(",", favoriteIdentifier);
            } else if (!addFavorite && hasIdentifier) {
                index.remove(cleanIdentifier);
                joined = TextUtils.join(",", index.toArray(new String[0]));
            } else {
                // Throw exceptions ????
            }
        }

        // prepare json data
        String[] sitePrefence = filter.split("\\.");

        int length = sitePrefence.length - 1;

        JSONObject jroot = new JSONObject();
        JSONObject jt = null;
        JSONObject jp = jroot;
        for (int i = 0; i < length; i++) {
            jt = new JSONObject();
            jp.put(sitePrefence[i], jt);
            jp = jt;
        }

        jt.put(OnPremiseUrlRegistry.FAVOURITES, joined);

        final JsonDataWriter formDataM = new JsonDataWriter(jroot);

        // send
        post(url, formDataM.getContentType(), new Output() {
            public void write(OutputStream out) throws IOException {
                formDataM.write(out);
            }
        }, ErrorCodeRegistry.DOCFOLDER_GENERIC);
    } catch (Exception e) {
        convertException(e);
    }
}

From source file:com.dycody.android.idealnote.async.DataBackupIntentService.java

/**
  * Imports notes and notebooks from Springpad exported archive
  */*from w  ww .  j  a  va  2 s  .  com*/
  * @param intent
  */
synchronized private void importDataFromSpringpad(Intent intent) {
    String backupPath = intent.getStringExtra(EXTRA_SPRINGPAD_BACKUP);
    Importer importer = new Importer();
    try {
        importer.setZipProgressesListener(percentage -> mNotificationsHelper
                .setMessage(getString(com.dycody.android.idealnote.R.string.extracted) + " " + percentage + "%")
                .show());
        importer.doImport(backupPath);
        // Updating notification
        updateImportNotification(importer);
    } catch (ImportException e) {
        new NotificationsHelper(this)
                .createNotification(com.dycody.android.idealnote.R.drawable.ic_emoticon_sad_white_24dp,
                        getString(com.dycody.android.idealnote.R.string.import_fail) + ": " + e.getMessage(),
                        null)
                .setLedActive().show();
        return;
    }
    List<SpringpadElement> elements = importer.getSpringpadNotes();

    // If nothing is retrieved it will exit
    if (elements == null || elements.size() == 0) {
        return;
    }

    // These maps are used to associate with post processing notes to categories (notebooks)
    HashMap<String, Category> categoriesWithUuid = new HashMap<>();

    // Adds all the notebooks (categories)
    for (SpringpadElement springpadElement : importer.getNotebooks()) {
        Category cat = new Category();
        cat.setName(springpadElement.getName());
        cat.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
        DbHelper.getInstance().updateCategory(cat);
        categoriesWithUuid.put(springpadElement.getUuid(), cat);

        // Updating notification
        importedSpringpadNotebooks++;
        updateImportNotification(importer);
    }
    // And creates a default one for notes without notebook 
    Category defaulCategory = new Category();
    defaulCategory.setName("Springpad");
    defaulCategory.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
    DbHelper.getInstance().updateCategory(defaulCategory);

    // And then notes are created
    Note note;
    Attachment mAttachment = null;
    Uri uri;
    for (SpringpadElement springpadElement : importer.getNotes()) {
        note = new Note();

        // Title
        note.setTitle(springpadElement.getName());

        // Content dependent from type of Springpad note
        StringBuilder content = new StringBuilder();
        content.append(
                TextUtils.isEmpty(springpadElement.getText()) ? "" : Html.fromHtml(springpadElement.getText()));
        content.append(
                TextUtils.isEmpty(springpadElement.getDescription()) ? "" : springpadElement.getDescription());

        // Some notes could have been exported wrongly
        if (springpadElement.getType() == null) {
            Toast.makeText(this, getString(com.dycody.android.idealnote.R.string.error), Toast.LENGTH_SHORT)
                    .show();
            continue;
        }

        if (springpadElement.getType().equals(SpringpadElement.TYPE_VIDEO)) {
            try {
                content.append(System.getProperty("line.separator"))
                        .append(springpadElement.getVideos().get(0));
            } catch (IndexOutOfBoundsException e) {
                content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
            }
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_TVSHOW)) {
            content.append(System.getProperty("line.separator"))
                    .append(TextUtils.join(", ", springpadElement.getCast()));
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOK)) {
            content.append(System.getProperty("line.separator")).append("Author: ")
                    .append(springpadElement.getAuthor()).append(System.getProperty("line.separator"))
                    .append("Publication date: ").append(springpadElement.getPublicationDate());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_RECIPE)) {
            content.append(System.getProperty("line.separator")).append("Ingredients: ")
                    .append(springpadElement.getIngredients()).append(System.getProperty("line.separator"))
                    .append("Directions: ").append(springpadElement.getDirections());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOKMARK)) {
            content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BUSINESS)
                && springpadElement.getPhoneNumbers() != null) {
            content.append(System.getProperty("line.separator")).append("Phone number: ")
                    .append(springpadElement.getPhoneNumbers().getPhone());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_PRODUCT)) {
            content.append(System.getProperty("line.separator")).append("Category: ")
                    .append(springpadElement.getCategory()).append(System.getProperty("line.separator"))
                    .append("Manufacturer: ").append(springpadElement.getManufacturer())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_WINE)) {
            content.append(System.getProperty("line.separator")).append("Wine type: ")
                    .append(springpadElement.getWine_type()).append(System.getProperty("line.separator"))
                    .append("Varietal: ").append(springpadElement.getVarietal())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_ALBUM)) {
            content.append(System.getProperty("line.separator")).append("Artist: ")
                    .append(springpadElement.getArtist());
        }
        for (SpringpadComment springpadComment : springpadElement.getComments()) {
            content.append(System.getProperty("line.separator")).append(springpadComment.getCommenter())
                    .append(" commented at 0").append(springpadComment.getDate()).append(": ")
                    .append(springpadElement.getArtist());
        }

        note.setContent(content.toString());

        // Checklists
        if (springpadElement.getType().equals(SpringpadElement.TYPE_CHECKLIST)) {
            StringBuilder sb = new StringBuilder();
            String checkmark;
            for (SpringpadItem mSpringpadItem : springpadElement.getItems()) {
                checkmark = mSpringpadItem.getComplete()
                        ? it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM
                        : it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM;
                sb.append(checkmark).append(mSpringpadItem.getName())
                        .append(System.getProperty("line.separator"));
            }
            note.setContent(sb.toString());
            note.setChecklist(true);
        }

        // Tags
        String tags = springpadElement.getTags().size() > 0
                ? "#" + TextUtils.join(" #", springpadElement.getTags())
                : "";
        if (note.isChecklist()) {
            note.setTitle(note.getTitle() + tags);
        } else {
            note.setContent(note.getContent() + System.getProperty("line.separator") + tags);
        }

        // Address
        String address = springpadElement.getAddresses() != null ? springpadElement.getAddresses().getAddress()
                : "";
        if (!TextUtils.isEmpty(address)) {
            try {
                double[] coords = GeocodeHelper.getCoordinatesFromAddress(this, address);
                note.setLatitude(coords[0]);
                note.setLongitude(coords[1]);
            } catch (IOException e) {
                Log.e(Constants.TAG,
                        "An error occurred trying to resolve address to coords during Springpad import");
            }
            note.setAddress(address);
        }

        // Reminder
        if (springpadElement.getDate() != null) {
            note.setAlarm(springpadElement.getDate().getTime());
        }

        // Creation, modification, category
        note.setCreation(springpadElement.getCreated().getTime());
        note.setLastModification(springpadElement.getModified().getTime());

        // Image
        String image = springpadElement.getImage();
        if (!TextUtils.isEmpty(image)) {
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, image);
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + image);
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // Other attachments
        for (SpringpadAttachment springpadAttachment : springpadElement.getAttachments()) {
            // The attachment could be the image itself so it's jumped
            if (image != null && image.equals(springpadAttachment.getUrl()))
                continue;

            if (TextUtils.isEmpty(springpadAttachment.getUrl())) {
                continue;
            }

            // Tries first with online images
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, springpadAttachment.getUrl());
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + springpadAttachment.getUrl());
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // If the note has a category is added to the map to be post-processed
        if (springpadElement.getNotebooks().size() > 0) {
            note.setCategory(categoriesWithUuid.get(springpadElement.getNotebooks().get(0)));
        } else {
            note.setCategory(defaulCategory);
        }

        // The note is saved
        DbHelper.getInstance().updateNote(note, false);
        ReminderHelper.addReminder(IdealNote.getAppContext(), note);

        // Updating notification
        importedSpringpadNotes++;
        updateImportNotification(importer);
    }

    // Delete temp data
    try {
        importer.clean();
    } catch (IOException e) {
        Log.w(Constants.TAG, "Springpad import temp files not deleted");
    }

    String title = getString(com.dycody.android.idealnote.R.string.data_import_completed);
    String text = getString(com.dycody.android.idealnote.R.string.click_to_refresh_application);
    createNotification(intent, this, title, text, null);
}

From source file:de.fmaul.android.cmis.repo.CmisRepository.java

private String createParams(FilterPrefs pref, Boolean isAdd, Boolean isFirst) {
    String params = "";
    String value = "";
    ArrayList<String> listParams = new ArrayList<String>(4);

    if (pref != null && pref.getParams()) {

        value = pref.getTypes();//from  ww  w  .j ava  2 s.com
        if (value != null && value.length() > 0) {
            listParams.add("types" + "=" + pref.getTypes());
        }

        /*
        if (pref.getFilter() != null){
           paramsList.put("filter", pref.getFilter());
        }*/

        if (pref.getPaging()) {
            if (isFirst) {
                listParams.add("skipCount" + "=0");
                setSkipCount(0);
            } else {
                value = pref.getMaxItems();
                if (value != null) {
                    if (value.length() == 0) {
                        value = "0";
                        setMaxItems(Integer.parseInt(value));
                    }
                    int skipCountValue = 0;
                    if (isAdd) {
                        skipCountValue = getSkipCount() + getMaxItems();
                    } else {
                        skipCountValue = getSkipCount() - getMaxItems();
                    }
                    if (skipCountValue < 0) {
                        skipCountValue = 0;
                    }
                    listParams.add("skipCount" + "=" + skipCountValue);
                    setSkipCount(skipCountValue);
                }
            }
        }

        value = pref.getMaxItems();
        if (value != null && value.length() > 0 && Integer.parseInt(value) > 0) {
            listParams.add("maxItems" + "=" + pref.getMaxItems());
            setMaxItems(Integer.parseInt(value));
        }

        value = pref.getOrder();
        if (pref.getOrder() != null && pref.getOrder().length() > 0) {
            listParams.add("orderBy" + "=" + pref.getOrder());
        }

        params = "?" + TextUtils.join("&", listParams);
    }

    try {
        params = new URI(null, params, null).toASCIIString();
    } catch (URISyntaxException e) {
    }
    Log.d(TAG, "Params : " + params);
    return params;
}

From source file:org.proninyaroslav.libretorrent.fragments.DetailTorrentTrackersFragment.java

private void shareUrl() {
    if (!selectedTrackers.isEmpty()) {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "url");

        if (selectedTrackers.size() == 1) {
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, selectedTrackers.get(0));
        } else {/*from   w  ww.  ja v a  2 s. com*/
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                    TextUtils.join(Utils.getLineSeparator(), selectedTrackers));
        }

        startActivity(Intent.createChooser(sharingIntent, getString(R.string.share_via)));

        selectedTrackers.clear();
    }
}

From source file:org.jraf.android.piclabel.app.form.FormActivity.java

private String reverseGeocode(float lat, float lon) {
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses;
    try {//from  w w w  . j a va2s  . c o  m
        addresses = geocoder.getFromLocation(lat, lon, 1);
    } catch (Throwable t) {
        Log.w(TAG, "reverseGeocode Could not reverse geocode", t);
        return null;
    }
    if (addresses == null || addresses.isEmpty())
        return null;
    Address address = addresses.get(0);
    ArrayList<String> strings = new ArrayList<String>(5);
    if (address.getMaxAddressLineIndex() > 0)
        strings.add(address.getAddressLine(0));
    if (!TextUtils.isEmpty(address.getLocality()))
        strings.add(address.getLocality());
    if (!TextUtils.isEmpty(address.getCountryName()))
        strings.add(address.getCountryName());
    return TextUtils.join(", ", strings);
}

From source file:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java

/**
 * Fetches places from the Places API, back-filling with random locations if too few
 * returned, and caches them all for future use.
 *
 * @param center/*from w w w  .j  a  v  a 2 s  .com*/
 * @param radius
 * @return
 */
private Place fetchPlacesAndGetCached(LatLng center, int radius) {
    // Before we start, mark if this is the first run
    boolean firstRun = Place.count(Place.class) == 0;

    // Make places API request using double the radius, to have cached items while travelling.
    ArrayList<LatLng> places = fetchPlacesFromAPI(center, radius * 2);
    int numFetched = places.size();
    Log.d(TAG, "fetchPlaces: API returned " + numFetched + " place(s)");

    // Build set of locations that Places API returned and are already cached, which
    // we can check against before caching a new location from Places API.
    Set<LatLng> cached = new HashSet<>();
    if (numFetched > 0) {
        String[] query = new String[numFetched];
        String[] queryArgs = new String[numFetched * 2];
        for (int i = 0; i < numFetched; i++) {
            query[i] = "(lat = ? AND lng = ?)";
            LatLng placeLatLng = places.get(i);
            int argsIndex = i * 2;
            queryArgs[argsIndex] = String.valueOf(placeLatLng.latitude);
            queryArgs[argsIndex + 1] = String.valueOf(placeLatLng.longitude);
        }

        // eg: SELECT * FROM places WHERE (lat = 1 AND lng = 2) OR (lat = 3 AND lng = 4);
        for (Place place : Place.find(Place.class, TextUtils.join(" OR ", query), queryArgs)) {
            cached.add(place.getLatLng());
        }
    }
    Log.d(TAG, "fetchPlaces: " + cached.size() + " place(s) are already cached");

    // Back-fill with random locations to ensure up to MIN_CACHED_PLACES places.
    // We reduce radius to half for these, to decrease the likelihood of
    // adding an inaccessible location.
    int fill = mConfig.MIN_CACHED_PLACES - numFetched;
    if (fill > 0) {
        Log.d(TAG, "fetchPlaces: back-filling with " + fill + " random places");
        for (int i = 0; i < fill; i++) {
            LatLng randomLatLng = randomLatLng(center, radius / 2);
            places.add(randomLatLng);
        }
    }

    // Save results to cache.
    Log.d(TAG, "fetchPlaces: caching " + places.size());
    for (LatLng latLng : places) {
        Place place = new Place(latLng);
        // Check that the place isn't already in the cache, which is very likely since
        // if the rate limit elapses and the user hasn't moved, duplicates will be returned.
        if (!cached.contains(place.getLatLng())) {
            place.save();
        } else {
            Log.d(TAG, "Location already cached, discarding: " + latLng);
        }
    }

    // Cull the cache if too large.
    int cull = Math.max((int) Place.count(Place.class) - mConfig.MAX_CACHED_PLACES, 0);
    Log.d(TAG, "fetchPlaces: culling " + cull + " cached places");
    if (cull > 0) {
        String[] emptyArgs = {};
        int i = 0;
        // Get the list of oldest cached places we want to cull, and use its highest ID
        // as the arg to delete.
        // eg: SELECT FROM places ORDER BY id LIMIT 20;
        List<Place> oldestPlaces = Place.find(Place.class, "", emptyArgs, "", "id", String.valueOf(cull));
        Place newestOfOldest = oldestPlaces.get(oldestPlaces.size() - 1);
        // eg: DELETE FROM places WHERE ID <= 20;
        Place.deleteAll(Place.class, "ID <= ?", String.valueOf(newestOfOldest.getId()));
    }

    // If it's the first run, try to return a particularly well-suited place
    if (firstRun) {
        Place firstRunPlace = getCachedFirstPlace(center);
        if (firstRunPlace != null) {
            return firstRunPlace;
        }
    }

    // Now that the cache is populated, use the logic to get a cached place and return it
    return getCachedPlace(center, radius);
}

From source file:com.afwsamples.testdpc.common.preference.DpcPreferenceHelper.java

private String joinRequirementList(List<String> items) {
    final StringBuilder sb = new StringBuilder(mContext.getString(R.string.requires));
    final String lastItem = items.remove(items.size() - 1);
    sb.append(TextUtils.join(mContext.getString(R.string.requires_delimiter), items));
    if (!items.isEmpty()) {
        sb.append(mContext.getString(R.string.requires_or));
    }//w  ww . ja va  2 s  .  c  om
    sb.append(lastItem);
    return sb.toString();
}

From source file:com.eutectoid.dosomething.picker.FriendPickerFragment.java

private GraphRequest createRequest(String userID, Set<String> extraFields) {
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    GraphRequest request = GraphRequest.newGraphPathRequest(accessToken,
            userID + friendPickerType.getRequestPath(), null);

    Set<String> fields = new HashSet<String>(extraFields);
    String[] requiredFields = new String[] { ID, NAME };
    fields.addAll(Arrays.asList(requiredFields));

    String pictureField = adapter.getPictureFieldSpecifier();
    if (pictureField != null) {
        fields.add(pictureField);/*from  w  ww.  j a va  2s.  c  o m*/
    }

    Bundle parameters = request.getParameters();
    parameters.putString("fields", TextUtils.join(",", fields));
    request.setParameters(parameters);

    return request;
}

From source file:com.bangz.smartmute.services.LocationMuteService.java

private void handleDeleteGeofences(long[] ids) {

    LogUtils.LOGD(TAG, "Handling delete geofences...");
    List<String> removeids = new ArrayList<String>();
    for (long id : ids) {
        removeids.add(String.valueOf(id));
    }/*from  ww  w .ja  v a  2  s. c o  m*/

    ConnectionResult cr = mGoogleApiClient.blockingConnect();
    if (cr.isSuccess() == false) {
        LogUtils.LOGD(TAG, "GoogleApiClient.blockconnect failed! message: " + cr.toString());
        return;
    }
    Status result = LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, removeids).await();
    if (result.isSuccess()) {
        LogUtils.LOGD(TAG, "Delete geofences successful.");
    } else {
        LogUtils.LOGD(TAG, "Delete geofences fail. message:" + result.getStatusMessage());
    }
    mGoogleApiClient.disconnect();

    // now delete these records from database ;

    ContentResolver contentResolver = getContentResolver();
    String args = TextUtils.join(", ", removeids);
    String where = String.format("%s IN (%s)", RulesColumns._ID, args);
    contentResolver.delete(RulesColumns.CONTENT_URI, where, null);

}

From source file:com.facebook.TestUserManager.java

private String getPermissionsString(List<String> permissions) {
    return TextUtils.join(",", permissions);
}