Example usage for android.util Pair Pair

List of usage examples for android.util Pair Pair

Introduction

In this page you can find the example usage for android.util Pair Pair.

Prototype

public Pair(F first, S second) 

Source Link

Document

Constructor for a Pair.

Usage

From source file:com.zd.vpn.fragments.AboutFragment.java

private Pair<String, String> getSkuTitle(final String sku, String title, String price,
        ArrayList<String> ownedSkus) {
    String text;/*from   www .  j  a va  2 s.co m*/
    if (ownedSkus.contains(sku))
        return new Pair<String, String>(getString(R.string.thanks_for_donation, price), null);

    if (price.contains("") || price.contains("\u20ac")) {
        text = title;
    } else {
        text = String.format(Locale.getDefault(), "%s (%s)", title, price);
    }
    //return text;
    return new Pair<String, String>(price, sku);

}

From source file:com.microsoft.windowsazure.mobileservices.http.MobileServiceHttpClient.java

/**
 * Makes a request over HTTP//from w ww .j  a  va2s. com
 *
 * @param path           The path of the request URI
 * @param content        The byte array to send as the request body
 * @param httpMethod     The HTTP Method used to invoke the API
 * @param requestHeaders The extra headers to send in the request
 * @param parameters     The query string parameters sent in the request
 * @param features       The features used in the request
 */
public ListenableFuture<ServiceFilterResponse> request(String path, byte[] content, String httpMethod,
        List<Pair<String, String>> requestHeaders, List<Pair<String, String>> parameters,
        EnumSet<MobileServiceFeatures> features) {
    final SettableFuture<ServiceFilterResponse> future = SettableFuture.create();

    if (path == null || path.trim().equals("")) {
        future.setException(new IllegalArgumentException("request path cannot be null"));
        return future;
    }

    if (httpMethod == null || httpMethod.trim().equals("")) {
        future.setException(new IllegalArgumentException("httpMethod cannot be null"));
        return future;
    }

    Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon();
    uriBuilder.path(path);

    if (parameters != null && parameters.size() > 0) {
        for (Pair<String, String> parameter : parameters) {
            uriBuilder.appendQueryParameter(parameter.first, parameter.second);
        }
    }

    ServiceFilterRequestImpl request;
    String url = uriBuilder.build().toString();

    if (httpMethod.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpGet(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPost(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPut(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpPatch(url), mClient.getAndroidHttpClientFactory());
    } else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
        request = new ServiceFilterRequestImpl(new HttpDelete(url), mClient.getAndroidHttpClientFactory());
    } else {
        future.setException(new IllegalArgumentException("httpMethod not supported"));
        return future;
    }

    String featuresHeader = MobileServiceFeatures.featuresToString(features);
    if (featuresHeader != null) {
        if (requestHeaders == null) {
            requestHeaders = new ArrayList<Pair<String, String>>();
        }

        boolean containsFeatures = false;
        for (Pair<String, String> header : requestHeaders) {
            if (header.first.equals(X_ZUMO_FEATURES)) {
                containsFeatures = true;
                break;
            }
        }

        if (!containsFeatures) {
            // Clone header list to prevent changing user's list
            requestHeaders = new ArrayList<Pair<String, String>>(requestHeaders);
            requestHeaders.add(new Pair<String, String>(X_ZUMO_FEATURES, featuresHeader));
        }
    }

    if (requestHeaders != null && requestHeaders.size() > 0) {
        for (Pair<String, String> header : requestHeaders) {
            request.addHeader(header.first, header.second);
        }
    }

    if (content != null) {
        try {
            request.setContent(content);
        } catch (Exception e) {
            future.setException(e);
            return future;
        }
    }

    MobileServiceConnection conn = mClient.createConnection();

    new RequestAsyncTask(request, conn) {
        @Override
        protected void onPostExecute(ServiceFilterResponse response) {
            if (mTaskException != null) {
                future.setException(mTaskException);
            } else {
                future.set(response);
            }
        }
    }.executeTask();

    return future;
}

From source file:com.normsstuff.maps4norm.Util.java

/**
 * Calculates the up- & downwards elevation along the passed trace.
 * <p/>// w  ww .ja va2  s .  com
 * This method might need to connect to the Google Elevation API and
 * therefore must not be called from the main UI thread.
 *
 * @param trace the list of LatLng objects
 * @return null if an error occurs, a pair of two float values otherwise:
 * first one is the upwards elevation, second one downwards
 * <p/>
 * based on
 * http://stackoverflow.com/questions/1995998/android-get-altitude
 * -by-longitude-and-latitude
 */
static Pair<Float, Float> getElevation(final List<LatLng> trace) {
    float up = 0, down = 0;
    float lastElevation = -Float.MAX_VALUE, currentElevation;
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    float difference;
    try {
        for (LatLng p : trace) {
            currentElevation = getAltitude(p, httpClient, localContext);

            // current and last point have a valid elevation data ->
            // calculate difference
            if (currentElevation > -Float.MAX_VALUE && lastElevation > -Float.MAX_VALUE) {
                difference = currentElevation - lastElevation;
                if (difference > 0)
                    up += difference;
                else
                    down += difference;
            }
            lastElevation = currentElevation;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return new Pair<Float, Float>(up, down);
}

From source file:co.uk.alt236.restclient4android.net.Connection.java

private ArrayList<Pair<String, String>> getHeaders(HttpResponse response) {
    Log.i(TAG, "^ CONNECTION: getting headers");

    ArrayList<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
    Header[] httpHeaders = response.getAllHeaders();

    if (httpHeaders == null) {
        return headers;
    }/*from   w ww.  j av  a2  s  .c om*/

    for (Header entry : httpHeaders) {
        String headerName = entry.getName();
        String headerValue = entry.getValue();

        if (headerName == null) {
            headerName = "";
        }
        if (headerValue == null) {
            headerValue = "";
        }

        headers.add(new Pair<String, String>(headerName, headerValue));
    }

    return headers;
}

From source file:com.brettyin.cardshelper.fragment.SignInFragment.java

private void performSignInWithTransition(View v) {
    final Activity activity = getActivity();

    final Pair[] pairs = TransitionHelper.createSafeTransitionParticipants(activity, true,
            new Pair<>(v, activity.getString(R.string.transition_avatar)));
    ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(activity, pairs);
    //CategorySelectionActivity.start(activity, mPlayer, activityOptions);
}

From source file:net.zionsoft.obadiah.model.Bible.java

public void loadTranslations(boolean forceRefresh, final OnTranslationsLoadedListener listener) {
    if (!forceRefresh && mDownloadedTranslations != null && mAvailableTranslations != null) {
        listener.onTranslationsLoaded(mDownloadedTranslations, mAvailableTranslations);
        return;//w  ww .j  a v  a  2  s .c  o  m
    }

    if (!NetworkHelper.isOnline(mContext)) {
        // do nothing if network is not available
        listener.onTranslationsLoaded(null, null);
        return;
    }

    new AsyncTask<Void, Void, Pair<List<TranslationInfo>, List<TranslationInfo>>>() {
        private final long mTimestamp = SystemClock.elapsedRealtime();

        @Override
        protected Pair<List<TranslationInfo>, List<TranslationInfo>> doInBackground(Void... params) {
            List<TranslationInfo> translations = null;
            try {
                translations = downloadTranslationList(NetworkHelper.PRIMARY_TRANSLATIONS_LIST_URL);
            } catch (Exception e) {
                Crashlytics.logException(e);
            }
            if (translations == null) {
                try {
                    translations = downloadTranslationList(NetworkHelper.SECONDARY_TRANSLATIONS_LIST_URL);
                } catch (Exception e) {
                    Crashlytics.logException(e);
                    return null;
                }
            }

            if (mDownloadedTranslationShortNames == null) {
                // this should not happen, but just in case
                mDownloadedTranslationShortNames = Collections
                        .unmodifiableList(getDownloadedTranslationShortNames());
            }

            final List<TranslationInfo> downloaded = new ArrayList<TranslationInfo>(
                    mDownloadedTranslationShortNames.size());
            final List<TranslationInfo> available = new ArrayList<TranslationInfo>(
                    translations.size() - mDownloadedTranslationShortNames.size());
            translations = TranslationHelper.sortByLocale(translations);
            for (TranslationInfo translation : translations) {
                boolean isDownloaded = false;
                for (String translationShortName : mDownloadedTranslationShortNames) {
                    if (translation.shortName.equals(translationShortName)) {
                        isDownloaded = true;
                        break;
                    }
                }
                if (isDownloaded)
                    downloaded.add(translation);
                else
                    available.add(translation);
            }

            return new Pair<List<TranslationInfo>, List<TranslationInfo>>(downloaded, available);
        }

        @Override
        protected void onPostExecute(Pair<List<TranslationInfo>, List<TranslationInfo>> result) {
            final boolean isSuccessful = result != null;
            Analytics.trackTranslationListDownloading(isSuccessful, SystemClock.elapsedRealtime() - mTimestamp);

            if (isSuccessful) {
                mDownloadedTranslations = result.first;
                mAvailableTranslations = result.second;
            } else {
                mDownloadedTranslations = null;
                mAvailableTranslations = null;
            }
            listener.onTranslationsLoaded(mDownloadedTranslations, mAvailableTranslations);
        }
    }.execute();
}

From source file:com.android.screenspeak.eventprocessor.ProcessorFocusAndSingleTap.java

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    if (!mAccessibilityManager.isTouchExplorationEnabled()) {
        // Don't manage focus when touch exploration is disabled.
        return;/*w w  w  . j  a  v a2s. c o  m*/
    }

    final AccessibilityRecordCompat record = AccessibilityEventCompat.asRecord(event);

    switch (event.getEventType()) {
    case AccessibilityEvent.TYPE_VIEW_CLICKED:
        // Prevent conflicts between lift-to-type and single tap. This
        // is only necessary when a CLICKED event occurs during a touch
        // interaction sequence (e.g. before an INTERACTION_END event),
        // but it isn't harmful to call more often.
        cancelSingleTap();
        break;
    case AccessibilityEvent.TYPE_VIEW_FOCUSED:
    case AccessibilityEvent.TYPE_VIEW_SELECTED:
        if (!mFirstWindowFocusManager.shouldProcessFocusEvent(event)) {
            return;
        }
        boolean isViewFocusedEvent = (AccessibilityEvent.TYPE_VIEW_FOCUSED == event.getEventType());
        if (!setFocusOnView(record, isViewFocusedEvent)) {
            // It is possible that the only speakable child of source node is invisible
            // at the moment, but could be made visible when view scrolls, or window state
            // changes. Cache it now. And try to focus on the cached record on:
            // VIEW_SCROLLED, WINDOW_CONTENT_CHANGED, WINDOW_STATE_CHANGED.
            // The above 3 are the events that could affect view visibility.
            if (mCachedPotentiallyFocusableRecordQueue.size() == MAX_CACHED_FOCUSED_RECORD_QUEUE) {
                mCachedPotentiallyFocusableRecordQueue.remove().first.recycle();
            }

            mCachedPotentiallyFocusableRecordQueue
                    .add(new Pair<>(AccessibilityRecordCompat.obtain(record), event.getEventType()));
        } else {
            emptyCachedPotentialFocusQueue();
        }
        break;
    case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER:
        final AccessibilityNodeInfoCompat touchedNode = record.getSource();
        try {
            if ((touchedNode != null) && !setFocusFromViewHoverEnter(touchedNode)) {
                mHandler.sendEmptyTouchAreaFeedbackDelayed(touchedNode);
            }
        } finally {
            AccessibilityNodeInfoUtils.recycleNodes(touchedNode);
        }

        break;
    case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED:
        mHandler.cancelEmptyTouchAreaFeedback();
        AccessibilityNodeInfo source = event.getSource();
        if (source != null) {
            AccessibilityNodeInfoCompat compatSource = new AccessibilityNodeInfoCompat(source);
            mLastFocusedItem = AccessibilityNodeInfoCompat.obtain(compatSource);
        }
        break;
    case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
        mFirstWindowFocusManager.registerWindowChange(event);
        handleWindowStateChange(event);
        break;
    case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
        handleWindowContentChanged();
        break;
    case AccessibilityEvent.TYPE_VIEW_SCROLLED:
        handleViewScrolled(event, record);
        break;
    case AccessibilityEventCompat.TYPE_TOUCH_INTERACTION_START:
        // This event type only exists on API 17+ (JB MR1).
        handleTouchInteractionStart();
        break;
    case AccessibilityEventCompat.TYPE_TOUCH_INTERACTION_END:
        // This event type only exists on API 17+ (JB MR1).
        handleTouchInteractionEnd();
        break;
    }
}

From source file:com.arvos.arviewer.ArvosHttpRequest.java

private Pair<String, Bitmap> downloadImage(String url) {
    Bitmap bitmap;/*  w  w  w . j  a v  a 2  s  .  co  m*/
    try {
        bitmap = ArvosCache.getBitmap(url);
        if (bitmap != null) {
            return new Pair<String, Bitmap>("OK", bitmap);
        }
    } catch (Exception e) {
        return new Pair<String, Bitmap>("ERCache read error. " + e.getLocalizedMessage(), null);
    }

    InputStream inputStream = null;
    if (mInstance.mSimulateWeb) {
        try {
            if (url.contains("one.png")) {
                inputStream = mContext.getResources().openRawResource(R.raw.one);
            } else if (url.contains("two.png")) {
                inputStream = mContext.getResources().openRawResource(R.raw.two);
            } else if (url.contains("three.png")) {
                inputStream = mContext.getResources().openRawResource(R.raw.three);
            }

            if (inputStream != null) {
                bitmap = BitmapFactory.decodeStream(inputStream);
                try {
                    ArvosCache.add(url, bitmap);
                } catch (Exception e) {
                    return new Pair<String, Bitmap>("ERCache write error. " + e.getLocalizedMessage(), null);
                }

                return new Pair<String, Bitmap>("OK", bitmap);
            }
        } catch (Exception e) {
            return new Pair<String, Bitmap>("ERException. " + e.getLocalizedMessage(), null);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

    try {
        inputStream = openHttpGETConnection(url);
        bitmap = BitmapFactory.decodeStream(inputStream);
        try {
            ArvosCache.add(url, bitmap);
        } catch (Exception e) {
            return new Pair<String, Bitmap>("ERCache write error. " + e.getLocalizedMessage(), null);
        }

        return new Pair<String, Bitmap>("OK", bitmap);
    } catch (Exception e) {
        return new Pair<String, Bitmap>("ERNetwork error. " + e.getLocalizedMessage(), null);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.fastbootmobile.encore.app.fragments.SearchFragment.java

private void onAlbumClick(int i, View v) {
    if (mAdapter.getChildrenCount(SearchAdapter.ALBUM) > 1) {
        SearchAdapter.SearchEntry entry = mAdapter.getChild(SearchAdapter.ALBUM, i);

        if (entry.ref.equals(KEY_SPECIAL_MORE)) {
            mAdapter.setGroupMaxCount(SearchAdapter.ALBUM, mAdapter.getGroupMaxCount(SearchAdapter.ALBUM) + 5);
        } else {//from  w w w . j a v  a2 s. c  om
            SearchAdapter.ViewHolder holder = (SearchAdapter.ViewHolder) v.getTag();
            Bitmap hero = ((MaterialTransitionDrawable) holder.albumArtImageView.getDrawable())
                    .getFinalDrawable().getBitmap();
            int color = 0xffffff;
            if (hero != null) {
                Palette palette = Palette.generate(hero);
                Palette.Swatch darkVibrantColor = palette.getDarkVibrantSwatch();
                Palette.Swatch darkMutedColor = palette.getDarkMutedSwatch();

                if (darkVibrantColor != null) {
                    color = darkVibrantColor.getRgb();
                } else if (darkMutedColor != null) {
                    color = darkMutedColor.getRgb();
                } else {
                    color = getResources().getColor(R.color.default_album_art_background);
                }
            }

            Intent intent = AlbumActivity.craftIntent(getActivity(), hero, entry.ref, entry.identifier, color);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ImageView ivCover = holder.albumArtImageView;
                ActivityOptions opt = ActivityOptions.makeSceneTransitionAnimation(getActivity(),
                        new Pair<View, String>(ivCover, "itemImage"));
                getActivity().startActivity(intent, opt.toBundle());
            } else {
                startActivity(intent);
            }
        }
    }
}

From source file:com.jbirdvegas.mgerrit.ProjectsList.java

/**
 * Split the query as if it was the name (or part) of a base project,
 *  a sub project or base project/sub project. Note that providing the
 *  seperator in the query will change the results that are provided.
 * @param query The (partial) name of a base project, sub project or both.
 * @return A pair comprised of a base project and sub project matching the query
 *  to search for/*from  w  w  w  . j  av  a  2 s.  co m*/
 */
private Pair<String, String> splitQuery(String query) {
    String p[] = query.split(SEPERATOR, 2);
    if (p.length < 2)
        return new Pair<>(p[0], p[0]);
    else
        return new Pair<>(p[0], p[1]);
}