Example usage for android.database Cursor getInt

List of usage examples for android.database Cursor getInt

Introduction

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

Prototype

int getInt(int columnIndex);

Source Link

Document

Returns the value of the requested column as an int.

Usage

From source file:com.navjagpal.fileshare.WebServer.java

private String getFileListing(Uri uri) {
    int folderId = Integer.parseInt(uri.getPathSegments().get(1));
    Uri fileUri = FileSharingProvider.Files.CONTENT_URI;
    String where = FileSharingProvider.Files.Columns.FOLDER_ID + "=" + folderId;
    Cursor c = mContext.getContentResolver().query(fileUri, null, where, null, null);
    int nameIndex = c.getColumnIndexOrThrow(FileSharingProvider.Files.Columns.DISPLAY_NAME);
    int idIndex = c.getColumnIndexOrThrow(FileSharingProvider.Files.Columns._ID);
    String s = "";
    boolean hasMusic = false;
    while (c.moveToNext()) {
        String name = c.getString(nameIndex);
        int id = c.getInt(idIndex);
        s += fileToLink(name, id) + "<br/>";
        if (name.endsWith(".mp3")) {
            hasMusic = true;/*from w  w w.j a v a2s .  com*/
        }
    }
    c.close();
    if (hasMusic) {
        s += getPlaylistLink(folderId) + "<br/>";
    }
    s += getZipLink(folderId) + "<br/>";
    return s;
}

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

private void fillFieldValue(int type, Field field, Object entity, Cursor cursor, int i)
        throws IllegalAccessException {
    if (cursor.isNull(i)) {
        field.set(entity, null);/*from   w  ww  .j  a va2s .  c o m*/
        return;
    }
    switch (type) {
    case INTEGER:
        field.set(entity, cursor.getInt(i));
        break;
    case SHORT:
        field.set(entity, cursor.getShort(i));
        break;
    case LONG:
        field.set(entity, cursor.getLong(i));
        break;
    case FLOAT:
        field.set(entity, cursor.getFloat(i));
        break;
    case DOUBLE:
        field.set(entity, cursor.getDouble(i));
        break;
    case STRING:
        field.set(entity, cursor.getString(i));
        break;
    case BYTE_ARRAY:
        field.set(entity, cursor.getBlob(i));
        break;
    case DATE:
        field.set(entity, new Date(cursor.getLong(i)));
        break;
    case BOOLEAN:
        field.set(entity, cursor.getInt(i) != 0);
        break;
    }
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility.java

/**
 * Gets a list of TransferObserver instances which are observing records
 * with the given type./*  www . jav  a  2 s  .c o  m*/
 *
 * @param type The type of the transfer.
 * @param states A list of the the transfer states.
 * @return A list of TransferObserver of transfer records with the given
 *         type and state.
 */
public List<TransferObserver> getTransfersWithTypeAndStates(TransferType type, TransferState[] states) {
    final List<TransferObserver> transferObservers = new ArrayList<TransferObserver>();
    Cursor c = null;
    try {
        c = dbUtil.queryTransfersWithTypeAndStates(type, states);
        while (c.moveToNext()) {
            final int partNum = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_PART_NUM));
            if (partNum != 0) {
                // skip parts of a multipart upload
                continue;
            }
            final int id = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_ID));
            final TransferObserver to = new TransferObserver(id, dbUtil);
            to.updateFromDB(c);
            transferObservers.add(to);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return transferObservers;
}

From source file:com.navjagpal.fileshare.WebServer.java

private String getFolderListing() {
    /* Get list of folders */
    Cursor c = mContext.getContentResolver().query(FileSharingProvider.Folders.CONTENT_URI, null, null, null,
            null);/*  w ww  .ja  va2 s .c o m*/
    int nameIndex = c.getColumnIndexOrThrow(FileSharingProvider.Folders.Columns.DISPLAY_NAME);
    int idIndex = c.getColumnIndexOrThrow(FileSharingProvider.Folders.Columns._ID);
    String s = "";
    while (c.moveToNext()) {
        String name = c.getString(nameIndex);
        int id = c.getInt(idIndex);
        s += folderToLink(name, id) + "<br/>";
    }
    c.close();
    return s;
}

From source file:gov.wa.wsdot.android.wsdot.ui.FerriesRouteSchedulesDayDeparturesFragment.java

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

    // Tell the framework to try to keep this fragment around
    // during a configuration change.
    setRetainInstance(true);/*w w  w. ja  v a  2  s  .  c  om*/

    ferriesTerminalSyncCallbacks = new LoaderCallbacks<Cursor>() {

        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            String[] projection = { FerriesTerminalSailingSpace._ID, FerriesTerminalSailingSpace.TERMINAL_ID,
                    FerriesTerminalSailingSpace.TERMINAL_NAME, FerriesTerminalSailingSpace.TERMINAL_ABBREV,
                    FerriesTerminalSailingSpace.TERMINAL_DEPARTING_SPACES,
                    FerriesTerminalSailingSpace.TERMINAL_LAST_UPDATED,
                    FerriesTerminalSailingSpace.TERMINAL_IS_STARRED };

            CursorLoader cursorLoader = new FerriesTerminalLoader(getActivity(),
                    FerriesTerminalSailingSpace.CONTENT_URI, projection, null, null, null);

            return cursorLoader;
        }

        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a");
            dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));

            if (cursor != null && cursor.moveToFirst()) {
                // Update existing FerriesScheduleTimesItem (times)
                do {
                    int departingTerminalID = cursor
                            .getInt(cursor.getColumnIndex(FerriesTerminalSailingSpace.TERMINAL_ID));
                    if (departingTerminalID != terminalItem.getDepartingTerminalID()) {
                        continue;
                    }
                    try {
                        JSONArray departingSpaces = new JSONArray(cursor.getString(
                                cursor.getColumnIndex(FerriesTerminalSailingSpace.TERMINAL_DEPARTING_SPACES)));
                        for (int i = 0; i < departingSpaces.length(); i++) {
                            JSONObject spaces = departingSpaces.getJSONObject(i);
                            String departure = dateFormat.format(
                                    new Date(Long.parseLong(spaces.getString("Departure").substring(6, 19))));
                            JSONArray spaceForArrivalTerminals = spaces
                                    .getJSONArray("SpaceForArrivalTerminals");
                            for (int j = 0; j < spaceForArrivalTerminals.length(); j++) {
                                JSONObject terminals = spaceForArrivalTerminals.getJSONObject(j);
                                if (terminals.getInt("TerminalID") != terminalItem.getArrivingTerminalID()) {
                                    continue;
                                } else {
                                    int driveUpSpaceCount = terminals.getInt("DriveUpSpaceCount");
                                    int maxSpaceCount = terminals.getInt("MaxSpaceCount");
                                    for (FerriesScheduleTimesItem time : times) {
                                        if (dateFormat.format(new Date(Long.parseLong(time.getDepartingTime())))
                                                .equals(departure)) {
                                            time.setDriveUpSpaceCount(driveUpSpaceCount);
                                            time.setMaxSpaceCount(maxSpaceCount);
                                            time.setLastUpdated(cursor.getString(cursor.getColumnIndex(
                                                    FerriesTerminalSailingSpace.TERMINAL_LAST_UPDATED)));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } while (cursor.moveToNext());
            }

            swipeRefreshLayout.setRefreshing(false);
            adapter.clear();
            adapter.setData(times);
        }

        public void onLoaderReset(Loader<Cursor> loader) {
            swipeRefreshLayout.setRefreshing(false);
        }
    };
}

From source file:com.granita.contacticloudsync.resource.LocalCalendar.java

@SuppressWarnings("Recycle")
public void processDirtyExceptions() throws CalendarStorageException {
    // process deleted exceptions
    Constants.log.info("Processing deleted exceptions");
    try {/*from   ww  w  . j  a v a  2  s.c  o  m*/
        @Cleanup
        Cursor cursor = provider.query(syncAdapterURI(Events.CONTENT_URI),
                new String[] { Events._ID, Events.ORIGINAL_ID, LocalEvent.COLUMN_SEQUENCE },
                Events.DELETED + "!=0 AND " + Events.ORIGINAL_ID + " IS NOT NULL", null, null);
        while (cursor != null && cursor.moveToNext()) {
            Constants.log.debug("Found deleted exception, removing; then re-schuling original event");
            long id = cursor.getLong(0), // can't be null (by definition)
                    originalID = cursor.getLong(1); // can't be null (by query)
            int sequence = cursor.isNull(2) ? 0 : cursor.getInt(2);

            // get original event's SEQUENCE
            @Cleanup
            Cursor cursor2 = provider.query(
                    syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)),
                    new String[] { LocalEvent.COLUMN_SEQUENCE }, null, null, null);
            int originalSequence = cursor.isNull(0) ? 0 : cursor.getInt(0);

            BatchOperation batch = new BatchOperation(provider);
            // re-schedule original event and set it to DIRTY
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)))
                    .withValue(LocalEvent.COLUMN_SEQUENCE, originalSequence)
                    .withValue(Events.DIRTY, DIRTY_INCREASE_SEQUENCE).build());
            // remove exception
            batch.enqueue(ContentProviderOperation
                    .newDelete(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id))).build());
            batch.commit();
        }
    } catch (RemoteException e) {
        throw new CalendarStorageException("Couldn't process locally modified exception", e);
    }

    // process dirty exceptions
    Constants.log.info("Processing dirty exceptions");
    try {
        @Cleanup
        Cursor cursor = provider.query(syncAdapterURI(Events.CONTENT_URI),
                new String[] { Events._ID, Events.ORIGINAL_ID, LocalEvent.COLUMN_SEQUENCE },
                Events.DIRTY + "!=0 AND " + Events.ORIGINAL_ID + " IS NOT NULL", null, null);
        while (cursor != null && cursor.moveToNext()) {
            Constants.log.debug("Found dirty exception, increasing SEQUENCE to re-schedule");
            long id = cursor.getLong(0), // can't be null (by definition)
                    originalID = cursor.getLong(1); // can't be null (by query)
            int sequence = cursor.isNull(2) ? 0 : cursor.getInt(2);

            BatchOperation batch = new BatchOperation(provider);
            // original event to DIRTY
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)))
                    .withValue(Events.DIRTY, DIRTY_DONT_INCREASE_SEQUENCE).build());
            // increase SEQUENCE and set DIRTY to 0
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id)))
                    .withValue(LocalEvent.COLUMN_SEQUENCE, sequence + 1).withValue(Events.DIRTY, 0).build());
            batch.commit();
        }
    } catch (RemoteException e) {
        throw new CalendarStorageException("Couldn't process locally modified exception", e);
    }
}

From source file:se.kth.ssvl.tslab.bytewalla.androiddtn.servlib.storage.SQLiteImplementation.java

/**
 * Get record from database based on condition.
 *  This function is used to only one record from database
 * @param table Name of table in which record already exist
 * @param condition Get record where this condition matches
 * @param field Only get this field from resulted row
 * @param orderBy Orderby Clause for SQLite Query 
 * @param limit Number of row get/*from  w w  w  .j a v a2 s .  c  o  m*/
 * @return Return required field value if found otherwise return -1
 */

public int get_record(String table, String condition, String field, String orderBy, String limit) {

    try {
        Cursor cursor = db.query(table, null, condition, null, null, null, orderBy, limit);

        int fieldColumn = cursor.getColumnIndex(field);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int result = cursor.getInt(fieldColumn);
                cursor.close();
                return result;
            }
        } else {
            Log.d(TAG, "Row not found!");
        }
        cursor.close();
    } catch (IndexOutOfBoundsException e) {
        Log.e(TAG, "Id Already deleted");
    } catch (SQLiteException e) {
        Log.e(TAG, "Coundn't run the query");
    } catch (Exception e) {
        Log.e(TAG, "General Exception");
    }
    return -1;
}

From source file:com.QuarkLabs.BTCeClient.services.CheckTickersService.java

/**
 * Processes new data, adds notifications if any
 *
 * @param tickersList JSONObject with new tickers data
 * @param oldData     JSONObject with old tickers data
 * @return String with all notifications
 *//*from   ww  w. j  a  va2 s  .co m*/
private String checkNotifiers(ArrayList<Ticker> tickersList, Map<String, Ticker> oldData) {

    DBWorker dbWorker = DBWorker.getInstance(this);
    Cursor cursor = dbWorker.getNotifiers();

    StringBuilder stringBuilder = new StringBuilder();
    for (Ticker ticker : tickersList) {
        cursor.moveToFirst();
        String pair = ticker.getPair();
        if (oldData.size() != 0 && oldData.containsKey(pair)) {
            double oldValue = oldData.get(pair).getLast();
            double newValue = ticker.getLast();
            while (!cursor.isAfterLast()) {
                boolean pairMatched = pair.replace("_", "/").toUpperCase(Locale.US)
                        .equals(cursor.getString(cursor.getColumnIndex("Pair")));
                if (pairMatched) {
                    float percent;
                    switch (cursor.getInt(cursor.getColumnIndex("Type"))) {
                    case PANIC_BUY_TYPE:
                        percent = cursor.getFloat(cursor.getColumnIndex("Value")) / 100;
                        if (newValue > ((1 + percent) * oldValue)) {
                            stringBuilder.append("Panic Buy for ")
                                    .append(pair.replace("_", "/").toUpperCase(Locale.US)).append("; ");
                        }
                        break;
                    case PANIC_SELL_TYPE:
                        percent = cursor.getFloat(cursor.getColumnIndex("Value")) / 100;
                        if (newValue < ((1 - percent) * oldValue)) {
                            stringBuilder.append("Panic Sell for ")
                                    .append(pair.replace("_", "/").toUpperCase(Locale.US)).append("; ");
                        }
                        break;
                    case STOP_LOSS_TYPE:
                        if (newValue < cursor.getFloat(cursor.getColumnIndex("Value"))) {
                            stringBuilder.append("Stop Loss for ")
                                    .append(pair.replace("_", "/").toUpperCase(Locale.US)).append("; ");
                        }
                        break;
                    case TAKE_PROFIT_TYPE:
                        if (newValue > cursor.getFloat(cursor.getColumnIndex("Value"))) {
                            stringBuilder.append("Take Profit for ")
                                    .append(pair.replace("_", "/").toUpperCase(Locale.US)).append("; ");
                        }
                        break;
                    default:
                        break;
                    }
                }
                cursor.moveToNext();
            }
        }
    }
    cursor.close();
    return stringBuilder.toString();
}

From source file:com.geniusgithub.contact.contact.calllog.ContactInfoHelper.java

/**
 * Looks up a contact using the given URI.
 * <p>/*from ww  w .  j av a  2  s  .co m*/
 * It returns null if an error occurs, {@link ContactInfo#EMPTY} if no matching contact is
 * found, or the {@link ContactInfo} for the given contact.
 * <p>
 * The {@link ContactInfo#formattedNumber} field is always set to {@code null} in the returned
 * value.
 */
private ContactInfo lookupContactFromUri(Uri uri) {
    final ContactInfo info;
    Cursor phonesCursor = mContext.getContentResolver().query(uri, PhoneQuery._PROJECTION, null, null, null);

    if (phonesCursor != null) {
        try {
            if (phonesCursor.moveToFirst()) {
                info = new ContactInfo();
                long contactId = phonesCursor.getLong(PhoneQuery.PERSON_ID);
                String lookupKey = phonesCursor.getString(PhoneQuery.LOOKUP_KEY);
                info.lookupKey = lookupKey;
                info.lookupUri = Contacts.getLookupUri(contactId, lookupKey);
                info.name = phonesCursor.getString(PhoneQuery.NAME);
                info.type = phonesCursor.getInt(PhoneQuery.PHONE_TYPE);
                info.label = phonesCursor.getString(PhoneQuery.LABEL);
                info.number = phonesCursor.getString(PhoneQuery.MATCHED_NUMBER);
                info.normalizedNumber = phonesCursor.getString(PhoneQuery.NORMALIZED_NUMBER);
                info.photoId = phonesCursor.getLong(PhoneQuery.PHOTO_ID);
                info.photoUri = UriUtils.parseUriOrNull(phonesCursor.getString(PhoneQuery.PHOTO_URI));
                info.formattedNumber = null;
            } else {
                info = ContactInfo.EMPTY;
            }
        } finally {
            phonesCursor.close();
        }
    } else {
        // Failed to fetch the data, ignore this request.
        info = null;
    }
    return info;
}

From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * ?getItem//from www  . ja v a  2 s .c  o m
 *
 * @param cursor
 * @return
 */
public static ECMessage packageMessage(Cursor cursor) {
    long id = cursor.getLong(cursor.getColumnIndex(IMessageColumn.ID));
    String sender = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.sender));
    String msgId = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_ID));
    // long ownThreadId =
    // cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.OWN_THREAD_ID));
    long createDate = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.CREATE_DATE));
    int version = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.VERSION));
    String userData = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.USER_DATA));
    int read = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.READ_STATUS));
    int boxType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.BOX_TYPE));
    int msgType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_TYPE));
    int sendStatus = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.SEND_STATUS));

    ECMessage ecMessage = ECMessage.createECMessage(ECMessage.Type.NONE);
    if (msgType == ECMessage.Type.TXT.ordinal() || msgType == Type.NONE.ordinal()) {
        String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
        ecMessage.setType(ECMessage.Type.TXT);
        ECTextMessageBody textBody = new ECTextMessageBody(content);
        ecMessage.setBody(textBody);
    } else if (msgType == Type.CALL.ordinal()) {
        String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
        ECCallMessageBody body = new ECCallMessageBody(content);
        ecMessage.setType(Type.CALL);
        ecMessage.setBody(body);
    } else if (msgType == ECMessage.Type.LOCATION.ordinal()) {
        String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
        ecMessage.setType(ECMessage.Type.LOCATION);

        String lon;
        String lat;
        try {
            JSONObject jsonObject = new JSONObject(content);
            lon = jsonObject.getString("lon");
            lat = jsonObject.getString("lat");
            ECLocationMessageBody textBody = new ECLocationMessageBody(Double.parseDouble(lat),
                    Double.parseDouble(lon));
            textBody.setTitle(jsonObject.getString("title"));
            ecMessage.setBody(textBody);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    else {
        String fileUrl = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.FILE_URL));
        String fileLocalPath = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.FILE_PATH));

        if (msgType == ECMessage.Type.VOICE.ordinal()) {
            ecMessage.setType(ECMessage.Type.VOICE);
            int duration = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.DURATION));
            ECVoiceMessageBody voiceBody = new ECVoiceMessageBody(new File(fileLocalPath), 0);
            voiceBody.setRemoteUrl(fileUrl);
            ecMessage.setBody(voiceBody);
            voiceBody.setDuration(duration);
        } else if (msgType == ECMessage.Type.IMAGE.ordinal() || msgType == ECMessage.Type.VIDEO.ordinal()
                || msgType == ECMessage.Type.FILE.ordinal()) {
            ECFileMessageBody fileBody = new ECFileMessageBody();
            if (msgType == ECMessage.Type.FILE.ordinal()) {
                ecMessage.setType(ECMessage.Type.FILE);
            } else if (msgType == ECMessage.Type.IMAGE.ordinal()) {
                fileBody = new ECImageMessageBody();
                ecMessage.setType(ECMessage.Type.IMAGE);
            } else {
                fileBody = new ECVideoMessageBody();
                ecMessage.setType(ECMessage.Type.VIDEO);
            }
            fileBody.setLocalUrl(fileLocalPath);
            fileBody.setRemoteUrl(fileUrl);
            fileBody.setFileName(DemoUtils.getFileNameFormUserdata(userData));
            ecMessage.setBody(fileBody);
        } else if (msgType == Type.RICH_TEXT.ordinal()) {
            {
                ECPreviewMessageBody body = new ECPreviewMessageBody();
                ecMessage.setType(Type.RICH_TEXT);
                String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
                body.setTitle(content);
                body.setLocalUrl(cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.FILE_PATH)));
                body.setUrl(cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.FILE_URL)));
                ecMessage.setBody(body);
            }
            //            return null;
        }
    }
    ecMessage.setId(id);
    ecMessage.setFrom(sender);
    ecMessage.setMsgId(msgId);
    ecMessage.setMsgTime(createDate);
    ecMessage.setUserData(userData);
    if (sendStatus == ECMessage.MessageStatus.SENDING.ordinal()) {
        ecMessage.setMsgStatus(ECMessage.MessageStatus.SENDING);
    } else if (sendStatus == ECMessage.MessageStatus.RECEIVE.ordinal() || sendStatus == 4) {
        // sendStatus == 4 ?
        ecMessage.setMsgStatus(ECMessage.MessageStatus.RECEIVE);
    } else if (sendStatus == ECMessage.MessageStatus.SUCCESS.ordinal()) {
        ecMessage.setMsgStatus(ECMessage.MessageStatus.SUCCESS);
    } else if (sendStatus == ECMessage.MessageStatus.FAILED.ordinal()) {
        ecMessage.setMsgStatus(ECMessage.MessageStatus.FAILED);
    }
    ecMessage.setDirection(getMessageDirect(boxType));

    return ecMessage;
}