Example usage for android.database Cursor moveToNext

List of usage examples for android.database Cursor moveToNext

Introduction

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

Prototype

boolean moveToNext();

Source Link

Document

Move the cursor to the next row.

Usage

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

private static void addPhonesToContactEntry(ContentResolver cr, long personId, ContactEntry entry)
        throws ParseException {
    Cursor c = cr.query(Phones.CONTENT_URI, null, "person=" + personId, null, null);
    int numberIndex = c.getColumnIndexOrThrow(People.Phones.NUMBER);
    try {//from  w  w  w.j  av  a2s  .co  m
        while (c.moveToNext()) {
            PhoneNumber phoneNumber = new PhoneNumber();
            cursorToContactsElement(phoneNumber, c, PROVIDER_TYPE_TO_ENTRY_PHONE);
            phoneNumber.setPhoneNumber(c.getString(numberIndex));
            entry.addPhoneNumber(phoneNumber);
        }
    } finally {
        if (c != null)
            c.close();
    }
}

From source file:net.peterkuterna.android.apps.devoxxsched.io.RemoteScheduleHandler.java

@Override
public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver)
        throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final HashMap<String, ContentProviderOperation> blockBatchMap = Maps.newHashMap();
    final HashMap<String, ContentProviderOperation> sessionUpdateBatchMap = Maps.newHashMap();

    int nrEntries = 0;
    for (JSONArray schedules : entries) {
        Log.d(TAG, "Retrieved " + schedules.length() + " schedule entries.");
        nrEntries += schedules.length();

        for (int i = 0; i < schedules.length(); i++) {
            JSONObject schedule = schedules.getJSONObject(i);

            final long startTime = ParserUtils.parseDevoxxTime(schedule.getString("fromTime"));
            final long endTime = ParserUtils.parseDevoxxTime(schedule.getString("toTime"));
            final String kind = schedule.getString("kind");

            final String blockId = Blocks.generateBlockId(kind, startTime, endTime);

            if (!blockBatchMap.containsKey(blockId)) {
                final Uri blockUri = Blocks.buildBlockUri(blockId);

                ContentProviderOperation.Builder builder;
                if (isRowExisting(Blocks.buildBlockUri(blockId), BlocksQuery.PROJECTION, resolver)) {
                    builder = ContentProviderOperation.newUpdate(blockUri);
                } else {
                    builder = ContentProviderOperation.newInsert(Blocks.CONTENT_URI);
                    builder.withValue(Blocks.BLOCK_ID, blockId);
                }/*from  www  . j  a  va  2  s  . c  om*/
                builder.withValue(Blocks.BLOCK_START, startTime);
                builder.withValue(Blocks.BLOCK_END, endTime);

                final String type = schedule.getString("type");
                final String code = schedule.getString("code");

                if (code.startsWith("D10")) {
                    builder.withValue(Blocks.BLOCK_TITLE, type.replaceAll("\\ \\(.*\\)", ""));
                } else {
                    builder.withValue(Blocks.BLOCK_TITLE, schedule.getString("code"));
                }

                builder.withValue(Blocks.BLOCK_TYPE, kind);
                blockBatchMap.put(blockId, builder.build());
            }

            if (schedule.has("presentationUri")) {
                final Uri presentationUri = Uri.parse(schedule.getString("presentationUri"));
                final String sessionId = presentationUri.getLastPathSegment();
                final Uri sessionUri = Sessions.buildSessionUri(sessionId);

                if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
                    String roomId = null;
                    if (schedule.has("room")) {
                        final String roomName = schedule.getString("room");
                        Cursor cursor = resolver.query(Rooms.buildRoomsWithNameUri(roomName),
                                RoomsQuery.PROJECTION, null, null, null);
                        if (cursor.moveToNext()) {
                            roomId = cursor.getString(RoomsQuery.ROOM_ID);
                        }
                        cursor.close();
                    }
                    final ContentProviderOperation.Builder builder = ContentProviderOperation
                            .newUpdate(sessionUri);
                    builder.withValue(Sessions.BLOCK_ID, blockId);
                    builder.withValue(Sessions.ROOM_ID, roomId);
                    if (schedule.has("note")) {
                        final String note = schedule.getString("note");
                        if (note != null && note.trim().length() > 0) {
                            builder.withValue(Sessions.NOTE, note.trim());
                        }
                    }

                    sessionUpdateBatchMap.put(sessionId, builder.build());
                }
            }
        }
    }

    batch.addAll(blockBatchMap.values());
    batch.addAll(sessionUpdateBatchMap.values());

    if (isRemoteSync() && nrEntries > 0) {
        for (String lostId : getLostIds(blockBatchMap.keySet(), Blocks.CONTENT_URI, BlocksQuery.PROJECTION,
                BlocksQuery.BLOCK_ID, resolver)) {
            if (!lostId.startsWith("lab")) {
                final Uri lostBlockUri = Blocks.buildBlockUri(lostId);
                batch.add(ContentProviderOperation.newDelete(lostBlockUri).build());
            }
        }
        for (String lostId : getLostIds(sessionUpdateBatchMap.keySet(), Sessions.CONTENT_URI,
                SessionsQuery.PROJECTION, SessionsQuery.SESSION_ID, resolver)) {
            Uri deleteUri = Sessions.buildSpeakersDirUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildTagsDirUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildSessionUri(lostId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

From source file:com.clevertrail.mobile.Database_SavedTrails.java

public String queueAll() {
    String[] columns = new String[] { "name", "json" };
    Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int index_NAME = cursor.getColumnIndex("name");
    for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
        result = result + cursor.getString(index_NAME) + "\n";
    }//  w  w w  . j  av a  2 s .c  o  m

    return result;
}

From source file:it.ms.theing.loquitur.functions.PhoneDir.java

/**
 * This function returns the full phone directory
 * @return//from  www . ja v  a2  s  . co  m
 * a Json array of phone / email fields
 * structure : [ { name:... , phone: ... , email: ... }, ..... ]
 */
@JavascriptInterface
public String list() {
    Cursor cursor = null;
    try {
        JSONArray obj = new JSONArray();
        cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
                null);
        while (cursor.moveToNext()) {

            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String ID = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String phone = getPhone(ID);
            String email = getEmail(ID);

            JSONObject jo = new JSONObject();
            jo.put("name", name.toLowerCase());
            jo.put("phone", phone);
            jo.put("email", email);
            obj.put(jo);

        }
        cursor.close();
        cursor = null;
        return obj.toString();
    } catch (Exception e) {
        Utils.safe(e);
    }

    if (cursor != null) {
        try {
            cursor.close();
        } catch (Exception e) {
        }
    }
    return "";
}

From source file:com.confidentsoftware.themebuilder.FlickrParser.java

private int addImagesFromJson(long wordId, String text, JSONObject queryResult) throws JSONException {
    JSONArray photos = queryResult.getJSONArray("photo");
    int numImages = 0;
    for (int i = 0; i < photos.length(); i++) {
        JSONObject photo = null;//ww w.  j  a v  a2s. c  o  m
        try {
            photo = photos.getJSONObject(i);
        } catch (JSONException e) {
            continue;
        }
        try {
            if (isPhotoOk(photo)) {
                String url = photo.getString(PHOTO_URL);
                String title = photo.getString("title");
                if (title.length() > MAX_TITLE_LENGTH) {
                    title = title.substring(0, MAX_TITLE_LENGTH - 3) + "...";
                }
                String id = photo.getString("id");
                Log.d(TAG, "Image: " + id);
                Uri imageUri = Images.findImage(mCr, Sites.CONTENT_URI_FLICKR, id);
                if (imageUri != null) {
                    Log.d(TAG, "Found existing image: " + imageUri);
                    // Just insert the mapping
                    Uri mappingUri = Dictionary.Words.CONTENT_URI.buildUpon().appendPath(String.valueOf(wordId))
                            .appendPath(Dictionary.PATH_IMAGES).appendPath(imageUri.getLastPathSegment())
                            .build();
                    Cursor c = mCr.query(mappingUri, PROJECTION_ID, null, null, null);
                    try {
                        if (!c.moveToNext()) {
                            mCr.insert(mappingUri, null);
                        }
                    } finally {
                        c.close();
                    }
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Images.URL, url);
                    values.put(Images.SITE, ContentUris.parseId(Sites.CONTENT_URI_FLICKR));
                    values.put(Images.SITE_UNIQUE_NAME, id);
                    values.put(Images.WIDTH, photo.getInt(PHOTO_WIDTH));
                    values.put(Images.HEIGHT, photo.getInt(PHOTO_HEIGHT));
                    values.put(Images.THUMB_URL, photo.getString(THUMB_URL));
                    values.put(Images.NUM_FAVORITES, getNumFavorites(id));
                    imageUri = mCr.insert(Dictionary.BASE_CONTENT_URI.buildUpon()
                            .appendPath(Dictionary.PATH_WORDS).appendPath(String.valueOf(wordId))
                            .appendPath(Dictionary.PATH_IMAGES).build(), values);
                    //
                    // String ownerName = photo.getString("owner");
                    // Author author = findAuthor(ownerName);
                    // if (author == null) {
                    // author = buildAuthor(ownerName);
                    // }
                    // TODO set license
                    // image.setLicense(License.getLicenseByFlickrId(photo
                    // .getInt("license")));
                    // dbHelper.getImageDao().create(image);
                }
                // dbHelper.getWordImageDao().create(
                // new WordImage(word, image));
                numImages++;
            }
        } catch (JSONException e) {
            // Catch here so that we continue through the loop
            Log.w(TAG, "Error parsing photo: " + photo, e);
        }
    }
    return numImages;
}

From source file:de.stadtrallye.rallyesoft.model.map.MapManager.java

private void readDatabase(List<Node> nodes, List<Edge> edges) {
    Cursor c = getDb().query(Nodes.TABLE, Nodes.COLS, null, null, null, null, null);

    while (c.moveToNext()) {
        nodes.add(new Node((int) c.getLong(0), c.getString(1), new LatLng(c.getDouble(2), c.getDouble(3)),
                c.getString(4)));/*w  w w .j a  va2  s  .  co m*/
    }
    c.close();

    c = getDb().query(Edges.TABLE, Edges.COLS, null, null, null, null, null);

    while (c.moveToNext()) {
        edges.add(new Edge(nodes.get((int) c.getLong(0)), nodes.get((int) c.getLong(1)), c.getString(2)));
    }
    c.close();
}

From source file:com.amazonaws.mobileconnectors.pinpoint.internal.event.EventRecorder.java

public List<JSONObject> getAllEvents() {
    final List<JSONObject> events = new ArrayList<JSONObject>();
    Cursor cursor = null;
    try {//from   w  ww . ja  va 2 s  . co  m
        cursor = dbUtil.queryAllEvents();
        while (cursor.moveToNext()) {
            events.add(translateFromCursor(cursor));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return events;
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

/**
 * Look at the groups sync settings and the overall sync preference to determine which
 * feeds to sync and add them to the feedsToSync list.
 *///from w  w  w.  jav a 2  s.  c  o  m
public static void addContactsFeedsToSync(ContentResolver cr, String account, Collection<String> feedsToSync) {
    boolean shouldSyncEverything = getShouldSyncEverything(cr, account);
    if (shouldSyncEverything) {
        feedsToSync.add(getContactsFeedForAccount(account));
        return;
    }

    Cursor cursor = cr.query(Contacts.Groups.CONTENT_URI, new String[] { Groups._SYNC_ID },
            "_sync_account=? AND should_sync>0", new String[] { account }, null);
    try {
        while (cursor.moveToNext()) {
            feedsToSync.add(getContactsFeedForGroup(account, cursor.getString(0)));
        }
    } finally {
        cursor.close();
    }
}

From source file:com.odoo.support.provider.OContentProvider.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    reInitModel();// w  ww . ja  va  2 s  .co  m
    SelectionBuilder builder = new SelectionBuilder();
    final SQLiteDatabase db = model.getWritableDatabase();
    final int match = matcher.match(uri);
    int count;
    switch (match) {
    case COLLECTION:
        Cursor cr = query(uri, new String[] { OColumn.ROW_ID }, where, whereArgs, null);
        while (cr.moveToNext()) {
            int id = cr.getInt(cr.getColumnIndex(OColumn.ROW_ID));
            handleManyToMany(getManyToManyRecords(values), id);
        }
        cr.close();

        count = builder.table(model.getTableName()).where(where, whereArgs).update(db, values);
        break;
    case SINGLE_ROW:
        String id = uri.getLastPathSegment();
        handleManyToMany(getManyToManyRecords(values), Integer.parseInt(id));
        count = builder.table(model.getTableName()).where(where, whereArgs).where(OColumn.ROW_ID + "=?", id)
                .where(where, whereArgs).update(db, values);
        break;
    default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    Context ctx = getContext();
    assert ctx != null;
    ctx.getContentResolver().notifyChange(uri, null, false);
    return count;
}

From source file:com.facebook.stetho.inspector.protocol.module.Database.java

/**
 * Flatten all columns and all rows of a cursor to a single array.  The array cannot be
 * interpreted meaningfully without the number of columns.
 *
 * @param cursor/*  w w  w  . ja  va2 s.c o m*/
 * @param limit Maximum number of rows to process.
 * @return List of Java primitives matching the value type of each column.
 */
private List<Object> flattenRows(Cursor cursor, int limit) {
    Util.throwIfNot(limit >= 0);
    List<Object> flatList = new ArrayList<Object>();
    final int numColumns = cursor.getColumnCount();
    for (int row = 0; row < limit && cursor.moveToNext(); row++) {
        for (int column = 0; column < numColumns; column++) {
            switch (cursor.getType(column)) {
            case Cursor.FIELD_TYPE_NULL:
                flatList.add(null);
                break;
            case Cursor.FIELD_TYPE_INTEGER:
                flatList.add(cursor.getLong(column));
                break;
            case Cursor.FIELD_TYPE_FLOAT:
                flatList.add(cursor.getDouble(column));
                break;
            case Cursor.FIELD_TYPE_BLOB:
                flatList.add(cursor.getBlob(column));
                break;
            case Cursor.FIELD_TYPE_STRING:
            default:
                flatList.add(cursor.getString(column));
                break;
            }
        }
    }
    if (!cursor.isAfterLast()) {
        for (int column = 0; column < numColumns; column++) {
            flatList.add("{truncated}");
        }
    }
    return flatList;
}