Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

In this page you can find the example usage for android.database Cursor moveToPosition.

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:com.massivcode.androidmusicplayer.activities.MainActivity.java

@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
    switch (parent.getId()) {

    //  ?   ?  ? ?? ?   ?  ?  ??.
    // ? ?  ?   ??? 
    case R.id.artist_ExlistView: {
        Cursor parentData = (Cursor) parent.getExpandableListAdapter().getGroup(groupPosition);
        String artist = parentData.getString(parentData.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
        ArrayList<Long> list = MusicInfoLoadUtil.getArtistTrackInfoList(MainActivity.this, artist);
        Intent intent = new Intent(MainActivity.this, MusicService.class);
        intent.setAction(MusicService.ACTION_PLAY);
        intent.putExtra("list", list);
        intent.putExtra("position", childPosition);
        startService(intent);/*from   w  w w .ja  v a 2  s .co m*/
        break;
    }
    case R.id.playlist_listView: {
        Cursor parentData = (Cursor) parent.getExpandableListAdapter().getGroup(groupPosition);
        parentData.moveToPosition(groupPosition);
        String playlistName = parentData.getString(
                parentData.getColumnIndexOrThrow(MyPlaylistContract.MyPlaylistEntry.COLUMN_NAME_PLAYLIST));
        ArrayList<Long> list = MusicInfoLoadUtil.getMusicIdListFromPlaylistName(playlistName,
                getApplicationContext());
        Intent intent = new Intent(MainActivity.this, MusicService.class);
        intent.setAction(MusicService.ACTION_PLAY);
        intent.putExtra("list", list);
        intent.putExtra("position", childPosition);
        startService(intent);
        break;
    }

    }
    return false;
}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.adapters.DagvergunningenAdapter.java

/**
 * Bind the cursor data to the view elements
 * @param view listitem view containing the elements
 * @param context the context/*from w  w w.j  a v a2  s .  c  om*/
 * @param cursor a cursor containing the dagvergunning data
 */
@Override
public void bindView(View view, Context context, Cursor cursor) {
    boolean multipleDagvergunningen = false;

    // get erkenningsnummer for checking multiple dagvergunningen for the same koopman
    String erkenningsnummer = cursor.getString(
            cursor.getColumnIndex(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE));

    // get current position, check for multiple dagvergunningen, and restore position again
    int position = cursor.getPosition();
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        if (cursor
                .getString(cursor.getColumnIndex(
                        MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE))
                .equals(erkenningsnummer) && cursor.getPosition() != position) {
            multipleDagvergunningen = true;
            break;
        }
        cursor.moveToNext();
    }
    cursor.moveToPosition(position);

    // get the viewholder layout containing the view items
    ViewHolder viewHolder = (ViewHolder) view.getTag();

    // koopman foto
    Glide.with(context.getApplicationContext())
            .load(cursor.getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL)))
            .error(R.drawable.no_koopman_image).into(viewHolder.koopmanFoto);

    // alert !
    String koopmanStatus = cursor.getString(cursor.getColumnIndex("koopman_status"));
    if (multipleDagvergunningen
            || koopmanStatus.equals(context.getString(R.string.koopman_status_verwijderd))) {
        viewHolder.koopmanStatusText.setVisibility(View.VISIBLE);
    } else {
        viewHolder.koopmanStatusText.setVisibility(View.GONE);
    }

    // koopman naam
    String koopmanVoorletters = cursor
            .getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS));
    String koopmanAchternaam = cursor
            .getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM));
    viewHolder.koopmanVoorlettersAchternaamText.setText(koopmanVoorletters + " " + koopmanAchternaam);

    // vervanger aanwezig
    String vervangerErkenningsnummer = cursor.getString(
            cursor.getColumnIndex(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ERKENNINGSNUMMER));
    if (vervangerErkenningsnummer != null) {
        viewHolder.vervangerAanwezigText.setVisibility(View.VISIBLE);
    } else {
        viewHolder.vervangerAanwezigText.setVisibility(View.GONE);
    }

    // registratietijd
    String registratieDatumtijd = cursor
            .getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_DATUMTIJD));
    try {
        Date registratieDate = new SimpleDateFormat(context.getString(R.string.date_format_datumtijd),
                Locale.getDefault()).parse(registratieDatumtijd);
        SimpleDateFormat sdf = new SimpleDateFormat(context.getString(R.string.date_format_tijd));
        String registratieTijd = sdf.format(registratieDate);
        viewHolder.dagvergunningRegistratieDatumtijdText.setText(registratieTijd);
    } catch (java.text.ParseException e) {
        viewHolder.dagvergunningRegistratieDatumtijdText.setText("");
    }

    // erkennings nummer
    viewHolder.erkenningsnummerText
            .setText(context.getString(R.string.label_erkenningsnummer) + ": " + erkenningsnummer);

    // sollicitatie nummer
    String sollicitatieNummer = cursor
            .getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER));
    if (sollicitatieNummer != null && !sollicitatieNummer.equals("")) {
        viewHolder.sollicitatieSollicitatieNummerText.setVisibility(View.VISIBLE);
        viewHolder.sollicitatieSollicitatieNummerText
                .setText(context.getString(R.string.label_sollicitatienummer) + ": " + sollicitatieNummer);
    } else {
        // we need to clear the textview contents because listview items are recycled and may
        // therefor contain data from other dagvergunning
        viewHolder.sollicitatieSollicitatieNummerText.setVisibility(View.GONE);
        viewHolder.sollicitatieSollicitatieNummerText.setText("");
    }

    // sollicitatie status
    String sollicitatieStatus = cursor
            .getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Dagvergunning.COL_STATUS_SOLLICITATIE));
    if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) {
        viewHolder.sollicitatieStatusText.setVisibility(View.VISIBLE);
        viewHolder.sollicitatieStatusText.setText(sollicitatieStatus);
        viewHolder.sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor(context,
                Utility.getSollicitatieStatusColor(context, sollicitatieStatus)));
    } else {
        viewHolder.sollicitatieStatusText.setVisibility(View.GONE);
        viewHolder.sollicitatieStatusText.setText("");
    }

    // notitie
    String notitie = cursor.getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Dagvergunning.COL_NOTITIE));
    if (notitie != null && !notitie.equals("")) {
        viewHolder.notitieText.setText(context.getString(R.string.label_notitie) + ": " + notitie);
        Utility.collapseView(viewHolder.notitieText, false);
    } else {
        Utility.collapseView(viewHolder.notitieText, true);
    }

    // totale lengte
    String totaleLengte = cursor
            .getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Dagvergunning.COL_TOTALE_LENGTE));
    viewHolder.dagvergunningTotaleLengteText
            .setText(totaleLengte + " " + context.getString(R.string.length_meter));

    // account naam
    String accountNaam = cursor.getString(cursor.getColumnIndex(MakkelijkeMarktProvider.Account.COL_NAAM));
    viewHolder.accountNaamText.setText(accountNaam);
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }//  ww w .  j  a  v  a 2 s.  c om

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    /*
     * First, find out what records match this query, and if they refer to two
     * or more (formId,formVersion) tuples, then be sure to remove all
     * FORM_MEDIA_PATH references. Otherwise, if they are all for the same
     * tuple, and the update specifies a FORM_MEDIA_PATH, move all the
     * non-matching directories elsewhere.
     */
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    boolean multiset = false;
    Cursor c = null;
    try {
        c = this.query(uri, null, whereId, whereIdArgs, null);
        if (c == null) {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
        }
        if (c.getCount() >= 1) {
            FormIdVersion ref = null;
            c.moveToPosition(-1);
            while (c.moveToNext()) {
                idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                        c.getColumnIndex(FormsColumns._ID));
                tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                formIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String tableId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                String formId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String formVersion = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_VERSION));
                FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion);

                int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx);
                if (mediaPath != null) {
                    mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath),
                            (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
                }

                if (ref != null && !ref.equals(cur)) {
                    multiset = true;
                    break;
                } else {
                    ref = cur;
                }
            }
        }
    } catch (Exception e) {
        log.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }

    if (multiset) {
        // don't let users manually update media path
        // we are referring to two or more (formId,formVersion) tuples.
        if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
            values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
        }
    } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        // we are not a multiset and we are setting the media path
        // try to move all the existing non-matching media paths to
        // somewhere else...
        File mediaPath = ODKFileUtils.asAppFile(appName,
                values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));
        for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
            File altPath = entry.getKey();
            if (!altPath.equals(mediaPath)) {
                try {
                    moveDirectory(appName, entry.getValue(), altPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString());
                }
            }
        }
        // OK. we have moved the existing form definitions elsewhere. We can
        // proceed with update...
    }

    // ensure that all values are correct and ignore some user-supplied
    // values...
    patchUpValues(appName, values);

    // Make sure that the necessary fields are all set
    if (values.containsKey(FormsColumns.DATE) == true) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    SQLiteDatabase db = null;
    int count;
    try {
        // OK Finally, now do the update...
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform update " + uri);
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:com.google.samples.apps.iosched.session.SessionDetailModel.java

private void readDataFromSpeakersCursor(Cursor cursor) {
    mSpeakers.clear();/*from   w  w w. j  a  v a  2s .  c  o m*/

    // Not using while(cursor.moveToNext()) because it would lead to issues when writing tests.
    // Either we would mock cursor.moveToNext() to return true and the test would have infinite
    // loop, or we would mock cursor.moveToNext() to return false, and the test would be for an
    // empty cursor.
    int count = cursor.getCount();
    for (int i = 0; i < count; i++) {
        cursor.moveToPosition(i);
        final String speakerName = cursor
                .getString(cursor.getColumnIndex(ScheduleContract.Speakers.SPEAKER_NAME));
        if (TextUtils.isEmpty(speakerName)) {
            continue;
        }

        final String speakerImageUrl = cursor
                .getString(cursor.getColumnIndex(ScheduleContract.Speakers.SPEAKER_IMAGE_URL));
        final String speakerCompany = cursor
                .getString(cursor.getColumnIndex(ScheduleContract.Speakers.SPEAKER_COMPANY));
        final String speakerUrl = cursor
                .getString(cursor.getColumnIndex(ScheduleContract.Speakers.SPEAKER_URL));
        final String speakerPlusoneUrl = cursor
                .getString(cursor.getColumnIndex(ScheduleContract.Speakers.SPEAKER_PLUSONE_URL));
        final String speakerTwitterUrl = cursor
                .getString(cursor.getColumnIndex(ScheduleContract.Speakers.SPEAKER_TWITTER_URL));
        final String speakerAbstract = cursor
                .getString(cursor.getColumnIndex(ScheduleContract.Speakers.SPEAKER_ABSTRACT));

        mSpeakers.add(new Speaker(speakerName, speakerImageUrl, speakerCompany, speakerUrl, speakerPlusoneUrl,
                speakerTwitterUrl, speakerAbstract));
    }
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}/*from  www .j a  va 2 s . c  o m*/
 */
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    Cursor del = null;
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    try {
        del = this.query(uri, null, whereId, whereIdArgs, null);
        if (del == null) {
            throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records");
        }
        del.moveToPosition(-1);
        while (del.moveToNext()) {
            idValue = ODKDatabaseUtils.get().getIndexAsType(del, Integer.class,
                    del.getColumnIndex(FormsColumns._ID));
            tableIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.TABLE_ID));
            formIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.FORM_ID));
            File mediaDir = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)));
            mediaDirs.put(mediaDir, (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
        }
    } catch (Exception e) {
        log.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (del != null && !del.isClosed()) {
            del.close();
        }
    }

    SQLiteDatabase db = null;
    int count;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.delete(DatabaseConstants.FORMS_TABLE_NAME, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform deletion " + e.toString());
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    // and attempt to move these directories to the stale forms location
    // so that they do not immediately get rescanned...

    for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
        try {
            moveDirectory(appName, entry.getValue(), entry.getKey());
        } catch (IOException e) {
            e.printStackTrace();
            log.e(t, "Unable to move directory " + e.toString());
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:com.android.mail.utils.NotificationUtils.java

/**
 * Seeks the cursor to the position of the most recent unread conversation. If no unread
 * conversation is found, the position of the cursor will be restored, and false will be
 * returned.//from w  w  w . j a v a2s .co  m
 */
private static boolean seekToLatestUnreadConversation(final Cursor cursor) {
    final int initialPosition = cursor.getPosition();
    do {
        final Conversation conversation = new Conversation(cursor);
        if (!conversation.read) {
            return true;
        }
    } while (cursor.moveToNext());

    // Didn't find an unread conversation, reset the position.
    cursor.moveToPosition(initialPosition);
    return false;
}

From source file:org.mozilla.mozstumbler.service.sync.UploadReports.java

private BatchRequestStats getRequestBody(Cursor cursor) {
    int wifiCount = 0;
    int cellCount = 0;
    JSONArray items = new JSONArray();

    int columnId = cursor.getColumnIndex(DatabaseContract.Reports._ID);
    int columnTime = cursor.getColumnIndex(DatabaseContract.Reports.TIME);
    int columnLat = cursor.getColumnIndex(DatabaseContract.Reports.LAT);
    int columnLon = cursor.getColumnIndex(DatabaseContract.Reports.LON);
    int columnAltitude = cursor.getColumnIndex(DatabaseContract.Reports.ALTITUDE);
    int columnAccuracy = cursor.getColumnIndex(DatabaseContract.Reports.ACCURACY);
    int columnRadio = cursor.getColumnIndex(DatabaseContract.Reports.RADIO);
    int columnCell = cursor.getColumnIndex(DatabaseContract.Reports.CELL);
    int columnWifi = cursor.getColumnIndex(DatabaseContract.Reports.WIFI);
    int columnCellCount = cursor.getColumnIndex(DatabaseContract.Reports.CELL_COUNT);
    int columnWifiCount = cursor.getColumnIndex(DatabaseContract.Reports.WIFI_COUNT);

    cursor.moveToPosition(-1);
    try {/*from   w w  w  . ja  va 2 s  . c  om*/
        while (cursor.moveToNext()) {
            JSONObject item = new JSONObject();
            item.put("time", DateTimeUtils.formatTime(DateTimeUtils.removeDay(cursor.getLong(columnTime))));
            item.put("lat", cursor.getDouble(columnLat));
            item.put("lon", cursor.getDouble(columnLon));
            if (!cursor.isNull(columnAltitude)) {
                item.put("altitude", cursor.getInt(columnAltitude));
            }
            if (!cursor.isNull(columnAccuracy)) {
                item.put("accuracy", cursor.getInt(columnAccuracy));
            }
            item.put("radio", cursor.getString(columnRadio));
            item.put("cell", new JSONArray(cursor.getString(columnCell)));
            item.put("wifi", new JSONArray(cursor.getString(columnWifi)));
            items.put(item);

            cellCount += cursor.getInt(columnCellCount);
            wifiCount += cursor.getInt(columnWifiCount);
        }
    } catch (JSONException jsonex) {
        Log.e(LOGTAG, "JSONException", jsonex);
    }

    if (items.length() == 0) {
        return null;
    }

    long minId, maxId;
    cursor.moveToFirst();
    minId = cursor.getLong(columnId);
    cursor.moveToLast();
    maxId = cursor.getLong(columnId);

    JSONObject wrapper = new JSONObject(Collections.singletonMap("items", items));
    return new BatchRequestStats(wrapper.toString().getBytes(), wifiCount, cellCount, items.length(), minId,
            maxId);
}

From source file:com.google.android.apps.muzei.gallery.GallerySettingsActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
    if (mChosenUris == data) {
        return;//from  w  w  w  .j a  va 2s .co  m
    }
    final Cursor previousData = mChosenUris;
    mChosenUris = data;
    DiffUtil.calculateDiff(new DiffUtil.Callback() {
        @Override
        public int getOldListSize() {
            return previousData != null ? previousData.getCount() : 0;
        }

        @Override
        public int getNewListSize() {
            return data.getCount();
        }

        @Override
        public boolean areItemsTheSame(final int oldItemPosition, final int newItemPosition) {
            previousData.moveToPosition(oldItemPosition);
            String oldImageUri = previousData
                    .getString(previousData.getColumnIndex(GalleryContract.ChosenPhotos.COLUMN_NAME_URI));
            data.moveToPosition(newItemPosition);
            String newImageUri = data
                    .getString(data.getColumnIndex(GalleryContract.ChosenPhotos.COLUMN_NAME_URI));
            return oldImageUri.equals(newImageUri);
        }

        @Override
        public boolean areContentsTheSame(final int oldItemPosition, final int newItemPosition) {
            // If the items are the same (same image URI), then they are equivalent and
            // no change animation is needed
            return true;
        }
    }).dispatchUpdatesTo(mChosenPhotosAdapter);
    onDataSetChanged();
}

From source file:info.guardianproject.otr.app.im.app.AccountListActivity.java

public void signIn(long accountId) {
    if (accountId <= 0) {
        Log.w(TAG, "signIn: account id is 0, bail");
        return;//from   w ww  . ja  v a2s. co  m
    }
    Cursor cursor = mAdapter.getCursor();

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        long cAccountId = cursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);

        if (cAccountId == accountId)
            break;

        cursor.moveToNext();
    }

    // Remember that the user signed in.
    setKeepSignedIn(accountId, true);

    long providerId = cursor.getLong(PROVIDER_ID_COLUMN);
    String password = cursor.getString(ACTIVE_ACCOUNT_PW_COLUMN);

    boolean isActive = false; // TODO(miron)
    mSignInHelper.signIn(password, providerId, accountId, isActive);

    cursor.moveToPosition(-1);
}

From source file:it.imwatch.nfclottery.MainActivity.java

/**
 * Draws a winner from the stored contacts in the ContentProvider
 * that haven't already won.//  www  . j  a  v a  2 s .com
 */
public void drawWinner() {
    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(NFCMLContent.Geeks.CONTENT_URI, NFCMLContent.Geeks.PROJECTION,
            NFCMLContent.Geeks.Columns.TIMEWINNER.getName() + "=0", null, null);

    int count = c != null ? c.getCount() : 0;
    if (count == 0) {
        // There is nobody to draw from
        if (c != null) {
            c.close();
        }

        showCroutonNao(getString(R.string.no_more_nonwinning_contacts), Style.ALERT);
        return;
    }

    int winnerPosition = (new Random()).nextInt(count);
    c.moveToPosition(winnerPosition);

    String winnerEmail = c.getString(NFCMLContent.Geeks.Columns.EMAIL.getIndex());
    String winnerName = c.getString(NFCMLContent.Geeks.Columns.NAME.getIndex());

    if (DEBUG) {
        Log.d(TAG, String.format("The winner is %s (position: %d)", DataHelper.cleanupSeparators(winnerEmail),
                c.getPosition()));
    }
    c.close();

    showWinner(winnerPosition, winnerEmail, winnerName);
}