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:at.bitfire.davdroid.DavService.java

@SuppressLint("MissingPermission")
void cleanupAccounts() {
    App.log.info("Cleaning up orphaned accounts");

    final OpenHelper dbHelper = new OpenHelper(this);
    try {//from   w  w w  . j av  a 2s  .c o  m
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        List<String> sqlAccountNames = new LinkedList<>();
        AccountManager am = AccountManager.get(this);
        for (Account account : am.getAccountsByType(Constants.ACCOUNT_TYPE))
            sqlAccountNames.add(DatabaseUtils.sqlEscapeString(account.name));

        if (sqlAccountNames.isEmpty())
            db.delete(Services._TABLE, null, null);
        else
            db.delete(Services._TABLE,
                    Services.ACCOUNT_NAME + " NOT IN (" + TextUtils.join(",", sqlAccountNames) + ")", null);
    } finally {
        dbHelper.close();
    }
}

From source file:com.linroid.pushapp.ui.send.SendActivity.java

private void pushToDevice(List<String> devices) {
    if (devices.size() == 0) {
        Snackbar.make(fab, R.string.error_not_select_any_device, Snackbar.LENGTH_SHORT).show();
        return;//from w  w w .j  av a  2s.  c  o m
    }
    Snackbar.make(fab, getString(R.string.msg_push_install_package, devices.size()), Snackbar.LENGTH_SHORT)
            .show();
    String deviceIds = TextUtils.join(",", devices.toArray());
    if (pack != null) {
        installApi.installPackage(deviceIds, pack.getId(), this);
    } else {
        File apkFile = new File(appInfo.sourceDir);
        CountingTypedFile typedFile = new CountingTypedFile(apkFile);
        dialog.show();
        typedFile.subscribe(new Subscriber<Pair<Long, Long>>() {
            @Override
            public void onCompleted() {
                dialog.setMessage(getString(R.string.msg_upload_complete));
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(Pair<Long, Long> pair) {
                dialog.setMessage(getString(R.string.msg_upload_progress,
                        Formatter.formatShortFileSize(SendActivity.this, pair.second),
                        Formatter.formatShortFileSize(SendActivity.this, pair.first)));
            }
        });
        installApi.installLocal(new TypedString(deviceIds), typedFile, this);
    }
}

From source file:at.florian_lentsch.expirysync.net.JsonCaller.java

private void prepareConnection(HttpURLConnection connection, String method, boolean outputAvailable)
        throws ProtocolException {
    connection.setDoInput(true);/*from  ww  w.  j a va2s.  c  o  m*/
    connection.setDoOutput(outputAvailable);
    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Accept", "application/json");

    // send cookies if previously set:
    if (this.cookieManager.getCookieStore().getCookies().size() > 0) {
        connection.setRequestProperty("Cookie",
                TextUtils.join(",", this.cookieManager.getCookieStore().getCookies()));
    }
}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }/*ww  w . j a  v a 2 s.c  om*/
    }

    X509TrustManager trustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

From source file:com.facebook.login.DeviceAuthDialog.java

public void startLogin(final LoginClient.Request request) {
    Bundle parameters = new Bundle();
    parameters.putString("type", "device_code");
    parameters.putString("client_id", FacebookSdk.getApplicationId());
    parameters.putString("scope", TextUtils.join(",", request.getPermissions()));
    GraphRequest graphRequest = new GraphRequest(null, DEVICE_OUATH_ENDPOINT, parameters, HttpMethod.POST,
            new GraphRequest.Callback() {
                @Override//from   w  w  w  .j  a  v  a2 s .  co m
                public void onCompleted(GraphResponse response) {
                    if (response.getError() != null) {
                        onError(response.getError().getException());
                        return;
                    }

                    JSONObject jsonObject = response.getJSONObject();
                    RequestState requestState = new RequestState();
                    try {
                        requestState.setUserCode(jsonObject.getString("user_code"));
                        requestState.setRequestCode(jsonObject.getString("code"));
                        requestState.setInterval(jsonObject.getLong("interval"));
                    } catch (JSONException ex) {
                        onError(new FacebookException(ex));
                        return;
                    }

                    setCurrentRequestState(requestState);
                }
            });
    graphRequest.executeAsync();
}

From source file:com.google.android.gms.location.sample.geofencing.GeofenceTransitionsIntentService.java

/**
 * Gets transition details and returns them as a formatted string.
 *
 * @param context               The app context.
 * @param geofenceTransition    The ID of the geofence transition.
 * @param triggeringGeofences   The geofence(s) triggered.
 * @return                      The transition details formatted as String.
 *///from   w  w  w.j  a  va 2s  . com
private String getGeofenceTransitionDetails(Context context, int geofenceTransition,
        List<Geofence> triggeringGeofences) {

    String geofenceTransitionString = getTransitionString(geofenceTransition);

    // Get the Ids of each geofence that was triggered.
    ArrayList triggeringGeofencesIdsList = new ArrayList();
    for (Geofence geofence : triggeringGeofences) {
        triggeringGeofencesIdsList.add(geofence.getRequestId());
    }
    String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);

    return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}

From source file:org.aosutils.android.youtube.YtApiClientV3.java

public static ArrayList<YtPlaylist> getPlaylistInfo(Collection<String> playlistIds, String apiKey)
        throws IOException, JSONException {
    ArrayList<YtPlaylist> playlists = new ArrayList<>();

    String uri = new Uri.Builder().scheme("https").authority("www.googleapis.com").path("/youtube/v3/playlists")
            .appendQueryParameter("key", apiKey).appendQueryParameter("part", "id,snippet")
            .appendQueryParameter("id", TextUtils.join(",", playlistIds)).build().toString();

    String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT);
    JSONObject jsonObject = new JSONObject(output);

    JSONArray items = jsonObject.getJSONArray("items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);

        String playlistId = item.getString("id");
        String title = item.getJSONObject("snippet").getString("title");
        String description = item.getJSONObject("snippet").getString("description");

        YtPlaylist playlist = new YtPlaylist(playlistId, title, description);
        playlists.add(playlist);//from w  ww  .j av  a 2s.c  o  m
    }

    return playlists;
}

From source file:com.example.ruby.mygetgps.services.GeofenceTransitionsIntentService.java

/**
 * Gets transition details and returns them as a formatted string.
 *
 * @param context               The app context.
 * @param geofenceTransition    The ID of the geofence transition.
 * @param triggeringGeofences   The geofence(s) triggered.
 * @return The transition details formatted as String.
 *///from ww  w  .j  a va2s.  co  m
private String getGeofenceTransitionDetails(Context context, int geofenceTransition,
        List<Geofence> triggeringGeofences) {

    String geofenceTransitionString = getTransitionString(geofenceTransition);

    // Get the Ids of each geofence that was triggered.
    ArrayList triggeringGeofencesIdsList = new ArrayList();
    for (Geofence geofence : triggeringGeofences) {
        triggeringGeofencesIdsList.add(geofence.getRequestId());
    }
    String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);

    return geofenceTransitionString; // + ": " + triggeringGeofencesIdsString;
}

From source file:org.hermes.ui.Components.EmojiView.java

private void saveRecents() {
    ArrayList<Long> localArrayList = new ArrayList<>();
    long[] arrayOfLong = Emoji.data[0];
    int i = arrayOfLong.length;
    for (int j = 0;; j++) {
        if (j >= i) {
            getContext().getSharedPreferences("emoji", 0).edit()
                    .putString("recents", TextUtils.join(",", localArrayList)).commit();
            return;
        }/*from   w  ww.j  av a2  s  .  co  m*/
        localArrayList.add(arrayOfLong[j]);
    }
}

From source file:org.geometerplus.android.fbreader.network.BearerAuthenticator.java

private boolean registerAccessToken(String clientId, String authUrl, String authToken) {
    String code = null;/* w  w  w. j  a  v  a2 s. c o  m*/
    try {
        code = GoogleAuthUtil.getToken(myActivity, myAccount,
                String.format("oauth2:server:client_id:%s:api_scope:%s", clientId,
                        TextUtils.join(" ", new Object[] { Scopes.DRIVE_FULL, Scopes.PROFILE })),
                null);
        System.err.println("ACCESS TOKEN = " + code);
        final String result = runTokenAuthorization(authUrl, authToken, code);
        System.err.println("AUTHENTICATION RESULT 2 = " + result);
        return true;
    } catch (UserRecoverableAuthException e) {
        myAuthorizationConfirmed = false;
        startActivityAndWait(e.getIntent(), NetworkLibraryActivity.REQUEST_AUTHORISATION);
        return myAuthorizationConfirmed && registerAccessToken(clientId, authUrl, authToken);
    } catch (Exception e) {
        return false;
    }
}