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:org.droidparts.http.RESTClient.java

public Pair<Integer, BufferedInputStream> getInputStream(String uri) throws HTTPException {
    L.d("InputStream on " + uri);
    int contentLength = -1;
    ConsumingInputStream cis = null;/* w  w  w. jav  a  2s.c  om*/
    if (useHttpURLConnection()) {
        HttpURLConnectionWrapper wrapper = getModern();
        HttpURLConnection conn = wrapper.getConnectedHttpURLConnection(uri, GET);
        contentLength = conn.getContentLength();
        cis = new ConsumingInputStream(HttpURLConnectionWrapper.getUnpackedInputStream(conn), conn);
    } else {
        DefaultHttpClientWrapper wrapper = getLegacy();
        HttpGet req = new HttpGet(uri);
        HttpResponse resp = wrapper.getResponse(req);
        HttpEntity entity = resp.getEntity();
        // 2G limit
        contentLength = (int) entity.getContentLength();
        cis = new ConsumingInputStream(DefaultHttpClientWrapper.getUnpackedInputStream(entity), entity);
    }
    return new Pair<Integer, BufferedInputStream>(contentLength, cis);
}

From source file:com.appsimobile.appsii.module.weather.loader.YahooWeatherApiClient.java

@VisibleForTesting
static LocationInfo parseLocationInfo(LocationInfo li, InputStream in)
        throws XmlPullParserException, IOException, CantGetWeatherException {

    CircularArray<Pair<String, String>> alternateWoeids = new CircularArray<>();
    String primaryWoeid = null;//  w  ww  .j  ava  2  s.c om

    XmlPullParser xpp = sXmlPullParserFactory.newPullParser();
    xpp.setInput(new InputStreamReader(in));

    boolean inWoe = false;
    boolean inTown = false;
    boolean inCountry = false;
    boolean inTimezone = false;
    int eventType = xpp.getEventType();

    while (eventType != XmlPullParser.END_DOCUMENT) {
        String tagName = xpp.getName();

        if (eventType == XmlPullParser.START_TAG && "woeid".equals(tagName)) {
            inWoe = true;
        } else if (eventType == XmlPullParser.TEXT && inWoe) {
            primaryWoeid = xpp.getText();
        } else if (eventType == XmlPullParser.START_TAG && tagName.startsWith("timezone")) {
            inTimezone = true;
        } else if (eventType == XmlPullParser.TEXT && inTimezone) {
            li.timezone = xpp.getText();
        } else if (eventType == XmlPullParser.START_TAG && (tagName.startsWith("locality")
                || tagName.startsWith("admin") || tagName.startsWith("country"))) {
            for (int i = xpp.getAttributeCount() - 1; i >= 0; i--) {
                String attrName = xpp.getAttributeName(i);
                if ("type".equals(attrName) && "Town".equals(xpp.getAttributeValue(i))) {
                    inTown = true;
                } else if ("type".equals(attrName) && "Country".equals(xpp.getAttributeValue(i))) {
                    inCountry = true;
                } else if ("woeid".equals(attrName)) {
                    String woeid = xpp.getAttributeValue(i);
                    if (!TextUtils.isEmpty(woeid)) {
                        alternateWoeids.addLast(new Pair<>(tagName, woeid));
                    }
                }
            }
        } else if (eventType == XmlPullParser.TEXT && inTown) {
            li.town = xpp.getText();
        } else if (eventType == XmlPullParser.TEXT && inCountry) {
            li.country = xpp.getText();
        }

        if (eventType == XmlPullParser.END_TAG) {
            inWoe = false;
            inTown = false;
            inCountry = false;
            inTimezone = false;
        }

        eventType = xpp.next();
    }

    // Add the primary woeid if it was found.
    if (!TextUtils.isEmpty(primaryWoeid)) {
        li.woeids.addLast(primaryWoeid);
    }

    // Sort by descending tag name to order by decreasing precision
    // (locality3, locality2, locality1, admin3, admin2, admin1, etc.)
    ArrayUtils.sort(alternateWoeids, new Comparator<Pair<String, String>>() {
        @Override
        public int compare(Pair<String, String> pair1, Pair<String, String> pair2) {
            return pair1.first.compareTo(pair2.first);
        }
    });

    int N = alternateWoeids.size();
    for (int i = 0; i < N; i++) {
        Pair<String, String> pair = alternateWoeids.get(i);
        li.woeids.addLast(pair.second);
    }

    if (li.woeids.size() > 0) {
        return li;
    }

    throw new CantGetWeatherException(true, R.string.no_weather_data, "No WOEIDs found nearby.");
}

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

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

        @Override//from  w  w  w  .  ja  v a  2  s  .  co  m
        public void executeOperation(MobileServiceTable<PersonTestObjectWithStringId> typedTable,
                MobileServiceJsonTable jsonTable) throws Exception {
            PersonTestObjectWithStringId pto = new PersonTestObjectWithStringId("John", "Doe", 33);
            List<Pair<String, String>> queryParams = new ArrayList<Pair<String, String>>();
            queryParams.add(new Pair<String, String>("a", "b"));
            typedTable.insert(pto, queryParams).get();
        }
    }, false, "QS,TT");
}

From source file:dynamite.zafroshops.app.fragment.AllZopsFragment.java

private void setZops(boolean force) {
    Activity activity = getActivity();/*  w w w  . j ava2 s .c o m*/
    adapter = new AllZopsGridViewAdapter(activity, R.id.gridItem, types);

    final SharedPreferences preferences = activity.getPreferences(0);
    final SharedPreferences.Editor editor = preferences.edit();

    if (!preferences.contains(StorageKeys.ZOPCATEGORY_KEY)) {
        InputStream is = getResources().openRawResource(R.raw.zops);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        HashMap<String, MobileZop> temp = new HashMap<>();

        types = new ArrayList<>(
                (ArrayList<MobileZop>) new Gson().fromJson(reader, new TypeToken<ArrayList<MobileZop>>() {
                }.getType()));
        for (MobileZop type : types) {
            String key = type.Type.toString();

            if (!temp.containsKey(key)) {
                temp.put(key, type);
            }
        }
        types = new ArrayList<>(temp.values());
        if (adapter != null) {
            adapter.setObjects(types);
            adapter.notifyDataSetChanged();
        }

        try {
            FileOutputStream fos = activity.openFileOutput(StorageKeys.ZOPCATEGORY_KEY, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);

            oos.writeObject(types);
            oos.close();
            fos.close();
            editor.putString(StorageKeys.ZOPCATEGORY_KEY, Integer.toString(types.size()));
            editor.commit();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        if (preferences.contains(StorageKeys.ZOPCATEGORY_KEY)) {
            try {
                FileInputStream fis = activity.openFileInput(StorageKeys.ZOPCATEGORY_KEY);
                ObjectInputStream ois = new ObjectInputStream(fis);

                types = (ArrayList) ois.readObject();
                ois.close();
                fis.close();

                if (adapter != null) {
                    adapter.setObjects(types);
                    adapter.notifyDataSetChanged();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        ListenableFuture<JsonElement> result = MainActivity.MobileClient.invokeApi("mobileZop", "GET",
                new ArrayList<Pair<String, String>>() {
                    {
                        add(new Pair<String, String>("count", "true"));
                    }
                });

        Futures.addCallback(result, new FutureCallback<JsonElement>() {

            @Override
            public void onSuccess(JsonElement result) {
                Activity activity = getActivity();
                JsonArray typesAsJson = result.getAsJsonArray();
                if (typesAsJson != null) {
                    types = new Gson().fromJson(result, new TypeToken<ArrayList<MobileZop>>() {
                    }.getType());
                    try {
                        FileOutputStream fos = activity.openFileOutput(StorageKeys.ZOPCATEGORY_KEY,
                                Context.MODE_PRIVATE);
                        ObjectOutputStream oos = new ObjectOutputStream(fos);

                        oos.writeObject(types);
                        oos.close();
                        fos.close();
                        editor.putString(StorageKeys.ZOPCATEGORY_KEY, Integer.toString(types.size()));
                        editor.commit();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (adapter != null) {
                    adapter.setObjects(types);
                    GridView zops = (GridView) activity.findViewById(R.id.gridViewZops);
                    RelativeLayout loader = (RelativeLayout) activity.findViewById(R.id.relativeLayoutLoader);
                    loader.setVisibility(View.INVISIBLE);
                    zops.setVisibility(View.VISIBLE);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(@NonNull Throwable t) {
                Activity activity = getActivity();
                if (activity != null && types.size() == 0) {
                    GridView zops = (GridView) activity.findViewById(R.id.gridViewZops);
                    RelativeLayout loader = (RelativeLayout) activity.findViewById(R.id.relativeLayoutLoader);
                    zops.setVisibility(View.INVISIBLE);
                    loader.setVisibility(View.VISIBLE);
                }
            }
        });
    }
}

From source file:org.anhonesteffort.flock.ContactCopyService.java

private void handleQueueAccountForCopy(Intent intent) {
    Log.d(TAG, "handleQueueAccountForCopy()");

    Account fromAccount = intent.getParcelableExtra(KEY_FROM_ACCOUNT);
    Account toAccount = intent.getParcelableExtra(KEY_TO_ACCOUNT);
    Integer contactCount = intent.getIntExtra(KEY_CONTACT_COUNT, -1);

    if (fromAccount == null || toAccount == null || contactCount < 0) {
        Log.e(TAG, "failed to parse to account, from account, or contact count from intent extras.");
        return;//from  w  ww  . j a  va 2  s .  co m
    }

    accountsForCopy.add(new Pair<Account, Account>(fromAccount, toAccount));
    countContactsToCopy += contactCount;

    Log.d(TAG, "contacts to copy: " + countContactsToCopy);
}

From source file:com.dabay6.android.apps.carlog.adapters.FuelHistoryCursorAdapter.java

/**
 * @param context The {@link Context} used to retrieve string resources.
 * @param history The current {@link FuelHistoryDTO} record.
 * @param cursor  All history records./*  ww w  .j  a v  a 2  s  .  c om*/
 */
private Pair<Float, String> calculateMilesPerGallon(final Context context, final FuelHistoryDTO history,
        final Cursor cursor) {
    final Pair<Long, String> returnValue;
    final int count = cursor.getCount() - 1;
    final int currentPosition = cursor.getPosition();
    final int next = cursor.getPosition() + 1;
    final float mileage;
    final float mpg;

    if (next <= count) {
        final FuelHistoryDTO previous;

        cursor.moveToPosition(next);

        previous = FuelHistoryDTO.newInstance(cursor);
        mileage = history.getOdometerReading() - previous.getOdometerReading();

        mpg = mileage / history.getFuelAmount();

        cursor.moveToPosition(currentPosition);
    } else {
        mpg = history.getOdometerReading() / history.getFuelAmount();
    }

    return new Pair<Float, String>(mpg, String.format(context.getString(R.string.miles_per_gallon), mpg));
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.PictureObj.java

public Pair<JSONObject, byte[]> handleUnprocessed(Context context, JSONObject msg) {
    if (!msg.has(DATA)) {
        return null;
    }/*from   www.  j ava  2  s .  c  o  m*/

    byte[] bytes = FastBase64.decode(msg.optString(DATA));
    msg.remove(DATA);
    return new Pair<JSONObject, byte[]>(msg, bytes);
}

From source file:net.simno.klingar.data.repository.MusicRepositoryImpl.java

@Override
public Single<Pair<List<Track>, Long>> createPlayQueue(Track track) {
    return media.playQueue(track.uri(), track.key(), track.parentKey(), track.libraryId())
            .flatMap(container -> Observable.just(container).flatMap(TRACKS)
                    .map(trackMapper(track.libraryId(), track.uri())).map(plexItem -> (Track) plexItem).toList()
                    .map(tracks -> new Pair<>(tracks, container.playQueueSelectedItemID)));
}

From source file:jp.realglobe.sugo.actor.android.hitoe.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ?? actor ID ??
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    final String actorSuffix = preferences.getString(getString(R.string.key_actor_suffix), null);
    if (actorSuffix == null) {
        preferences.edit().putString(getString(R.string.key_actor_suffix),
                String.valueOf(Math.abs((new Random(System.nanoTime())).nextInt()))).apply();
    }/*from ww w . j  a  v  a 2s  .  c  o  m*/

    this.vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    this.ringtone = RingtoneManager.getRingtone(this,
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
    this.googleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this,
                            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                            && ActivityCompat.checkSelfPermission(MainActivity.this,
                                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    LocationServices.FusedLocationApi.requestLocationUpdates(MainActivity.this.googleApiClient,
                            LocationRequest.create().setInterval(LOCATION_INTERVAL)
                                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY),
                            location -> {
                                MainActivity.this.location = location;
                                Log.d(LOG_TAG, "Location changed to " + location);
                            });
                    Log.d(LOG_TAG, "Location monitor started");
                }

                @Override
                public void onConnectionSuspended(int i) {
                    Log.d(LOG_TAG, "Location monitor suspended");
                }
            }).addOnConnectionFailedListener(connectionResult -> {
                final String warning = "Location detection error: " + connectionResult;
                MainActivity.this.warningView.post(() -> setWarning(warning));
                Log.w(LOG_TAG, warning);
            }).build();
    hitoe = new HitoeWrapper(HitoeSdkAPIImpl.getInstance(this.getApplicationContext()));
    hitoe.setHeartrateReceiver(() -> {
        synchronized (this) {
            // ?? hitoe ???????
            if (!this.hitoeReady) {
                this.hitoeReady = true;
                handler.post(() -> {
                    synchronized (this) {
                        if (this.hitoeReady) {
                            this.disableHitoeSetting();
                        }
                    }
                });
            }
        }
    }, (date, heartrate) -> {
        this.heartrate = new Pair<>(date, heartrate);
        this.heartrateView.post(() -> this.heartrateView.setText(String.format(Locale.US, "%d", heartrate)));
    });
    hitoe.setDisconnectCallback(() -> {
        synchronized (this) {
            // ?? hitoe ???????
            this.hitoeReady = false;
            handler.post(() -> {
                synchronized (this) {
                    if (!this.hitoeReady) {
                        this.enableHitoeSetting();
                    }
                }
            });
        }
    });
    this.handler = new Handler();
    this.timer = new Handler();
    this.heartrate = new Pair<>(0L, 0);

    // ??
    reset();

    // ???????????
    checkPermission();
}

From source file:net.illusor.swipeplayer.activities.SwipePagerAdapter.java

/**
 * Gets information about currently browsed folders
 * @return Pair of files: (root of the browsed hierarchy, last element of the browsed hierarchy) or null, if the adapter is empty
 *//*  ww  w  .  j  a  v  a2  s.  com*/
public Pair<File, File> getFolderStructure() {
    if (this.browserFolders.size() == 0)
        return null;

    File first = this.browserFolders.get(0);
    File second = this.browserFolders.get(this.browserFolders.size() - 1);
    return new Pair<>(first, second);
}