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.microsoft.firstapp.AuthService.java

/**
 * Handles logging in with custom auth/*  ww  w  . jav  a2  s . c o m*/
 * 
 * @param username
 * @param password
 * @param callback
 */
public void login(String username, String password, TableJsonOperationCallback callback) {
    JsonObject customUser = new JsonObject();
    customUser.addProperty("username", username);
    customUser.addProperty("password", password);

    List<Pair<String, String>> parameters = new ArrayList<Pair<String, String>>();
    parameters.add(new Pair<String, String>("login", "true"));

    mTableAccounts.insert(customUser, parameters, callback);
}

From source file:com.renard.documentview.DocumentAdapter.java

public Pair<List<Uri>, List<Spanned>> getTextsToSave() {
    List<Uri> documentIds = new ArrayList<Uri>();
    List<Spanned> texts = new ArrayList<Spanned>();

    for (Integer id : mChangedDocuments) {
        documentIds.add(Uri.withAppendedPath(DocumentContentProvider.CONTENT_URI, String.valueOf(id)));
        final CharSequence text = mChangedTexts.get(id);
        texts.add((Spanned) text);/*from w w w .j  av a  2  s. co  m*/
    }
    return new Pair<List<Uri>, List<Spanned>>(documentIds, texts);
}

From source file:cx.ring.model.Conversation.java

public String getLastInteractionSumary(Resources resources) {
    if (!current_calls.isEmpty()) {
        return resources.getString(R.string.ongoing_call);
    }// w  w w  .ja  va2  s  .c  om
    Pair<Date, String> d = new Pair<>(new Date(0), null);

    for (HistoryEntry e : history.values()) {
        Pair<Date, String> nd = e.getLastInteractionSumary(resources);
        if (nd == null)
            continue;
        if (d.first.compareTo(nd.first) < 0)
            d = nd;
    }
    return d.second;
}

From source file:io.v.example.vbeam.vbeamexample.MainActivity.java

@Override
public ListenableFuture<Pair<String, byte[]>> createIntent(VContext context, ServerCall call) {
    String blessing = "anonymous";
    String[] names = VSecurity.getRemoteBlessingNames(ctx, call.security());
    if (names.length > 0) {
        blessing = names[0];/*  w  w  w .ja v  a 2 s. co m*/
    }
    byte[] payload = ("Hello " + blessing).getBytes(Charset.forName("utf-8"));
    Intent intent = new Intent(this, GotBeamActivity.class);
    intent.setPackage(getApplicationContext().getPackageName());
    System.out.println("APP_SCHEME: " + intent.toUri(Intent.URI_ANDROID_APP_SCHEME));
    System.out.println("INTENT_SCHEME: " + intent.toUri(Intent.URI_INTENT_SCHEME));
    return Futures.immediateFuture(new Pair<>(intent.toUri(Intent.URI_INTENT_SCHEME), payload));
}

From source file:nz.ac.otago.psyanlab.common.ImportPaleActivity.java

@Override
public void onFilesPicked(File... files) {
    new AsyncTask<File, Void, Pair<ArrayList<String>, ArrayList<Long>>>() {
        @Override//from w  w w  . j av  a 2 s. c  o m
        protected Pair<ArrayList<String>, ArrayList<Long>> doInBackground(File... files) {
            ArrayList<Long> ids = new ArrayList<Long>();
            ArrayList<String> errored = new ArrayList<String>();
            for (int i = 0; i < files.length; i++) {
                Uri uri;
                try {
                    uri = mUserDelegate.addExperiment(files[i].getPath());
                } catch (JSONException e) {
                    errored.add(files[i].getName());
                    e.printStackTrace();
                    continue;
                } catch (IOException e) {
                    errored.add(files[i].getName());
                    e.printStackTrace();
                    continue;
                }
                ids.add(Long.parseLong(uri.getLastPathSegment()));
            }
            return new Pair<ArrayList<String>, ArrayList<Long>>(errored, ids);
        }

        @Override
        protected void onPostExecute(Pair<ArrayList<String>, ArrayList<Long>> result) {
            ArrayList<String> errored = result.first;
            ArrayList<Long> ids = result.second;
            if (errored.size() > 0) {
                toast(getResources().getString(R.string.format_error_importing, TextUtils.join(", ", errored)));
            }

            if (ids.size() > 0) {
                Intent r = new Intent();
                long[] lids = new long[ids.size()];
                for (int i = 0; i < ids.size(); i++) {
                    lids[i] = ids.get(i);
                }
                r.putExtra(RETURN_IDS, lids);
                setResult(RESULT_OK, r);
                finish();
            }
        };
    }.execute(files);
}

From source file:com.owncloud.android.lib.resources.shares.UpdateRemoteShareOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    /// prepare array of parameters to update
    List<Pair<String, String>> parametersToUpdate = new ArrayList<Pair<String, String>>();
    if (mPassword != null) {
        parametersToUpdate.add(new Pair<String, String>(PARAM_PASSWORD, mPassword));
    }//from   w  ww .j ava 2s.  c  o m
    if (mExpirationDateInMillis < 0) {
        // clear expiration date
        parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, ""));

    } else if (mExpirationDateInMillis > 0) {
        // set expiration date
        DateFormat dateFormat = new SimpleDateFormat(FORMAT_EXPIRATION_DATE);
        Calendar expirationDate = Calendar.getInstance();
        expirationDate.setTimeInMillis(mExpirationDateInMillis);
        String formattedExpirationDate = dateFormat.format(expirationDate.getTime());
        parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, formattedExpirationDate));

    } // else, ignore - no update

    /* TODO complete rest of parameters
    if (mPermissions > 0) {
    parametersToUpdate.add(new Pair("permissions", Integer.toString(mPermissions)));
    }
    if (mPublicUpload != null) {
    parametersToUpdate.add(new Pair("publicUpload", mPublicUpload.toString());
    }
    */

    /// perform required PUT requests
    PutMethod put = null;
    String uriString = null;

    try {
        Uri requestUri = client.getBaseUri();
        Uri.Builder uriBuilder = requestUri.buildUpon();
        uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH.substring(1));
        uriBuilder.appendEncodedPath(Long.toString(mRemoteId));
        uriString = uriBuilder.build().toString();

        for (Pair<String, String> parameter : parametersToUpdate) {
            if (put != null) {
                put.releaseConnection();
            }
            put = new PutMethod(uriString);
            put.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
            put.setRequestEntity(new StringRequestEntity(parameter.first + "=" + parameter.second,
                    ENTITY_CONTENT_TYPE, ENTITY_CHARSET));

            status = client.executeMethod(put);

            if (status == HttpStatus.SC_OK) {
                String response = put.getResponseBodyAsString();

                // Parse xml response
                ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser(
                        new ShareXMLParser());
                parser.setOwnCloudVersion(client.getOwnCloudVersion());
                parser.setServerBaseUri(client.getBaseUri());
                result = parser.parse(response);

            } else {
                result = new RemoteOperationResult(false, status, put.getResponseHeaders());
            }
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while updating remote share ", e);
        if (put != null) {
            put.releaseConnection();
        }

    } finally {
        if (put != null) {
            put.releaseConnection();
        }
    }
    return result;
}

From source file:com.is.rest.cache.CacheAwareHttpClient.java

/**
 * Intercepts all requests sent and run them through the cache policies
 * @see AsyncHttpClient#sendRequest(org.apache.http.impl.client.DefaultHttpClient, org.apache.http.protocol.HttpContext, org.apache.http.client.methods.HttpUriRequest, String, ResponseHandlerInterface, Context)
 *//*from   w ww.j a  v a2s  .c o m*/
@Override
@SuppressWarnings("unchecked")
protected RequestHandle sendRequest(final DefaultHttpClient client, final HttpContext httpContext,
        final HttpUriRequest uriRequest, final String contentType,
        final ResponseHandlerInterface responseHandler, final Context context) {

    Logger.d("CacheAwareHttpClient.sendRequest");

    AsyncTask<Void, Void, Pair<Object, Boolean>> task;

    if (Callback.class.isAssignableFrom(responseHandler.getClass())) {
        final Callback<Object> callback = (Callback<Object>) responseHandler;
        final CacheInfo cacheInfo = callback.getCacheInfo();
        callback.setCacheManager(cacheManager);
        if (callback.getCacheInfo().getKey() == null) {
            try {
                callback.getCacheInfo().setKey(uriRequest.getURI().toURL().toString());
            } catch (MalformedURLException e) {
                Logger.e("unchacheable because uri threw : ", e);
            }
        }

        task = new AsyncTask<Void, Void, Pair<Object, Boolean>>() {

            @Override
            public Pair<Object, Boolean> doInBackground(Void... params) {
                Pair<Object, Boolean> cachedResult = null;
                if (Callback.class.isAssignableFrom(responseHandler.getClass())) {
                    switch (callback.getCacheInfo().getPolicy()) {
                    case ENABLED:
                        try {
                            cachedResult = new Pair<Object, Boolean>(
                                    cacheManager.get(cacheInfo.getKey(), cacheInfo), false);
                        } catch (IOException e) {
                            Logger.e("cache error", e);
                        } catch (ClassNotFoundException e) {
                            Logger.e("cache error", e);
                        }
                        break;
                    case NETWORK_ENABLED:
                        try {
                            cachedResult = new Pair<Object, Boolean>(
                                    cacheManager.get(cacheInfo.getKey(), cacheInfo), true);
                        } catch (IOException e) {
                            Logger.e("cache error", e);
                        } catch (ClassNotFoundException e) {
                            Logger.e("cache error", e);
                        }
                        break;
                    case LOAD_IF_OFFLINE:
                        if (callback.getContext() == null) {
                            throw new IllegalArgumentException(
                                    "Attempt to use LOAD_IF_OFFLINE on a callback with no context provided. Context is required to lookup internet connectivity");
                        }
                        ConnectivityManager connectivityManager = (ConnectivityManager) callback.getContext()
                                .getSystemService(Context.CONNECTIVITY_SERVICE);
                        if (connectivityManager.getActiveNetworkInfo() != null
                                && connectivityManager.getActiveNetworkInfo().isConnected()) {
                            try {
                                cachedResult = new Pair<Object, Boolean>(
                                        cacheManager.get(cacheInfo.getKey(), cacheInfo), false);
                            } catch (IOException e) {
                                Logger.e("cache error", e);
                            } catch (ClassNotFoundException e) {
                                Logger.e("cache error", e);
                            }
                        }
                        break;
                    default:
                        break;

                    }
                }
                return cachedResult;
            }

            @Override
            public void onPostExecute(Pair<Object, Boolean> result) {
                if (result != null && result.first != null) {
                    Logger.d("CacheAwareHttpClient.sendRequest.onPostExecute proceeding with cache: " + result);
                    callback.getCacheInfo().setLoadedFromCache(true);
                    callback.onSuccess(HttpStatus.SC_OK, null, null, result.first);
                    if (result.second != null && result.second) { //retry request if necessary even if loaded from cache such as in NETWORK_ENABLED
                        if (Callback.class.isAssignableFrom(responseHandler.getClass())) {
                            Callback<Object> callback = (Callback<Object>) responseHandler;
                            CacheInfo secondCacheInfo = callback.getCacheInfo();
                            secondCacheInfo.setPolicy(CachePolicy.ENABLED);
                            secondCacheInfo.setLoadedFromCache(false);
                            try {
                                boolean invalidated = cacheManager.invalidate(secondCacheInfo.getKey());
                                Logger.d(String.format("Key: '%s' invalidated as result of second call: %s",
                                        secondCacheInfo.getKey(), invalidated));
                            } catch (IOException e) {
                                Logger.e("cache error", e);
                            }
                            Logger.d("Sending second cache filling call for " + uriRequest);
                            CacheAwareHttpClient.super.sendRequest(client, httpContext, uriRequest, contentType,
                                    responseHandler, context);
                        }
                    }
                } else {
                    Logger.d("CacheAwareHttpClient.sendRequest.onPostExecute proceeding uncached");
                    CacheAwareHttpClient.super.sendRequest(client, httpContext, uriRequest, contentType,
                            responseHandler, context);
                }
            }

        };
        ExecutionUtils.execute(task);
    }

    return new RequestHandle(null);
}

From source file:conexionSiabra.ConexionSiabra.java

public JSONObject modificarPermisosPorPalabras(List<String> permisos) {
    String sPermisosLista = "[";
    for (int i = 0; i < permisos.size(); i++) {
        sPermisosLista = sPermisosLista.concat("" + permisos.get(i) + ",");
    }/* w w  w . j  a  v a 2 s  . c o  m*/
    sPermisosLista = sPermisosLista.concat("]");
    sPermisosLista = sPermisosLista.replace(",]", "]");
    Pair<String, String> elemento = new Pair<String, String>("permisos", sPermisosLista);
    ArrayList<Pair<String, String>> elementos = new ArrayList<Pair<String, String>>();
    elementos.add(elemento);
    return oauth.peticionPost(elementos, url_modificar_permisos_por_palabras);
}

From source file:org.sufficientlysecure.keychain.ui.BackupRestoreFragment.java

private void exportToFile(boolean includeSecretKeys) {
    FragmentActivity activity = getActivity();
    if (activity == null) {
        return;// w  ww  .ja  v a2 s  .  c  o m
    }

    if (!includeSecretKeys) {
        startBackup(false);
        return;
    }

    new AsyncTask<ContentResolver, Void, ArrayList<Pair<Long, Long>>>() {
        @Override
        protected ArrayList<Pair<Long, Long>> doInBackground(ContentResolver... resolver) {
            ArrayList<Pair<Long, Long>> askPassphraseIds = new ArrayList<>();
            Cursor cursor = resolver[0].query(KeyRings.buildUnifiedKeyRingsUri(),
                    new String[] { KeyRings.MASTER_KEY_ID, KeyRings.HAS_SECRET, },
                    KeyRings.HAS_SECRET + " != 0", null, null);
            try {
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        SecretKeyType secretKeyType = SecretKeyType.fromNum(cursor.getInt(1));
                        switch (secretKeyType) {
                        // all of these make no sense to ask
                        case PASSPHRASE_EMPTY:
                        case DIVERT_TO_CARD:
                        case UNAVAILABLE:
                            continue;
                        case GNU_DUMMY: {
                            Long masterKeyId = cursor.getLong(0);
                            Long subKeyId = getFirstSubKeyWithPassphrase(masterKeyId, resolver[0]);
                            if (subKeyId != null) {
                                askPassphraseIds.add(new Pair<>(masterKeyId, subKeyId));
                            }
                            continue;
                        }
                        default: {
                            long masterKeyId = cursor.getLong(0);
                            askPassphraseIds.add(new Pair<>(masterKeyId, masterKeyId));
                        }
                        }
                    }
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
            return askPassphraseIds;
        }

        private Long getFirstSubKeyWithPassphrase(long masterKeyId, ContentResolver resolver) {
            Cursor cursor = resolver.query(KeychainContract.Keys.buildKeysUri(masterKeyId),
                    new String[] { Keys.KEY_ID, Keys.HAS_SECRET, }, Keys.HAS_SECRET + " != 0", null, null);
            try {
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        SecretKeyType secretKeyType = SecretKeyType.fromNum(cursor.getInt(1));
                        switch (secretKeyType) {
                        case PASSPHRASE_EMPTY:
                        case DIVERT_TO_CARD:
                        case UNAVAILABLE:
                            return null;
                        case GNU_DUMMY:
                            continue;
                        default: {
                            return cursor.getLong(0);
                        }
                        }
                    }
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(ArrayList<Pair<Long, Long>> askPassphraseIds) {
            super.onPostExecute(askPassphraseIds);
            FragmentActivity activity = getActivity();
            if (activity == null) {
                return;
            }

            mIdsForRepeatAskPassphrase = askPassphraseIds.iterator();

            if (mIdsForRepeatAskPassphrase.hasNext()) {
                startPassphraseActivity();
                return;
            }

            startBackup(true);
        }

    }.execute(activity.getContentResolver());
}

From source file:com.fbartnitzek.tasteemall.location.ShowProducerMapFragment.java

@Nullable
@Override//from ww w .j  ava2s . c om
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    Bundle args = getArguments();
    if (args == null) {
        Log.w(LOG_TAG, "onCreateView without args...");
    } else {
        Log.v(LOG_TAG, "onCreateView with args: " + args);

        if (args.containsKey(REVIEW_URI)) {
            mBaseUri = args.getParcelable(REVIEW_URI);
            getLoaderManager().restartLoader(PRODUCERS_LOADER_ID, null, this);
        }
    }

    mProducerLocationAdapter = new ProducerLocationAdapter(
            new ProducerLocationAdapter.ProducerLocationAdapterClickHandler() {
                @Override
                public void onClick(String producerId, ProducerLocationAdapter.ViewHolder viewHolder,
                        LatLng latLng, String formatted, String name) {
                    addProducerLocationMarker(producerId, viewHolder, latLng, formatted, name);
                }
            });

    mHeadingProducerLocations = (TextView) mRootView.findViewById(R.id.heading_map_producers);
    mHeadingProducerLocations.setText(R.string.label_list_map_producer_locations_preview);
    RecyclerView locationRecyclerView = (RecyclerView) mRootView.findViewById(R.id.recyclerview_map_producer);
    locationRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    locationRecyclerView.setAdapter(mProducerLocationAdapter);

    mHeadingReviewsOfProducer = (TextView) mRootView.findViewById(R.id.heading_map_sub_list_reviews);
    mHeadingReviewsOfProducer.setText(R.string.label_list_map_reviews_of_producer_preview);
    mReviewOfProducerAdapter = new ReviewOfLocationAdapter(
            new ReviewOfLocationAdapter.ReviewAdapterClickHandler() {
                @Override
                public void onClick(Uri contentUri, ReviewOfLocationAdapter.ViewHolder vh) {
                    Bundle bundle = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                        bundle = ActivityOptions.makeSceneTransitionAnimation(getActivity(),
                                new Pair<View, String>(vh.drinkNameView, vh.drinkNameView.getTransitionName()),
                                new Pair<View, String>(vh.producerNameView,
                                        vh.producerNameView.getTransitionName()))
                                .toBundle();
                    }

                    startActivity(new Intent(getActivity(), ShowReviewActivity.class).setData(contentUri),
                            bundle);
                }
            }, getActivity());
    RecyclerView reviewsRecyclerView = (RecyclerView) mRootView
            .findViewById(R.id.recyclerview_map_sub_list_reviews);
    reviewsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    reviewsRecyclerView.setAdapter(mReviewOfProducerAdapter);

    return mRootView;
}