List of usage examples for android.text TextUtils join
public static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens)
From source file:website.openeng.anki.StudyOptionsFragment.java
/** * Special method to show the context menu for the custom study options * TODO: Turn this into a DialogFragment *///from ww w . j a va 2s .c om private void showCustomStudyContextMenu() { Resources res = getResources(); Drawable icon = res.getDrawable(R.drawable.ic_sort_black_36dp); icon.setAlpha(Themes.ALPHA_ICON_ENABLED_DARK); MaterialDialog dialog = new MaterialDialog.Builder(this.getActivity()) .title(res.getString(R.string.custom_study)).icon(icon).cancelable(true) .items(res.getStringArray(R.array.custom_study_options_labels)) .itemsCallback(new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog materialDialog, View view, int which, CharSequence charSequence) { DialogFragment dialogFragment; if (which == CustomStudyDialog.CUSTOM_STUDY_TAGS) { /* * This is a special Dialog for CUSTOM STUDY, where instead of only collecting a * number, it is necessary to collect a list of tags. This case handles the creation * of that Dialog. */ dialogFragment = website.openeng.anki.dialogs.TagsDialog.newInstance( TagsDialog.TYPE_CUSTOM_STUDY_TAGS, new ArrayList<String>(), new ArrayList<String>(getCol().getTags().all())); ((TagsDialog) dialogFragment).setTagsDialogListener(new TagsDialogListener() { @Override public void onPositive(List<String> selectedTags, int option) { /* * Here's the method that gathers the final selection of tags, type of cards and generates the search * screen for the custom study deck. */ StringBuilder sb = new StringBuilder(); switch (option) { case 1: sb.append("is:new "); break; case 2: sb.append("is:due "); break; default: // Logging here might be appropriate : ) break; } List<String> arr = new ArrayList<>(); if (selectedTags.size() > 0) { for (String tag : selectedTags) { arr.add(String.format("tag:'%s'", tag)); } sb.append("(" + TextUtils.join(" or ", arr) + ")"); } mSearchTerms = sb.toString(); createFilteredDeck(new JSONArray(), new Object[] { mSearchTerms, Consts.DYN_MAX_SIZE, Consts.DYN_RANDOM }, false); } }); } else { // Show CustomStudyDialog for all options other than the tags dialog dialogFragment = CustomStudyDialog.newInstance(which); // If we increase limits, refresh the interface to reflect the new counts ((CustomStudyDialog) dialogFragment).setCustomStudyDialogListener( new CustomStudyDialog.CustomStudyDialogListener() { @Override public void onPositive(int option) { if (option == CustomStudyDialog.CUSTOM_STUDY_NEW || option == CustomStudyDialog.CUSTOM_STUDY_REV) { refreshInterfaceAndDecklist(true); } } }); } // Show the DialogFragment via Activity ((AnkiActivity) getActivity()).showDialogFragment(dialogFragment); } }).build(); dialog.setOwnerActivity(getActivity()); dialog.show(); }
From source file:com.google.android.car.kitchensink.radio.RadioTestFragment.java
private void addLog(int priority, String message) { Log.println(priority, TAG, message); synchronized (this) { mLogMessages.add(message);/*from w ww . j av a 2s .c o m*/ if (mLogMessages.size() > MAX_LOG_MESSAGES) { mLogMessages.poll(); } mLog.setText(TextUtils.join("\n", mLogMessages)); } }
From source file:com.nijie.samples.facebookfoo.FacebookFooMainActivity.java
private void onFriendPickerDone(FriendPickerFragment fragment) { FragmentManager fm = getSupportFragmentManager(); fm.popBackStack();/* w w w . ja v a2 s .com*/ String results = ""; List<GraphUser> selection = fragment.getSelection(); tags = selection; if (selection != null && selection.size() > 0) { ArrayList<String> names = new ArrayList<String>(); for (GraphUser user : selection) { names.add(user.getName()); } results = TextUtils.join(", ", names); } else { results = getString(R.string.no_friends_selected); } showAlert(getString(R.string.you_picked), results); }
From source file:com.pindroid.platform.BookmarkManager.java
public static CursorLoader SearchBookmarks(String query, String tagname, boolean unread, String username, Context context) {//from ww w. ja v a2s .c om final String[] projection = new String[] { Bookmark._ID, Bookmark.Url, Bookmark.Description, Bookmark.Hash, Bookmark.Meta, Bookmark.Tags, Bookmark.Shared, Bookmark.ToRead, Bookmark.Synced, Bookmark.Deleted }; String selection = null; final String sortorder = Bookmark.Description + " ASC"; final String[] queryBookmarks = query.split(" "); final ArrayList<String> queryList = new ArrayList<String>(); final ArrayList<String> selectionlist = new ArrayList<String>(); if (query != null && query != "" && (tagname == null || tagname == "")) { for (String s : queryBookmarks) { queryList.add("(" + Bookmark.Tags + " LIKE ? OR " + Bookmark.Description + " LIKE ? OR " + Bookmark.Notes + " LIKE ?)"); selectionlist.add("%" + s + "%"); selectionlist.add("%" + s + "%"); selectionlist.add("%" + s + "%"); } selectionlist.add(username); selection = TextUtils.join(" AND ", queryList) + " AND " + Bookmark.Account + "=?"; } else if (query != null && query != "") { for (String s : queryBookmarks) { queryList.add("(" + Bookmark.Description + " LIKE ? OR " + Bookmark.Notes + " LIKE ?)"); selectionlist.add("%" + s + "%"); selectionlist.add("%" + s + "%"); } selection = TextUtils.join(" AND ", queryList) + " AND " + Bookmark.Account + "=? AND " + "(" + Bookmark.Tags + " LIKE ? OR " + Bookmark.Tags + " LIKE ? OR " + Bookmark.Tags + " LIKE ? OR " + Bookmark.Tags + " = ?)"; selectionlist.add(username); selectionlist.add("% " + tagname + " %"); selectionlist.add("% " + tagname); selectionlist.add(tagname + " %"); selectionlist.add(tagname); } else { selectionlist.add(username); selection = Bookmark.Account + "=?"; } if (unread) { selection += " AND " + Bookmark.ToRead + "=1"; } selection += " AND " + Bookmark.Deleted + "=0"; return new CursorLoader(context, Bookmark.CONTENT_URI, projection, selection, selectionlist.toArray(new String[] {}), sortorder); }
From source file:self.philbrown.droidQuery.Ajax.java
protected TaskResponse doInBackground(Void... arg0) { if (this.isCancelled) return null; //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming. if (!beforeSendIsAsync) { try {//from w ww . java 2 s . c o m mutex.acquire(); } catch (InterruptedException e) { Log.w("AjaxTask", "Synchronization Error. Running Task Async"); } final Thread asyncThread = Thread.currentThread(); isLocked = true; mHandler.post(new Runnable() { @Override public void run() { if (options.beforeSend() != null) { if (options.context() != null) options.beforeSend().invoke($.with(options.context()), options); else options.beforeSend().invoke(null, options); } if (options.isAborted()) { cancel(true); return; } if (options.global()) { synchronized (globalTasks) { if (globalTasks.isEmpty()) { $.ajaxStart(); } globalTasks.add(Ajax.this); } $.ajaxSend(); } else { synchronized (localTasks) { localTasks.add(Ajax.this); } } isLocked = false; LockSupport.unpark(asyncThread); } }); if (isLocked) LockSupport.park(); } //here is where to use the mutex //handle cached responses Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options); //handle ajax caching option if (cachedResponse != null && options.cache()) { Success s = new Success(cachedResponse); s.reason = "cached response"; s.allHeaders = null; return s; } if (connection == null) { try { String type = options.type(); URL url = new URL(options.url()); if (type == null) { type = "GET"; } if (type.equalsIgnoreCase("CUSTOM")) { try { connection = options.customConnection(); } catch (Exception e) { connection = null; } if (connection == null) { Log.w("droidQuery.ajax", "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET."); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); } } else { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) { connection.setDoOutput(true); } } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); Error e = new Error(null); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = 0; e.reason = "Bad Configuration"; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = new Headers(); e.error = error; return e; } } Map<String, Object> args = new HashMap<String, Object>(); args.put("options", options); args.put("request", null); args.put("connection", connection); EventCenter.trigger("ajaxPrefilter", args, null); if (options.headers() != null) { if (options.headers().authorization() != null) { options.headers() .authorization(options.headers().authorization() + " " + options.getEncodedCredentials()); } else if (options.username() != null) { //guessing that authentication is basic options.headers().authorization("Basic " + options.getEncodedCredentials()); } for (Entry<String, String> entry : options.headers().map().entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } if (options.data() != null) { try { OutputStream os = connection.getOutputStream(); os.write(options.data().toString().getBytes()); os.close(); } catch (Throwable t) { Log.w("Ajax", "Could not post data"); } } if (options.timeout() != 0) { connection.setConnectTimeout(options.timeout()); connection.setReadTimeout(options.timeout()); } if (options.trustedCertificate() != null) { Certificate ca = options.trustedCertificate(); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); } catch (KeyStoreException e) { if (options.debug()) e.printStackTrace(); } catch (NoSuchAlgorithmException e) { if (options.debug()) e.printStackTrace(); } catch (CertificateException e) { if (options.debug()) e.printStackTrace(); } catch (IOException e) { if (options.debug()) e.printStackTrace(); } if (keyStore == null) { Log.w("Ajax", "Could not configure trusted certificate"); } else { try { //Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); //Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } catch (KeyManagementException e) { if (options.debug()) e.printStackTrace(); } catch (NoSuchAlgorithmException e) { if (options.debug()) e.printStackTrace(); } catch (KeyStoreException e) { if (options.debug()) e.printStackTrace(); } } } try { if (options.cookies() != null) { CookieManager cm = new CookieManager(); CookieStore cookies = cm.getCookieStore(); URI uri = URI.create(options.url()); for (Entry<String, String> entry : options.cookies().entrySet()) { HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue()); cookies.add(uri, cookie); } connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies())); } connection.connect(); final int statusCode = connection.getResponseCode(); final String message = connection.getResponseMessage(); if (options.dataFilter() != null) { if (options.context() != null) options.dataFilter().invoke($.with(options.context()), connection, options.dataType()); else options.dataFilter().invoke(null, connection, options.dataType()); } final Function function = options.statusCode().get(statusCode); if (function != null) { mHandler.post(new Runnable() { @Override public void run() { if (options.context() != null) function.invoke($.with(options.context()), statusCode, options.clone()); else function.invoke(null, statusCode, options.clone()); } }); } //handle dataType String dataType = options.dataType(); if (dataType == null) dataType = "text"; if (options.debug()) Log.i("Ajax", "dataType = " + dataType); Object parsedResponse = null; InputStream stream = null; try { if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) { if (options.debug()) Log.i("Ajax", "parsing text"); stream = AjaxUtil.getInputStream(connection); parsedResponse = parseText(stream); } else if (dataType.equalsIgnoreCase("xml")) { if (options.debug()) Log.i("Ajax", "parsing xml"); if (options.customXMLParser() != null) { stream = AjaxUtil.getInputStream(connection); if (options.SAXContentHandler() != null) options.customXMLParser().parse(stream, options.SAXContentHandler()); else options.customXMLParser().parse(stream, new DefaultHandler()); parsedResponse = "Response handled by custom SAX parser"; } else if (options.SAXContentHandler() != null) { stream = AjaxUtil.getInputStream(connection); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(options.SAXContentHandler()); reader.parse(new InputSource(stream)); parsedResponse = "Response handled by custom SAX content handler"; } else { parsedResponse = parseXML(connection); } } else if (dataType.equalsIgnoreCase("json")) { if (options.debug()) Log.i("Ajax", "parsing json"); parsedResponse = parseJSON(connection); } else if (dataType.equalsIgnoreCase("script")) { if (options.debug()) Log.i("Ajax", "parsing script"); parsedResponse = parseScript(connection); } else if (dataType.equalsIgnoreCase("image")) { if (options.debug()) Log.i("Ajax", "parsing image"); stream = AjaxUtil.getInputStream(connection); parsedResponse = parseImage(stream); } else if (dataType.equalsIgnoreCase("raw")) { if (options.debug()) Log.i("Ajax", "parsing raw data"); parsedResponse = parseRawContent(connection); } } catch (ClientProtocolException cpe) { if (options.debug()) cpe.printStackTrace(); Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = statusCode; e.reason = message; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; return e; } catch (Exception ioe) { if (options.debug()) ioe.printStackTrace(); Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = statusCode; e.reason = message; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; return e; } finally { connection.disconnect(); try { if (stream != null) { stream.close(); } } catch (IOException e) { } } if (statusCode >= 300) { //an error occurred Error e = new Error(parsedResponse); Log.e("Ajax Test", parsedResponse.toString()); //AjaxError error = new AjaxError(); //error.request = request; //error.options = options; e.status = e.status; e.reason = e.reason; //error.status = e.status; //error.reason = e.reason; //error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); //e.error = error; if (options.debug()) Log.i("Ajax", "Error " + e.status + ": " + e.reason); return e; } else { //handle ajax ifModified option List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified"); if (lastModifiedHeaders.size() >= 1) { try { String h = lastModifiedHeaders.get(0); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); Date lastModified = format.parse(h); if (options.ifModified() && lastModified != null) { Date lastModifiedDate; synchronized (lastModifiedUrls) { lastModifiedDate = lastModifiedUrls.get(options.url()); } if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) { //request response has not been modified. //Causes an error instead of a success. Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = e.status; e.reason = e.reason; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; Function func = options.statusCode().get(304); if (func != null) { if (options.context() != null) func.invoke($.with(options.context())); else func.invoke(null); } return e; } else { synchronized (lastModifiedUrls) { lastModifiedUrls.put(options.url(), lastModified); } } } } catch (Throwable t) { Log.e("Ajax", "Could not parse Last-Modified Header", t); } } //Now handle a successful request Success s = new Success(parsedResponse); s.reason = message; s.allHeaders = Headers.createHeaders(connection.getHeaderFields()); return s; } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); if (t instanceof java.net.SocketTimeoutException) { Error e = new Error(null); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; error.response = e.response; e.status = 0; String reason = t.getMessage(); if (reason == null) reason = "Socket Timeout"; e.reason = reason; error.status = e.status; error.reason = e.reason; if (connection != null) e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); else e.allHeaders = new Headers(); e.error = error; return e; } return null; } }
From source file:com.facebook.AccessToken.java
private void appendPermissions(StringBuilder builder) { builder.append(" permissions:"); if (this.permissions == null) { builder.append("null"); } else {// ww w . java2s.c om builder.append("["); builder.append(TextUtils.join(", ", permissions)); builder.append("]"); } }
From source file:de.azapps.mirakel.main_activity.MainActivity.java
/** * Is called if the user want to destroy a Task * * @param tasks, List of all Tasks which should be destroyed *//*w w w . jav a 2s . co m*/ public void handleDestroyTask(final List<Task> tasks) { if ((tasks == null) || (tasks.isEmpty())) { return; } final List<Task> normalTasks = new ArrayList<>(tasks.size()); // Tasks we should handle in a special way for (Task t : tasks) { if (t.getRecurrence().isPresent()) { handleDestroyRecurringTask(t); } else if (t.countSubtasks() > 0L) { handleDestroySubtasks(t); } else { normalTasks.add(t); } } // This must then be a bug in a ROM if (normalTasks.isEmpty()) { return; } final String names = TextUtils.join(", ", normalTasks); new AlertDialog.Builder(this) .setTitle(getResources().getQuantityString(R.plurals.task_delete, normalTasks.size())) .setMessage(this.getString(R.string.delete_content, names)) .setPositiveButton(this.getString(android.R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { for (final Task t : normalTasks) { t.destroy(); } updateAfterDestroy(); } }).setNegativeButton(this.getString(android.R.string.no), null).show(); if (getTasksFragment() != null) { getTasksFragment().updateList(); } }
From source file:org.strongswan.android.ui.VpnProfileImportActivity.java
private String getSubnets(JSONObject split, String key) throws JSONException { ArrayList<String> subnets = new ArrayList<>(); JSONArray arr = split.optJSONArray(key); if (arr != null) { for (int i = 0; i < arr.length(); i++) { /* replace all spaces, e.g. in "192.168.1.1 - 192.168.1.10" */ subnets.add(arr.getString(i).replace(" ", "")); }// w ww.ja v a 2 s .c o m } else { String value = split.optString(key, null); if (!TextUtils.isEmpty(value)) { subnets.add(value); } } if (subnets.size() > 0) { String joined = TextUtils.join(" ", subnets); IPRangeSet ranges = IPRangeSet.fromString(joined); if (ranges == null) { throw new JSONException(getString(R.string.profile_import_failed_value, "split-tunneling." + key)); } return ranges.toString(); } return null; }
From source file:com.facebook.android.friendsmash.HomeFragment.java
private void sendFilteredChallenge() { // Okay, we're going to filter our friends by their device, we're looking for friends with an Android device // Show the progressContainer during the network call progressContainer.setVisibility(View.VISIBLE); // Get a list of the user's friends' names and devices final Session session = Session.getActiveSession(); Request friendDevicesGraphPathRequest = Request.newGraphPathRequest(session, "me/friends", new Request.Callback() { @Override/* w w w . ja va2s.c om*/ public void onCompleted(Response response) { // Hide the progressContainer now that the network call has completed progressContainer.setVisibility(View.INVISIBLE); FacebookRequestError error = response.getError(); if (error != null) { Log.e(FriendSmashApplication.TAG, error.toString()); ((HomeActivity) getActivity()).handleError(error, false); } else if (session == Session.getActiveSession()) { if (response != null) { // Get the result GraphObject graphObject = response.getGraphObject(); JSONArray dataArray = (JSONArray) graphObject.getProperty("data"); if (dataArray.length() > 0) { // Ensure the user has at least one friend ... // Store the filtered friend ids in the following List ArrayList<String> filteredFriendIDs = new ArrayList<String>(); for (int i = 0; i < dataArray.length(); i++) { JSONObject currentUser = dataArray.optJSONObject(i); if (currentUser != null) { JSONArray currentUserDevices = currentUser.optJSONArray("devices"); if (currentUserDevices != null) { // The user has at least one (mobile) device logged into Facebook for (int j = 0; j < currentUserDevices.length(); j++) { JSONObject currentUserDevice = currentUserDevices .optJSONObject(j); if (currentUserDevice != null) { String currentUserDeviceOS = currentUserDevice .optString("os"); if (currentUserDeviceOS != null) { if (currentUserDeviceOS.equals("Android")) { filteredFriendIDs.add(currentUser.optString("id")); } } } } } } } // Now we have a list of friends with an Android device, we can send requests to them Bundle params = new Bundle(); // Uncomment following link once uploaded on Google Play for deep linking // params.putString("link", "https://play.google.com/store/apps/details?id=com.facebook.android.friendsmash"); // We create our parameter dictionary as we did before params.putString("message", "I just smashed " + application.getScore() + " friends! Can you beat it?"); // We have the same list of suggested friends String[] suggestedFriends = { "695755709", "685145706", "569496010", "286400088", "627802916", }; // Of course, not all of our suggested friends will have Android devices - we need to filter them down ArrayList<String> validSuggestedFriends = new ArrayList<String>(); // So, we loop through each suggested friend for (String suggestedFriend : suggestedFriends) { // If they are on our device filtered list, we know they have an Android device if (filteredFriendIDs.contains(suggestedFriend)) { // So we can call them valid validSuggestedFriends.add(suggestedFriend); } } params.putString("suggestions", TextUtils.join(",", validSuggestedFriends .toArray(new String[validSuggestedFriends.size()]))); // Show FBDialog without a notification bar showDialogWithoutNotificationBar("apprequests", params); } } } } }); // Pass in the fields as extra parameters, then execute the Request Bundle extraParamsBundle = new Bundle(); extraParamsBundle.putString("fields", "name,devices"); friendDevicesGraphPathRequest.setParameters(extraParamsBundle); Request.executeBatchAsync(friendDevicesGraphPathRequest); }
From source file:org.strongswan.android.ui.VpnProfileImportActivity.java
private String getApps(JSONArray arr) throws JSONException { ArrayList<String> apps = new ArrayList<>(); if (arr != null) { for (int i = 0; i < arr.length(); i++) { apps.add(arr.getString(i));//from www .j a v a 2s.c om } } return TextUtils.join(" ", apps); }