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:at.bitfire.davdroid.resource.LocalCalendar.java

public static LocalCalendar[] findAll(Account account, ContentProviderClient providerClient)
        throws RemoteException {
    @Cleanup
    Cursor cursor = providerClient.query(calendarsURI(account), new String[] { Calendars._ID, Calendars.NAME },
            Calendars.DELETED + "=0 AND " + Calendars.SYNC_EVENTS + "=1", null, null);

    LinkedList<LocalCalendar> calendars = new LinkedList<>();
    while (cursor != null && cursor.moveToNext())
        calendars.add(new LocalCalendar(account, providerClient, cursor.getInt(0), cursor.getString(1)));
    return calendars.toArray(new LocalCalendar[calendars.size()]);
}

From source file:com.ubuntuone.android.files.provider.MetaUtilities.java

public static Set<String> getUserNodePaths() {
    Set<String> userNodePaths = new TreeSet<String>();
    final String[] projection = new String[] { Nodes._ID, Nodes.NODE_RESOURCE_PATH };
    final String selection = Nodes.NODE_PARENT_PATH + " IS NULL";
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, null, null);
    try {/*ww  w .j  av  a 2s.c  om*/
        if (c.moveToFirst()) {
            String resourcePath;
            do {
                resourcePath = c.getString(c.getColumnIndex(Nodes.NODE_RESOURCE_PATH));
                userNodePaths.add(resourcePath);
            } while (c.moveToNext());
        }
    } finally {
        c.close();
    }
    return userNodePaths;
}

From source file:com.kevinquan.google.activityrecoginition.model.MotionHelper.java

public static List<MotionSnapshot> parseMotionSnapshots(Cursor result, final boolean sortDescending) {
    if (!CursorUtils.hasResults(result)) {
        Log.d(TAG, "No results were provided to parse motion snapshots from");
        return new ArrayList<MotionSnapshot>();
    }//w  ww . jav  a 2s  .  co  m
    Hashtable<Long, MotionSnapshot> snapshots = new Hashtable<Long, MotionSnapshot>();

    do {
        Motion thisMotion = new Motion(result);
        if (thisMotion.getTimestamp() == 0) {
            Log.w(TAG, "Current motion seems corrupt: " + thisMotion);
            continue;
        }
        if (!snapshots.containsKey(thisMotion.getTimestamp())) {
            MotionSnapshot snapshot = new MotionSnapshot(thisMotion);
            snapshots.put(snapshot.getTimestamp(), snapshot);
        } else {
            if (!snapshots.get(thisMotion.getTimestamp()).addMotion(thisMotion)) {
                Log.w(TAG, "Could not add motion to snapshot: " + thisMotion.toString());
            }
        }
    } while (result.moveToNext());

    List<MotionSnapshot> results = new ArrayList<MotionSnapshot>();
    results.addAll(snapshots.values());
    Collections.sort(results, new Comparator<MotionSnapshot>() {
        @Override
        public int compare(MotionSnapshot lhs, MotionSnapshot rhs) {
            int result = ((Long) lhs.getTimestamp()).compareTo((Long) rhs.getTimestamp());
            return sortDescending ? -1 * result : result;
        }
    });
    return results;
}

From source file:com.smarthome.deskclock.Alarms.java

/**
 * Disables non-repeating alarms that have passed.  Called at
 * boot./*from   ww w. j a v a2s.  c  om*/
 */
public static void disableExpiredAlarms(final Context context) {
    Cursor cur = getFilteredAlarmsCursor(context.getContentResolver());
    long now = System.currentTimeMillis();

    if (cur.moveToFirst()) {
        do {
            Alarm alarm = new Alarm(cur);
            // A time of 0 means this alarm repeats. If the time is
            // non-zero, check if the time is before now.
            if (alarm.time != 0 && alarm.time < now) {
                Log.v("Disabling expired alarm set for " + Log.formatTime(alarm.time));
                enableAlarmInternal(context, alarm, false);
            }
        } while (cur.moveToNext());
    }
    cur.close();
}

From source file:com.onesignal.NotificationOpenedProcessor.java

private static void addChildNotifications(JSONArray dataArray, String summaryGroup, SQLiteDatabase writableDb) {
    String[] retColumn = { NotificationTable.COLUMN_NAME_FULL_DATA };
    String[] whereArgs = { summaryGroup };

    Cursor cursor = writableDb.query(NotificationTable.TABLE_NAME, retColumn,
            NotificationTable.COLUMN_NAME_GROUP_ID + " = ? AND " + // Where String
                    NotificationTable.COLUMN_NAME_DISMISSED + " = 0 AND " + NotificationTable.COLUMN_NAME_OPENED
                    + " = 0 AND " + NotificationTable.COLUMN_NAME_IS_SUMMARY + " = 0",
            whereArgs, null, null, null);

    if (cursor.getCount() > 1) {
        cursor.moveToFirst();/* w  ww.  j  ava  2s. c  om*/
        do {
            try {
                String jsonStr = cursor
                        .getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_FULL_DATA));
                dataArray.put(new JSONObject(jsonStr));
            } catch (Throwable t) {
                OneSignal.Log(OneSignal.LOG_LEVEL.ERROR,
                        "Could not parse JSON of sub notification in group: " + summaryGroup);
            }
        } while (cursor.moveToNext());
    }

    cursor.close();
}

From source file:com.tcity.android.sync.SyncService.java

private void syncAll(@NotNull Cursor cursor) {
    while (cursor.moveToNext()) {
        try {/*www . j a  v  a 2 s .c  o m*/
            String id = DBUtils.getId(cursor);

            sync(id, DBUtils.getParentId(cursor), myDB.getBuildConfigurationSyncBound(id));
        } catch (IOException e) {
            Log.i(SyncService.class.getSimpleName(), e.getMessage(), e);
        }
    }
}

From source file:Main.java

/**
 * Print the content of the cursor/*from www . java2 s  .  c  o  m*/
 *
 * @param cursor, The cursor, which content needs to be printed
 * @param logTag, The log tag
 */
public static void printCursorContent(Cursor cursor, String logTag) {
    if (cursor == null) {
        Log.d(logTag, "Cursor is NULL!");
        return;
    }
    final int columnSpace = 2;
    ArrayList<Integer> columnWidth = new ArrayList<Integer>();
    for (int columnIndex = 0; columnIndex < cursor.getColumnCount(); columnIndex++) {
        String value = cursor.getColumnName(columnIndex);
        int maxWidth = value.length();
        if (cursor.moveToFirst()) {
            do {
                try {
                    value = cursor.getString(columnIndex);
                } catch (Exception e) {
                    value = "BLOB";
                    Log.d(logTag, "Get value from " + cursor.getColumnName(columnIndex) + " failed. Caused by "
                            + e.getLocalizedMessage());
                }
                if (!TextUtils.isEmpty(value) && value.length() > maxWidth) {
                    maxWidth = value.length();
                }
            } while (cursor.moveToNext());
        }
        columnWidth.add(maxWidth + columnSpace);
    }
    ArrayList<ArrayList<String>> tableContent = new ArrayList<ArrayList<String>>();
    for (int columnIndex = 0; columnIndex < cursor.getColumnCount(); columnIndex++) {
        ArrayList<String> columnContent = new ArrayList<String>();
        String value = cursor.getColumnName(columnIndex);
        columnContent.add(appendColumnSpaces(value, columnWidth.get(columnIndex)));
        if (cursor.moveToFirst()) {
            do {
                try {
                    value = cursor.getString(columnIndex);
                } catch (Exception e) {
                    value = "BLOB";
                }
                columnContent.add(appendColumnSpaces(value, columnWidth.get(columnIndex)));
            } while (cursor.moveToNext());
        }
        tableContent.add(columnContent);
    }
    // Including the header
    int maxRowIndex = cursor.getCount() + 1;
    for (int rowIndex = 0; rowIndex < maxRowIndex; rowIndex++) {
        StringBuilder rowValues = new StringBuilder();
        for (int columnIndex = 0; columnIndex < cursor.getColumnCount(); columnIndex++) {
            ArrayList<String> columnValues = tableContent.get(columnIndex);
            rowValues.append(columnValues.get(rowIndex));
        }
        Log.d(logTag, rowValues.toString());
    }
    // set the cursor back the first item
    cursor.moveToFirst();
}

From source file:edu.stanford.mobisocial.dungbeetle.model.DbObject.java

/**
 * @param v the view to bind//  w w w . j a  v a 2 s.  c  o m
 * @param context standard activity context
 * @param c the cursor source for the object in the db object table.
 * Must include _id in the projection.
 * 
 * @param allowInteractions controls whether the bound view is
 * allowed to intercept touch events and do its own processing.
 */
public static void bindView(View v, final Context context, Cursor cursor, boolean allowInteractions) {
    TextView nameText = (TextView) v.findViewById(R.id.name_text);
    ViewGroup frame = (ViewGroup) v.findViewById(R.id.object_content);
    frame.removeAllViews();

    // make sure we have all the columns we need
    Long objId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID));
    String[] projection = null;
    String selection = DbObj.COL_ID + " = ?";
    String[] selectionArgs = new String[] { Long.toString(objId) };
    String sortOrder = null;
    Cursor c = context.getContentResolver().query(DbObj.OBJ_URI, projection, selection, selectionArgs,
            sortOrder);
    if (!c.moveToFirst()) {
        Log.w(TAG, "could not find obj " + objId);
        c.close();
        return;
    }
    DbObj obj = App.instance().getMusubi().objForCursor(c);
    if (obj == null) {
        nameText.setText("Failed to access database.");
        Log.e("DbObject", "cursor was null for bindView of DbObject");
        return;
    }
    DbUser sender = obj.getSender();
    Long timestamp = c.getLong(c.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP));
    Long hash = obj.getHash();
    short deleted = c.getShort(c.getColumnIndexOrThrow(DELETED));
    String feedName = obj.getFeedName();
    String type = obj.getType();
    Date date = new Date(timestamp);
    c.close();
    c = null;

    if (sender == null) {
        nameText.setText("Message from unknown contact.");
        return;
    }
    nameText.setText(sender.getName());

    final ImageView icon = (ImageView) v.findViewById(R.id.icon);
    if (sViewProfileAction == null) {
        sViewProfileAction = new OnClickViewProfile((Activity) context);
    }
    icon.setTag(sender.getLocalId());
    if (allowInteractions) {
        icon.setOnClickListener(sViewProfileAction);
        v.setTag(objId);
    }
    icon.setImageBitmap(sender.getPicture());

    if (deleted == 1) {
        v.setBackgroundColor(sDeletedColor);
    } else {
        v.setBackgroundColor(Color.TRANSPARENT);
    }

    TextView timeText = (TextView) v.findViewById(R.id.time_text);
    timeText.setText(RelativeDate.getRelativeDate(date));

    frame.setTag(objId); // TODO: error prone! This is database id
    frame.setTag(R.id.object_entry, cursor.getPosition()); // this is cursor id
    FeedRenderer renderer = DbObjects.getFeedRenderer(type);
    if (renderer != null) {
        renderer.render(context, frame, obj, allowInteractions);
    }

    if (!allowInteractions) {
        v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
        v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
    } else {
        if (!MusubiBaseActivity.isDeveloperModeEnabled(context)) {
            v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
            v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
        } else {
            ImageView attachmentCountButton = (ImageView) v.findViewById(R.id.obj_attachments_icon);
            TextView attachmentCountText = (TextView) v.findViewById(R.id.obj_attachments);
            attachmentCountButton.setVisibility(View.VISIBLE);

            if (hash == 0) {
                attachmentCountButton.setVisibility(View.GONE);
            } else {
                //int color = DbObject.colorFor(hash);
                boolean selfPost = false;
                DBHelper helper = new DBHelper(context);
                try {
                    Cursor attachments = obj.getSubfeed().query("type=?", new String[] { LikeObj.TYPE });
                    try {
                        attachmentCountText.setText("+" + attachments.getCount());

                        if (attachments.moveToFirst()) {
                            while (!attachments.isAfterLast()) {
                                if (attachments.getInt(attachments.getColumnIndex(CONTACT_ID)) == -666) {
                                    selfPost = true;
                                    break;
                                }
                                attachments.moveToNext();

                            }
                        }
                    } finally {
                        attachments.close();
                    }
                } finally {
                    helper.close();
                }
                if (selfPost) {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love_red);
                } else {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love);
                }
                attachmentCountText.setTag(R.id.object_entry, hash);
                attachmentCountText.setTag(R.id.feed_label, Feed.uriForName(feedName));
                attachmentCountText.setOnClickListener(LikeListener.getInstance(context));
            }
        }
    }
}

From source file:com.orm.androrm.migration.MigrationHelper.java

public boolean hasField(Class<? extends Model> model, String name) {
    String table = DatabaseBuilder.getTableName(model);
    String sql = "PRAGMA TABLE_INFO(`" + table + "`)";

    Cursor c = getCursor(sql);

    while (c.moveToNext()) {
        String fieldName = c.getString(c.getColumnIndexOrThrow("name"));

        if (fieldName.equals(name)) {
            close(c);/*w w w  .  j  av a2 s  . c o  m*/
            return true;
        }
    }

    close(c);
    return false;
}

From source file:com.orm.androrm.migration.MigrationHelper.java

/**
 * Checks whether a given table name already exists in the database.
 * //from www. ja v  a  2s .c om
 * @param name Name of the table to look up.
 * @return <code>true</code> if one exists <code>false</code> otherwise.
 */
public boolean tableExists(String name) {
    String sql = "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '" + name + "'";

    Cursor c = getCursor(sql);

    while (c.moveToNext()) {
        String table = c.getString(c.getColumnIndexOrThrow("name"));

        if (table.equalsIgnoreCase(name)) {
            close(c);

            return true;
        }
    }

    close(c);
    return false;
}