List of usage examples for android.text TextUtils join
public static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens)
From source file:eu.faircode.netguard.ServiceSinkhole.java
public static List<InetAddress> getDns(Context context) { List<InetAddress> listDns = new ArrayList<>(); List<String> sysDns = Util.getDefaultDNS(context); // Get custom DNS servers SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean ip6 = prefs.getBoolean("ip6", true); String vpnDns1 = prefs.getString("dns", null); String vpnDns2 = prefs.getString("dns2", null); Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN1=" + vpnDns1 + " VPN2=" + vpnDns2); if (vpnDns1 != null) try {//from www .j av a 2s . c om InetAddress dns = InetAddress.getByName(vpnDns1); if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()) && (ip6 || dns instanceof Inet4Address)) listDns.add(dns); } catch (Throwable ignored) { } if (vpnDns2 != null) try { InetAddress dns = InetAddress.getByName(vpnDns2); if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()) && (ip6 || dns instanceof Inet4Address)) listDns.add(dns); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } // Use system DNS servers only when no two custom DNS servers specified if (listDns.size() <= 1) for (String def_dns : sysDns) try { InetAddress ddns = InetAddress.getByName(def_dns); if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress()) && (ip6 || ddns instanceof Inet4Address)) listDns.add(ddns); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } // Remove local DNS servers when not routing LAN boolean lan = prefs.getBoolean("lan", false); boolean use_hosts = prefs.getBoolean("filter", false) && prefs.getBoolean("use_hosts", false); if (lan && use_hosts) { List<InetAddress> listLocal = new ArrayList<>(); try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); if (nis != null) while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); if (ni != null && ni.isUp() && !ni.isLoopback()) { List<InterfaceAddress> ias = ni.getInterfaceAddresses(); if (ias != null) for (InterfaceAddress ia : ias) { InetAddress hostAddress = ia.getAddress(); BigInteger host = new BigInteger(1, hostAddress.getAddress()); int prefix = ia.getNetworkPrefixLength(); BigInteger mask = BigInteger.valueOf(-1) .shiftLeft(hostAddress.getAddress().length * 8 - prefix); for (InetAddress dns : listDns) if (hostAddress.getAddress().length == dns.getAddress().length) { BigInteger ip = new BigInteger(1, dns.getAddress()); if (host.and(mask).equals(ip.and(mask))) { Log.i(TAG, "Local DNS server host=" + hostAddress + "/" + prefix + " dns=" + dns); listLocal.add(dns); } } } } } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } List<InetAddress> listDns4 = new ArrayList<>(); List<InetAddress> listDns6 = new ArrayList<>(); try { listDns4.add(InetAddress.getByName("8.8.8.8")); listDns4.add(InetAddress.getByName("8.8.4.4")); if (ip6) { listDns6.add(InetAddress.getByName("2001:4860:4860::8888")); listDns6.add(InetAddress.getByName("2001:4860:4860::8844")); } } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } for (InetAddress dns : listLocal) { listDns.remove(dns); if (dns instanceof Inet4Address) { if (listDns4.size() > 0) { listDns.add(listDns4.get(0)); listDns4.remove(0); } } else { if (listDns6.size() > 0) { listDns.add(listDns6.get(0)); listDns6.remove(0); } } } } return listDns; }
From source file:illab.nabal.proxy.TwitterProxy.java
/** * Get a Twitter profile corresponding to given user name. * /* ww w . j a v a 2 s . c o m*/ * @param userNames * @return list of TwitterProfile objects * @throws Exception */ private List<TwitterProfile> getProfilesByUserName(String[] userNames) throws Exception { String apiUri = "/users/lookup.json"; // throw an exception if user name is invalid if (userNames == null || userNames.length == 0) { throw new SystemException("No user name is specified."); } // check paramter length else if (userNames.length > 100) { throw new SystemException("user names should be no more than 100."); } String commaSeparatedUserNames = TextUtils.join(",", userNames); return populateProfileList(getJsonArray(getResponseString( getHttpPost(apiUri, new BasicNameValuePair("screen_name", commaSeparatedUserNames), new BasicNameValuePair("include_entities", "true"))))); }
From source file:com.landenlabs.all_devtool.PackageFragment.java
/** * Delete cache files.//from w ww.jav a2 s . c o m */ private void deleteCaches() { ArrayList<PackageInfo> uninstallList = new ArrayList<PackageInfo>(); for (PackingItem packageItem : m_list) { if (packageItem.m_checked) { try { PackageInfo packInfo = packageItem.m_packInfo; long cacheSize = 0; long fileCount = 0; Context mContext = getActivity().createPackageContext(packInfo.packageName, Context.CONTEXT_IGNORE_SECURITY); File cacheDirectory = null; Utils.DirSizeCount cacheDirSize = null; if (mContext.getCacheDir() != null) { cacheDirectory = mContext.getCacheDir(); // cacheSize = cacheDirectory.length()/1024; cacheDirSize = Utils.getDirectorySize(cacheDirectory); if (cacheDirSize == null) { // Cache is not readable or empty, // Try and map cache dir to one of the sd storage paths for (String storageDir : m_storageDirs) { try { File cacheDirectory2 = new File(cacheDirectory.getCanonicalPath() .replace("/data/data", storageDir + "/Android/data")); if (cacheDirectory2.exists()) { cacheDirectory = cacheDirectory2; cacheDirSize = Utils.getDirectorySize(cacheDirectory); break; } } catch (Exception ex) { m_log.d(ex.getMessage()); } } } if (cacheDirSize != null) { List<String> deletedFiles = Utils.deleteFiles(cacheDirectory); if (deletedFiles == null || deletedFiles.isEmpty()) { } else { String fileMsg = TextUtils.join("\n", deletedFiles.toArray()); Toast.makeText(getContext(), packageItem.m_appName + "\n" + fileMsg, Toast.LENGTH_LONG).show(); } } } } catch (Exception ex) { m_log.e(ex.getLocalizedMessage()); } } } // ((BaseExpandableListAdapter) m_listView.getExpandableListAdapter()).notifyDataSetChanged(); // updateList(); loadPackages(); }
From source file:com.parse.OfflineStore.java
private Task<Void> deleteObjects(final List<String> uuids, final ParseSQLiteDatabase db) { if (uuids.size() <= 0) { return Task.forResult(null); }//from ww w. j a v a 2 s . c om // SQLite has a max 999 SQL variables in a statement, so we need to split it up into manageable // chunks. We can do this because we're already in a transaction. if (uuids.size() > MAX_SQL_VARIABLES) { return deleteObjects(uuids.subList(0, MAX_SQL_VARIABLES), db) .onSuccessTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { return deleteObjects(uuids.subList(MAX_SQL_VARIABLES, uuids.size()), db); } }); } String[] placeholders = new String[uuids.size()]; for (int i = 0; i < placeholders.length; i++) { placeholders[i] = "?"; } String where = OfflineSQLiteOpenHelper.KEY_UUID + " IN (" + TextUtils.join(",", placeholders) + ")"; // dynamic args String[] args = uuids.toArray(new String[uuids.size()]); return db.deleteAsync(OfflineSQLiteOpenHelper.TABLE_OBJECTS, where, args); }
From source file:jp.mixi.android.sdk.MixiContainerImpl.java
private boolean startSingleSignOn(Activity activity, int activityCode, String[] permissions) { // ?????intent???? Intent intent = new Intent(); intent.putExtra("mode", "authorize"); intent.setClassName(OFFICIAL_PACKAGE, AUTH_ACTIVITY); intent.putExtra(CLIENT_ID, mClientId); // ??/* ww w . ja v a 2s. c om*/ if (permissions != null && permissions.length > 0) { intent.putExtra("scope", TextUtils.join(" ", permissions)); } // state? intent.putExtra(STATE, String.valueOf(new Random().nextLong() >>> 1)); if (!validateOfficialAppsForIntent(activity, intent, VALIDATE_OFFICIAL_FOR_ACTIVITY, SUPPORTED_VERSION)) { return false; } try { activity.startActivityForResult(intent, activityCode); } catch (ActivityNotFoundException e) { Log.v(TAG, e.getMessage()); return false; } return true; }
From source file:org.sirimangalo.meditationplus.ActivityMain.java
private void populateOnline(JSONArray onlines) { if (onlines.length() == 0) { onlineList.setVisibility(View.GONE); return;//from w ww .j a v a 2 s . co m } onlineList.setVisibility(View.VISIBLE); ArrayList<JSONObject> onlineArray = new ArrayList<JSONObject>(); ArrayList<String> onlineNamesArray = new ArrayList<String>(); // collect into array for (int i = 0; i < onlines.length(); i++) { try { JSONObject a = onlines.getJSONObject(i); onlineArray.add(a); onlineNamesArray.add(a.getString("username")); } catch (JSONException e) { e.printStackTrace(); } } String text = getString(R.string.online) + " "; // add spans int pos = text.length(); // start after "Online: " text += TextUtils.join(", ", onlineNamesArray); Spannable span = new SpannableString(text); span.setSpan(new StyleSpan(Typeface.BOLD), 0, pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // bold the "Online: " Drawable android = context.getResources().getDrawable(R.drawable.android); android.setBounds(0, 0, 48, 32); for (JSONObject oneOnA : onlineArray) { try { final String oneOn = oneOnA.getString("username"); int end = pos + oneOn.length(); boolean isMed = false; for (int j = 0; j < jsonList.length(); j++) { JSONObject user = jsonList.getJSONObject(j); String username = user.getString("username"); if (username.equals(oneOn)) isMed = true; } if (oneOnA.getString("source").equals("android")) { ImageSpan image = new ImageSpan(android, ImageSpan.ALIGN_BASELINE); span.setSpan(image, pos - 1, pos, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } ClickableSpan clickable = new ClickableSpan() { @Override public void onClick(View widget) { showProfile(oneOn); } }; span.setSpan(clickable, pos, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); span.setSpan(new UnderlineSpan() { public void updateDrawState(TextPaint tp) { tp.setUnderlineText(false); } }, pos, end, 0); span.setSpan(new ForegroundColorSpan(isMed ? 0xFF009900 : 0xFFFF9900), pos, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); pos += oneOn.length() + 2; } catch (JSONException e) { e.printStackTrace(); } } onlineList.setText(span); onlineList.setMovementMethod(LinkMovementMethod.getInstance()); }
From source file:com.android.mail.ui.ConversationViewFragment.java
@Override public void showExternalResources(final String senderRawAddress) { mWebView.getSettings().setBlockNetworkImage(false); final Address sender = getAddress(senderRawAddress); if (sender == null) { // Don't need to unblock any images return;//from www .j a v a 2s. co m } final MessageCursor cursor = getMessageCursor(); final List<String> messageDomIds = new ArrayList<>(); int pos = -1; while (cursor.moveToPosition(++pos)) { final ConversationMessage message = cursor.getMessage(); if (sender.equals(getAddress(message.getFrom()))) { message.alwaysShowImages = true; mViewState.setShouldShowImages(message, true); messageDomIds.add(mTemplates.getMessageDomId(message)); } } final String url = String.format("javascript:unblockImages(['%s']);", TextUtils.join("','", messageDomIds)); mWebView.loadUrl(url); }
From source file:com.annanovas.bestprice.DashBoardEditActivity.java
private void generateBrandRecyclerView() { sectionAdapter = new SectionedRecyclerViewAdapter(); myDB.open();//w ww. j av a2s . c om for (int i = 0; i < selectedProductIdList.size(); i++) { chosenBrandList.add(new ArrayList<String>()); ArrayList<BrandObject> brandArrayList = myDB.getAllBrands(selectedProductIdList.get(i)); showLog("Size " + chosenBrandIdList.size()); if (chosenBrandIdList.size() != 0) { for (int j = 0; j < brandArrayList.size(); j++) { String cellId = String.valueOf(brandArrayList.get(j).getId()); if (chosenBrandIdList.contains(cellId)) { BrandObject loop = brandArrayList.get(j); loop.setChecked(true); brandArrayList.set(j, loop); chosenBrandList.get(i).add(loop.getName()); showLog("Brand " + loop.getName()); } } } String sectionTag = String.format("section%sTag", getRandomStringNumber()); sectionAdapter.addSection(sectionTag, new BrandSectionAdapter(i, getApplicationContext(), sectionTag, selectedProductList.get(i), brandArrayList)); } if (chosenBrandIdList.size() != 0) { brandName = ""; for (int i = 0; i < chosenBrandList.size(); i++) { if (chosenBrandList.get(i).size() > 0) { //brandName += productTypeList[i] + ":" + TextUtils.join(", ", chosenBrandList.get(i)) + "\n"; brandName += selectedProductList.get(i) + ":" + TextUtils.join(", ", chosenBrandList.get(i)) + "\n"; showLog("Product " + selectedProductList.get(i)); } } tvDealerShipWith.setText(brandName); } myDB.close(); LinearLayoutManager linearLayoutManager3 = new LinearLayoutManager(DashBoardEditActivity.this); brandRecyclerView.setLayoutManager(linearLayoutManager3); brandRecyclerView.setItemAnimator(new DefaultItemAnimator()); brandRecyclerView.setAdapter(sectionAdapter); brandRecyclerView.setNestedScrollingEnabled(false); etBrandSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String newText = s.toString(); for (Section section : sectionAdapter.getSectionsMap().values()) { if (section instanceof FilterableSection) { ((FilterableSection) section).filter(newText); } } sectionAdapter.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable s) { } }); }
From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java
/** * Limit the number of cached files per art source to {@link #MAX_CACHE_SIZE}. * @see #MAX_CACHE_SIZE/*from ww w . java2s .c o m*/ */ private void cleanupCachedFiles() { Context context = getContext(); if (context == null) { return; } Cursor sources = querySource(MuzeiContract.Sources.CONTENT_URI, new String[] { MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME }, null, null, null); if (sources == null) { return; } // Access to certain artwork can be persisted through MuzeiDocumentsProvider // We never want to delete these artwork as that would break other apps Set<Uri> persistedUris = MuzeiDocumentsProvider.getPersistedArtworkUris(context); // Loop through each source, cleaning up old artwork while (sources.moveToNext()) { String componentName = sources.getString(0); // Now use that ComponentName to look through the past artwork from that source Cursor artworkBySource = queryArtwork(MuzeiContract.Artwork.CONTENT_URI, new String[] { BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, MuzeiContract.Artwork.COLUMN_NAME_TOKEN }, MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME + "=?", new String[] { componentName }, MuzeiContract.Artwork.COLUMN_NAME_DATE_ADDED + " DESC"); if (artworkBySource == null) { continue; } List<String> artworkIdsToKeep = new ArrayList<>(); List<String> artworkToKeep = new ArrayList<>(); // First find all of the persisted artwork from this source and mark them as artwork to keep while (artworkBySource.moveToNext()) { long id = artworkBySource.getLong(0); Uri uri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, id); String artworkUri = artworkBySource.getString(1); String artworkToken = artworkBySource.getString(2); String unique = !TextUtils.isEmpty(artworkUri) ? artworkUri : artworkToken; if (persistedUris.contains(uri)) { // Always keep artwork that is persisted artworkIdsToKeep.add(Long.toString(id)); artworkToKeep.add(unique); } } // Now go through the artwork from this source and find the most recent artwork // and mark them as artwork to keep int count = 0; artworkBySource.moveToPosition(-1); while (artworkBySource.moveToNext()) { // BaseColumns._ID is a long, but we need it as a String later anyways String id = artworkBySource.getString(0); String artworkUri = artworkBySource.getString(1); String artworkToken = artworkBySource.getString(2); String unique = !TextUtils.isEmpty(artworkUri) ? artworkUri : artworkToken; if (artworkToKeep.contains(unique)) { // This ensures we are double counting the same artwork in our count artworkIdsToKeep.add(id); continue; } if (count++ < MAX_CACHE_SIZE) { // Keep artwork below the MAX_CACHE_SIZE artworkIdsToKeep.add(id); artworkToKeep.add(unique); } } // Now delete all artwork not in the keep list int numDeleted = deleteArtwork(MuzeiContract.Artwork.CONTENT_URI, MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME + "=?" + " AND " + MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " NOT IN (" + TextUtils.join(",", artworkIdsToKeep) + ")", new String[] { componentName }); if (numDeleted > 0) { Log.d(TAG, "For " + componentName + " kept " + artworkToKeep.size() + " artwork, deleted " + numDeleted); } artworkBySource.close(); } sources.close(); }
From source file:com.android.mail.browse.MessageHeaderView.java
/** * Render an email list for the expanded message details view. *//*from w w w. ja v a 2 s . c o m*/ private static void renderEmailList(Resources res, int headerId, int detailsId, String[] emails, String viaDomain, View rootView, Map<String, Address> addressCache, Account account, VeiledAddressMatcher veiledMatcher, BidiFormatter bidiFormatter) { if (emails == null || emails.length == 0) { return; } final String[] formattedEmails = new String[emails.length]; for (int i = 0; i < emails.length; i++) { final Address email = Utils.getAddress(addressCache, emails[i]); String name = email.getPersonal(); final String address = email.getAddress(); // Check if the address here is a veiled address. If it is, we need to display an // alternate layout final boolean isVeiledAddress = veiledMatcher != null && veiledMatcher.isVeiledAddress(address); final String addressShown; if (isVeiledAddress) { // Add the warning at the end of the name, and remove the address. The alternate // text cannot be put in the address part, because the address is made into a link, // and the alternate human-readable text is not a link. addressShown = ""; if (TextUtils.isEmpty(name)) { // Empty name and we will block out the address. Let's write something more // readable. name = res.getString(VeiledAddressMatcher.VEILED_ALTERNATE_TEXT_UNKNOWN_PERSON); } else { name = name + res.getString(VeiledAddressMatcher.VEILED_ALTERNATE_TEXT); } } else { addressShown = address; } if (name == null || name.length() == 0 || name.equalsIgnoreCase(addressShown)) { formattedEmails[i] = bidiFormatter.unicodeWrap(addressShown); } else { // The one downside to having the showViaDomain here is that // if the sender does not have a name, it will not show the via info if (viaDomain != null) { formattedEmails[i] = res.getString(R.string.address_display_format_with_via_domain, bidiFormatter.unicodeWrap(name), bidiFormatter.unicodeWrap(addressShown), bidiFormatter.unicodeWrap(viaDomain)); } else { formattedEmails[i] = res.getString(R.string.address_display_format, bidiFormatter.unicodeWrap(name), bidiFormatter.unicodeWrap(addressShown)); } } } rootView.findViewById(headerId).setVisibility(VISIBLE); final TextView detailsText = (TextView) rootView.findViewById(detailsId); detailsText.setText(TextUtils.join("\n", formattedEmails)); stripUnderlines(detailsText, account); detailsText.setVisibility(VISIBLE); }