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.example.scrumptious.SelectionFragment.java

private Pair<File, Integer> getImageFileAndMinDimension() {
    File photoFile = null;/*from w ww.j a va2 s  .  c o m*/
    String photoUriString = photoUri.toString();
    if (photoUriString.startsWith("file://")) {
        photoFile = new File(photoUri.getPath());
    } else if (photoUriString.startsWith("content://")) {
        FileOutputStream photoOutputStream = null;
        InputStream contentInputStream = null;
        try {
            Uri photoUri = Uri.parse(photoUriString);
            photoFile = new File(getTempPhotoStagingDirectory(),
                    URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8"));

            photoOutputStream = new FileOutputStream(photoFile);
            contentInputStream = getActivity().getContentResolver().openInputStream(photoUri);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = contentInputStream.read(buffer)) > 0) {
                photoOutputStream.write(buffer, 0, len);
            }
        } catch (FileNotFoundException fnfe) {
            Log.e(TAG, "photo not found", fnfe);
        } catch (UnsupportedEncodingException uee) {
            Log.e(TAG, "bad photo name", uee);
        } catch (IOException ioe) {
            Log.e(TAG, "can't copy photo", ioe);
        } finally {
            try {
                if (photoOutputStream != null) {
                    photoOutputStream.close();
                }
                if (contentInputStream != null) {
                    contentInputStream.close();
                }
            } catch (IOException ioe) {
                Log.e(TAG, "can't close streams");
            }
        }
    }

    if (photoFile != null) {
        InputStream is = null;
        try {
            is = new FileInputStream(photoFile);

            // We only want to get the bounds of the image, rather than load the whole thing.
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, options);

            return new Pair<>(photoFile, Math.min(options.outWidth, options.outHeight));
        } catch (Exception e) {
            return null;
        } finally {
            Utility.closeQuietly(is);
        }
    }
    return null;
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java

public void testJsonTableLookupWithParametersFeatureHeader() {
    testTableFeatureHeader(new TableTestOperation() {

        @Override/* w w  w.  j  a  va  2 s .  co  m*/
        public void executeOperation(MobileServiceTable<PersonTestObjectWithStringId> typedTable,
                MobileServiceJsonTable jsonTable) throws Exception {
            List<Pair<String, String>> queryParams = new ArrayList<Pair<String, String>>();
            queryParams.add(new Pair<String, String>("a", "b"));
            jsonTable.lookUp("1", queryParams).get();
        }
    }, false, "QS,TU");
}

From source file:com.ichi2.libanki.Models.java

/** "Mapping of field name -> (ord, field). */
public Map<String, Pair<Integer, JSONObject>> fieldMap(JSONObject m) {
    JSONArray ja;/*from   ww  w  . j ava 2  s . co  m*/
    try {
        ja = m.getJSONArray("flds");
        // TreeMap<Integer, String> map = new TreeMap<Integer, String>();
        Map<String, Pair<Integer, JSONObject>> result = new HashMap<String, Pair<Integer, JSONObject>>();
        for (int i = 0; i < ja.length(); i++) {
            JSONObject f = ja.getJSONObject(i);
            result.put(f.getString("name"), new Pair<Integer, JSONObject>(f.getInt("ord"), f));
        }
        return result;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.inmite.apps.smsjizdenka.adapter.TicketsAdapter.java

/**
 * Tries to delete ticket either from swipe-to-dismiss or button.
 *
 * @return Pair of ticket id and previous status or null if it wasn't deleted.
 *//*  w w w  . jav a  2  s. co  m*/
public Pair<Long, Integer> archiveTicket(int position) {
    Cursor cursor = getCursor();
    if (cursor.isClosed()) {
        return null;
    }
    cursor.moveToPosition(position);
    long id;
    try {
        id = cursor.getLong(iId);
    } catch (CursorIndexOutOfBoundsException e) {
        return null;
    }
    final Time validTo = FormatUtil.timeFrom3339(cursor.getString(iValidTo));
    int status = getValidityStatus(cursor.getInt(iStatus), validTo);
    if (status == Tickets.STATUS_EXPIRED) {
        ContentValues values = new ContentValues();
        values.put(TicketProvider.Tickets.STATUS, TicketProvider.Tickets.STATUS_DELETED);
        c.getContentResolver().update(ContentUris.withAppendedId(TicketProvider.Tickets.CONTENT_URI, id),
                values, null, null);
        // I had to call this deprecated method, because it needs to run synchronously. In asynchronous case, previous tickets blinks during swipe to dismiss.
        //noinspection deprecation
        getCursor().requery();
        return new Pair<Long, Integer>(id, status);
    } else {
        return null;
    }
}

From source file:nl.eduvpn.app.fragment.HomeFragment.java

/**
 * Starts downloading the list of profiles for a single VPN provider.
 *
 * @param adapter       The adapter to download the data into.
 * @param instance      The VPN provider instance.
 * @param discoveredAPI The discovered API containing the URLs.
 * @param authState     The access and refresh token for the API.
 *///from   w w w  .  j a  v  a2  s  . c o m
private void _fetchProfileList(@NonNull final ProfileAdapter adapter, @NonNull final Instance instance,
        @NonNull DiscoveredAPI discoveredAPI, @NonNull AuthState authState) {
    _apiService.getJSON(discoveredAPI.getProfileListEndpoint(), authState,
            new APIService.Callback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject result) {
                    try {
                        List<Profile> profiles = _serializerService.deserializeProfileList(result);
                        List<Pair<Instance, Profile>> newItems = new ArrayList<>();
                        for (Profile profile : profiles) {
                            newItems.add(new Pair<>(instance, profile));
                        }
                        adapter.addItemsIfNotAdded(newItems);
                    } catch (SerializerService.UnknownFormatException ex) {
                        _problematicInstances.add(instance);
                        Log.e(TAG, "Error parsing profile list.", ex);
                    }
                    _checkLoadingFinished(adapter);
                }

                @Override
                public void onError(String errorMessage) {
                    _problematicInstances.add(instance);
                    Log.e(TAG, "Error fetching profile list: " + errorMessage);
                    _checkLoadingFinished(adapter);
                }
            });
}

From source file:com.tmall.wireless.tangram3.dataparser.concrete.PojoGroupBasicAdapter.java

@Override
public void insertComponents(int pos, List<BaseCell> components) {
    if (mData != null && mData.size() > 0 && components != null && !components.isEmpty() && pos >= 0) {
        int newItemSize = components.size();
        if (mCards != null) {
            List<Pair<Range<Integer>, Card>> newCards = new ArrayList<>();
            for (int i = 0, size = mCards.size(); i < size; i++) {
                Pair<Range<Integer>, Card> pair = mCards.get(i);
                int start = pair.first.getLower();
                int end = pair.first.getUpper();
                if (end < pos) {
                    //do nothing
                    newCards.add(pair);//w  ww  .  j av a2 s .  co m
                } else if (start <= pos && pos < end) {
                    Pair<Range<Integer>, Card> newPair = new Pair<>(Range.create(start, end + newItemSize),
                            pair.second);
                    newCards.add(newPair);
                } else if (pos <= start) {
                    Pair<Range<Integer>, Card> newPair = new Pair<>(
                            Range.create(start + newItemSize, end + newItemSize), pair.second);
                    newCards.add(newPair);
                }
            }
            mCards.clear();
            mCards.addAll(newCards);
        }
        for (int i = 0, size = components.size(); i < size; i++) {
            BaseCell cell = components.get(i);
            if (cell != null) {
                cell.added();
            }
        }
        for (int i = 0; i < newItemSize; i++) {
            if ((pos + i) < mData.size()) {
                mData.add(pos + i, components.get(i));
            } else {
                mData.add(components.get(i));
            }
        }
        notifyItemRangeInserted(pos, newItemSize);
    }
}

From source file:ru.gkpromtech.exhibition.db.Table.java

public List<Pair<Entity[], T>> selectJoined(Join[] joins, String selection, String[] selectionArgs,
        String orderBy, String groupBy)
        throws InvalidClassException, IllegalAccessException, InstantiationException {

    List<Pair<Entity[], T>> result = new ArrayList<>();
    Table<? extends Entity>[] tables = new Table<?>[joins.length];

    StringBuilder query = new StringBuilder();
    for (int i = 0; i < joins.length; ++i) {
        tables[i] = ((DbHelper) mSqlHelper).getTableFor(joins[i].entity);
        for (String column : tables[i].mColumns) {
            query.append(",f").append(i).append(".").append(column);
        }// w  w w  .j a  v  a  2  s . c om
    }
    for (String column : mColumns)
        query.append(",t.").append(column);
    query.replace(0, 1, "SELECT "); // first comma -> select

    query.append("\nFROM ").append(mTableName).append(" t");
    for (int i = 0; i < joins.length; ++i) {
        Join join = joins[i];
        query.append("\n");
        if (join.type != null)
            query.append(join.type).append(" ");
        query.append("JOIN ").append(tables[i].mTableName).append(" f").append(i).append(" ON ");
        if (join.customJoinOn != null) {
            query.append(join.customJoinOn);
        } else {
            query.append("f").append(i).append(".").append(join.entityRow).append(" = t.").append(join.row);
        }
    }

    if (selection != null)
        query.append("\nWHERE ").append(selection);
    if (groupBy != null)
        query.append("\nGROUP BY ").append(groupBy);
    if (orderBy != null)
        query.append("\nORDER BY ").append(orderBy);

    String queryString = query.toString();
    if (BuildConfig.DEBUG)
        Log.d("PP", queryString);

    SQLiteDatabase db = mSqlHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(queryString, selectionArgs);

    //noinspection TryFinallyCanBeTryWithResources
    try {
        while (cursor.moveToNext()) {
            int col = 0;
            Entity[] entities = new Entity[joins.length];
            for (int i = 0; i < joins.length; ++i) {
                Table<? extends Entity> table = tables[i];
                entities[i] = joins[i].entity.newInstance();
                for (int j = 0; j < table.mFields.length; ++j, ++col)
                    fillFieldValue(table.mType[j], table.mFields[j], entities[i], cursor, col);
            }

            T entity = mEntityClass.newInstance();
            for (int j = 0; j < mFields.length; ++j, ++col)
                fillFieldValue(mType[j], mFields[j], entity, cursor, col);
            result.add(new Pair<>(entities, entity));
        }
    } finally {
        cursor.close();
        db.close();
    }

    return result;
}

From source file:com.freeme.filemanager.view.FileViewFragment.java

private View createStorageVolumeItem(final String volumPath, String volumDescription) {

    View listItem = LayoutInflater.from(mActivity).inflate(R.layout.dropdown_item, null);
    View listContent = listItem.findViewById(R.id.list_item);
    ImageView img = (ImageView) listItem.findViewById(R.id.item_icon);
    TextView text = (TextView) listItem.findViewById(R.id.path_name);
    text.setText(volumDescription);/*from   w  ww.  j  a v  a2s . c  o  m*/

    //*/ freeme.liuhaoran , 20160728 , volumeItem image
    /*/
    img.setImageResource(getStorageVolumeIconByDescription(volumDescription));
    //*/
    Log.i("liuhaoran3", "storageVolume.getPath() = " + storageVolume.getPath());
    Log.i("liuhaoran3", "internalPath = " + internalPath);
    if (storageVolume.getPath().equals(internalPath)) {
        img.setImageDrawable((getResources().getDrawable(R.drawable.storage_internal_n)));
    } else if ((storageVolume.getDescription(mActivity).toString()).contains("SD")) {
        img.setImageDrawable((getResources().getDrawable(R.drawable.storage_sd_card_n)));
    } else if (storageVolume.getDescription(mActivity).toString().contains("usbotg")) {
        img.setImageDrawable((getResources().getDrawable(R.drawable.storage_usb_n)));
    }
    //*/

    //modigy by droi heqianqian if the stroage device is not phone memeory, then set the storage could be unmoumt
    ImageView unmount_btn = (ImageView) listItem.findViewById(R.id.unmount_btn);
    if (volumPath.equals(Util.SD_DIR)) {
        //*/ freeme.liuhaoran , 20160802 , judge whether there is a SD card operation permissions
        if (ContextCompat.checkSelfPermission(mActivity,
                "android.permission.MOUNT_UNMOUNT_FILESYSTEMS") == PackageManager.PERMISSION_GRANTED) {
            unmount_btn.setVisibility(View.VISIBLE);
            unmount_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    MountHelper.getInstance(mActivity).unMount(volumPath);
                    showVolumesList(false);
                    mVolumeSwitch.setVisibility(View.GONE);
                    int mounedCount = StorageHelper.getInstance(mActivity).getMountedVolumeCount();
                }
            });
        } else {
            unmount_btn.setVisibility(View.INVISIBLE);
        }
        //*/
    }
    listItem.setOnClickListener(mStorageVolumeClick);
    listItem.setTag(new Pair(volumPath, volumDescription));
    return listItem;
}

From source file:org.gaeproxy.GAEProxyService.java

/** Called when the activity is first created. */
public boolean handleConnection() {

    if (proxyType.equals("GAE")) {
        appHost = parseHost("g.maxcdn.info", true);
        if (appHost == null || appHost.equals("") || isInBlackList(appHost)) {
            appHost = settings.getString("appHost", DEFAULT_HOST);
        }/*  w  w  w .  j  a v  a  2s  .c  om*/
    } else if (proxyType.equals("PaaS")) {
        appHost = parseHost(appId, false);
        if (appHost == null || appHost.equals("") || isInBlackList(appHost)) {
            return false;
        }
    }

    videoHost = parseHost("v.maxcdn.info", true);
    if (videoHost == null || videoHost.equals("") || isInBlackList(videoHost)) {
        videoHost = settings.getString("videoHost", VIDEO_HOST);
    }

    handler.sendEmptyMessage(MSG_HOST_CHANGE);

    dnsHost = parseHost("myhosts.sinaapp.com", false);
    if (dnsHost == null || dnsHost.equals("") || isInBlackList(appHost)) {
        dnsHost = DEFAULT_DNS;
    }

    try {
        String[] hosts = dnsHost.split("\\|");
        dnsHost = hosts[hosts.length - 1];
        appMask = appHost.split("\\|");
        videoMask = videoHost.split("\\|");
    } catch (Exception ex) {
        return false;
    }

    if (!isGlobalProxy) {
        if (mProxiedApps == null) {
            mProxiedApps = App.getProxiedApps(this);
        }
    }

    // DNS Proxy Setup
    // with AsyncHttpClient
    if ("PaaS".equals(proxyType)) {
        Pair<String, String> orgHost = new Pair<String, String>(appId, appMask[0]);
        dnsServer = new DNSServer(this, dnsHost, orgHost);
    } else if ("GAE".equals(proxyType)) {
        dnsServer = new DNSServer(this, dnsHost, null);
    }
    dnsPort = dnsServer.getServPort();

    // Random mirror for load balance
    // only affect when appid equals proxyofmax
    if (appId.equals("proxyofmax")) {
        appId = new String(Base64.decodeBase64(getString(R.string.mirror_list).getBytes()));
        appPath = getString(R.string.mirror_path);
        sitekey = getString(R.string.mirror_sitekey);
    }

    if (!preConnection())
        return false;

    Thread dnsThread = new Thread(dnsServer);
    dnsThread.setDaemon(true);
    dnsThread.start();

    connect();
    flushDNS();

    return true;
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.SystemPropertiesTests.java

private void insertUserParameterWithSystemProperties(
        final EnumSet<MobileServiceSystemProperty> systemProperties) throws Throwable {

    final String tableName = "MyTableName";

    final String responseContent = "{\"id\":\"an id\",\"String\":\"Hey\"}";
    final JsonObject obj = new JsonParser().parse("{\"id\":\"an id\",\"String\":\"what\"}").getAsJsonObject();

    MobileServiceClient client = null;//  w  ww . j  a  v a  2s . c  o m

    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Add a filter to handle the request and create a new json
    // object with an id defined
    client = client.withFilter(getTestFilter(responseContent));

    client = client.withFilter(new ServiceFilter() {
        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            assertTrue(request.getUrl().contains("__systemproperties=__createdAt"));

            return nextServiceFilterCallback.onNext(request);
        }
    });

    // Create get the MobileService table
    MobileServiceJsonTable msTable = client.getTable(tableName);

    msTable.setSystemProperties(systemProperties);

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

    try {
        // Call the insert method
        JsonObject jsonObject = msTable.insert(obj, parameters).get();

        // Asserts
        if (jsonObject == null) {
            fail("Expected result");
        }

    } catch (Exception exception) {
        fail(exception.getMessage());
    }
}