Example usage for android.database Cursor getLong

List of usage examples for android.database Cursor getLong

Introduction

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

Prototype

long getLong(int columnIndex);

Source Link

Document

Returns the value of the requested column as a long.

Usage

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Test that query for the next card in the schedule returns a valid result WITH a deck selector
 */// ww w . j  ava  2s .c  om
public void testQueryCardFromCertainDeck() {
    long deckToTest = mTestDeckIds[0];
    String deckSelector = "deckID=?";
    String deckArguments[] = { Long.toString(deckToTest) };
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    Sched sched = col.getSched();
    long selectedDeckBeforeTest = col.getDecks().selected();
    col.getDecks().select(1); //select Default deck

    Cursor reviewInfoCursor = getContext().getContentResolver().query(FlashCardsContract.ReviewInfo.CONTENT_URI,
            null, deckSelector, deckArguments, null);
    assertNotNull(reviewInfoCursor);
    assertEquals("Check that we actually received one card", 1, reviewInfoCursor.getCount());
    try {
        reviewInfoCursor.moveToFirst();
        int cardOrd = reviewInfoCursor
                .getInt(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.CARD_ORD));
        long noteID = reviewInfoCursor
                .getLong(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.NOTE_ID));
        assertEquals("Check that the selected deck has not changed", 1, col.getDecks().selected());

        col.getDecks().select(deckToTest);
        Card nextCard = null;
        for (int i = 0; i < 10; i++) {//minimizing fails, when sched.reset() randomly chooses between multiple cards
            sched.reset();
            nextCard = sched.getCard();
            if (nextCard.note().getId() == noteID && nextCard.getOrd() == cardOrd)
                break;
        }
        assertNotNull("Check that there actually is a next scheduled card", nextCard);
        assertEquals("Check that received card and actual card have same note id", nextCard.note().getId(),
                noteID);
        assertEquals("Check that received card and actual card have same card ord", nextCard.getOrd(), cardOrd);
    } finally {
        reviewInfoCursor.close();
    }

    col.getDecks().select(selectedDeckBeforeTest);
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

public static long getLocalKey(String tableName, String remoteKey) {
    Cursor c = db.query(tableName, new String[] { "_id" }, "remote_key = ?", new String[] { remoteKey }, null,
            null, null, null);/*from  w w  w.  j  a va 2 s  .com*/
    if (c.moveToFirst()) {
        long l = c.getLong(0);
        c.close();
        return l;
    } else {
        c.close();
        if (tableName.equals(DatabaseHelper.CATEGORY_TABLE)) {
            return -2;
        } else {
            return KEY_CREATE;
        }
    }
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java

/**
 * Cursor to channellist.//from   w  w w .java  2 s. c  om
 *
 * @param position the position
 * @return the array list
 * @author RayBa
 * @date 07.04.2013
 */
private ArrayList<Channel> cursorToChannellist(int position) {
    Cursor c = (Cursor) mAdapter.getItem(position);
    ArrayList<Channel> chans = new ArrayList<Channel>();
    c.moveToPosition(-1);
    while (c.moveToNext()) {
        Channel channel = new Channel();
        channel.setId(c.getLong(c.getColumnIndex(ChannelTbl._ID)));
        channel.setEpgID(c.getLong(c.getColumnIndex(ChannelTbl.EPG_ID)));
        channel.setLogoUrl(c.getString(c.getColumnIndex(ChannelTbl.LOGO_URL)));
        String name = c.getString(c.getColumnIndex(ChannelTbl.NAME));
        channel.setName(name);
        channel.setPosition(c.getInt(c.getColumnIndex(ChannelTbl.POSITION)));
        chans.add(channel);
    }
    return chans;
}

From source file:com.cttapp.bby.mytlc.layer8apps.CalendarHandler.java

private ArrayList<Shift> checkForDuplicates(ArrayList<Shift> newShifts) {
    Preferences pf = new Preferences(this);
    ArrayList<String> oldShifts = pf.getSavedShifts();

    ContentResolver cr = getContentResolver();

    for (String id : oldShifts) {
        Cursor cursor = cr.query(getEventsUri(), new String[] { "dtstart", "dtend" },
                "CALENDAR_ID = " + calID + " AND _ID = " + id, null, null);

        if (!cursor.moveToFirst()) {
            continue;
        }//  ww  w  .  j  ava 2s . c  om

        do {
            Calendar now = Calendar.getInstance();

            Calendar startTime = Calendar.getInstance();
            startTime.setTimeInMillis(cursor.getLong(0));

            Calendar endTime = Calendar.getInstance();
            endTime.setTimeInMillis(cursor.getLong(1));

            if (endTime.compareTo(now) == -1) {
                deleteShift(id);
                continue;
            }

            boolean shiftFound = false;

            for (Shift shift : newShifts) {
                if (shift.getStartDate().get(Calendar.HOUR_OF_DAY) == startTime.get(Calendar.HOUR_OF_DAY)
                        && shift.getEndDate().get(Calendar.MINUTE) == shift.getEndDate().get(Calendar.MINUTE)) {
                    newShifts.remove(shift);
                    shiftFound = true;
                    break;
                }
            }

            if (!shiftFound) {
                cr.delete(getEventsUri(), "CALENDAR_ID = " + calID + " AND _ID = " + String.valueOf(id), null);
            }
        } while (cursor.moveToNext());
    }
    return newShifts;
}

From source file:com.android.browser.BookmarksPageCallbacks.java

private void editBookmark(BrowserBookmarksAdapter adapter, int position) {
    Intent intent = new Intent(getActivity(), AddBookmarkPage.class);
    Cursor cursor = adapter.getItem(position);
    Bundle item = new Bundle();
    item.putString(BrowserContract.Bookmarks.TITLE, cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE));
    item.putString(BrowserContract.Bookmarks.URL, cursor.getString(BookmarksLoader.COLUMN_INDEX_URL));
    byte[] data = cursor.getBlob(BookmarksLoader.COLUMN_INDEX_FAVICON);
    if (data != null) {
        item.putParcelable(BrowserContract.Bookmarks.FAVICON,
                BitmapFactory.decodeByteArray(data, 0, data.length));
    }/*from  ww w  .  j av  a 2  s  . c om*/
    item.putLong(BrowserContract.Bookmarks._ID, cursor.getLong(BookmarksLoader.COLUMN_INDEX_ID));
    item.putLong(BrowserContract.Bookmarks.PARENT, cursor.getLong(BookmarksLoader.COLUMN_INDEX_PARENT));
    intent.putExtra(AddBookmarkPage.EXTRA_EDIT_BOOKMARK, item);
    intent.putExtra(AddBookmarkPage.EXTRA_IS_FOLDER,
            cursor.getInt(BookmarksLoader.COLUMN_INDEX_IS_FOLDER) == 1);
    startActivity(intent);
}

From source file:com.android.contacts.common.model.ContactLoader.java

/**
 * Extracts Contact level columns from the cursor.
 *//*from   www .j  a  va  2 s .  co  m*/
private Contact loadContactHeaderData(final Cursor cursor, Uri contactUri) {
    final String directoryParameter = contactUri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY);
    final long directoryId = directoryParameter == null ? Directory.DEFAULT
            : Long.parseLong(directoryParameter);
    final long contactId = cursor.getLong(ContactQuery.CONTACT_ID);
    final String lookupKey = cursor.getString(ContactQuery.LOOKUP_KEY);
    final long nameRawContactId = cursor.getLong(ContactQuery.NAME_RAW_CONTACT_ID);
    final int displayNameSource = cursor.getInt(ContactQuery.DISPLAY_NAME_SOURCE);
    final String displayName = cursor.getString(ContactQuery.DISPLAY_NAME);
    final String altDisplayName = cursor.getString(ContactQuery.ALT_DISPLAY_NAME);
    final String phoneticName = cursor.getString(ContactQuery.PHONETIC_NAME);
    final long photoId = cursor.getLong(ContactQuery.PHOTO_ID);
    final String photoUri = cursor.getString(ContactQuery.PHOTO_URI);
    final boolean starred = cursor.getInt(ContactQuery.STARRED) != 0;
    final Integer presence = cursor.isNull(ContactQuery.CONTACT_PRESENCE) ? null
            : cursor.getInt(ContactQuery.CONTACT_PRESENCE);
    final boolean sendToVoicemail = cursor.getInt(ContactQuery.SEND_TO_VOICEMAIL) == 1;
    final String customRingtone = cursor.getString(ContactQuery.CUSTOM_RINGTONE);
    final boolean isUserProfile = cursor.getInt(ContactQuery.IS_USER_PROFILE) == 1;

    Uri lookupUri;
    if (directoryId == Directory.DEFAULT || directoryId == Directory.LOCAL_INVISIBLE) {
        lookupUri = ContentUris.withAppendedId(Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey),
                contactId);
    } else {
        lookupUri = contactUri;
    }

    return new Contact(mRequestedUri, contactUri, lookupUri, directoryId, lookupKey, contactId,
            nameRawContactId, displayNameSource, photoId, photoUri, displayName, altDisplayName, phoneticName,
            starred, presence, sendToVoicemail, customRingtone, isUserProfile);
}

From source file:edu.nd.darts.cimon.MonitorReport.java

/**
 * Generate monitor report and store on SD card.
 * //from  ww w. ja v a  2s.com
 * @return true if file successfully created
 */
private boolean createFile() {

    if (DebugLog.DEBUG)
        Log.d(TAG, "MonitorReport - createFile:" + monitorId + " metric:" + metricId);
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        if (DebugLog.WARNING)
            Log.w(TAG, "MonitorReport.createFile - external storage not available");
        return false;
    }
    File file = new File(context.getExternalFilesDir(null), "monitor" + monitorId + ".csv");
    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new FileWriter(file));

        if (metadata) {
            writer.write("sep=\t");
            writer.newLine();
            Uri metricUri = Uri.withAppendedPath(CimonContentProvider.METRICS_URI, String.valueOf(metricId));
            Cursor metricCursor = context.getContentResolver().query(metricUri, null, null, null, null);
            if (metricCursor == null) {
                if (DebugLog.WARNING)
                    Log.w(TAG, "MonitorReport.createFile - metric cursor is empty");
            } else {
                int nameCol = metricCursor.getColumnIndex(MetricsTable.COLUMN_METRIC);
                int unitsCol = metricCursor.getColumnIndex(MetricsTable.COLUMN_UNITS);
                if (metricCursor.moveToFirst()) {
                    if (nameCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - metric name column not found");
                    } else {
                        metricName = metricCursor.getString(nameCol);
                    }
                    writer.write("Metric: " + metricName);
                    writer.newLine();

                    if (unitsCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - metric name column not found");
                    } else {
                        String units = metricCursor.getString(unitsCol);
                        writer.write("Units: " + units);
                        writer.newLine();
                    }
                } else {
                    if (DebugLog.WARNING)
                        Log.w(TAG, "MonitorReport.createFile - metric cursor empty");
                }
            }
            metricCursor.close();

            Uri monitorUri = Uri.withAppendedPath(CimonContentProvider.MONITOR_URI, String.valueOf(monitorId));
            Cursor monitorCursor = context.getContentResolver().query(monitorUri, null, null, null, null);
            if (monitorCursor == null) {
                if (DebugLog.WARNING)
                    Log.w(TAG, "MonitorReport.createFile - monitor cursor is empty");
            } else {
                int offsetCol = monitorCursor.getColumnIndex(MonitorTable.COLUMN_TIME_OFFSET);
                if (monitorCursor.moveToFirst()) {
                    if (offsetCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - epoch offset column not found");
                    } else {
                        long offset = monitorCursor.getLong(offsetCol);
                        writer.write("Offset from epoch (milliseconds): " + offset);
                        writer.newLine();
                    }
                } else {
                    if (DebugLog.WARNING)
                        Log.w(TAG, "MonitorReport.createFile - monitor cursor empty");
                }
            }
            monitorCursor.close();

            writer.newLine();
        }
        writer.write("Timestamp\tValue");
        writer.newLine();

        String[] projection = { DataTable.COLUMN_TIMESTAMP, DataTable.COLUMN_VALUE };
        Uri monitorUri = Uri.withAppendedPath(CimonContentProvider.MONITOR_DATA_URI, String.valueOf(monitorId));
        Cursor mCursor = context.getContentResolver().query(monitorUri, projection, null, null, null);
        if (mCursor == null) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - data cursor is empty");
            writer.close();
            return false;
        }
        int timestampCol = mCursor.getColumnIndex(DataTable.COLUMN_TIMESTAMP);
        if (timestampCol < 0) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - timestamp column not found");
            mCursor.close();
            writer.close();
            return false;
        }
        int valueCol = mCursor.getColumnIndex(DataTable.COLUMN_VALUE);
        if (valueCol < 0) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - value column not found");
            mCursor.close();
            writer.close();
            return false;
        }
        long timestamp;
        float value;
        if (mCursor.moveToFirst()) {
            while (!mCursor.isAfterLast()) {
                timestamp = mCursor.getLong(timestampCol);
                value = mCursor.getFloat(valueCol);
                writer.write(timestamp + "\t" + value);
                writer.newLine();
                mCursor.moveToNext();
            }
        }
        mCursor.close();

        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (DebugLog.WARNING)
            Log.w(TAG, "MonitorReport.createFile - file writer failed");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.google.zxing.client.android.history.HistoryManager.java

/**
 * <p>/*from   w w  w .j  a  va2 s.  com*/
 * Builds a text representation of the scanning history. Each scan is
 * encoded on one line, terminated by a line break (\r\n). The values in
 * each line are comma-separated, and double-quoted. Double-quotes within
 * values are escaped with a sequence of two double-quotes. The fields
 * output are:
 * </p>
 * 
 * <ul>
 * <li>Raw text</li>
 * <li>Display text</li>
 * <li>Format (e.g. QR_CODE)</li>
 * <li>Timestamp</li>
 * <li>Formatted version of timestamp</li>
 * </ul>
 */
CharSequence buildHistory() {
    SQLiteOpenHelper helper = new DBHelper(activity);
    SQLiteDatabase db = null;
    Cursor cursor = null;
    try {
        db = helper.getWritableDatabase();
        cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null,
                DBHelper.TIMESTAMP_COL + " DESC");

        StringBuilder historyText = new StringBuilder(1000);
        while (cursor.moveToNext()) {

            historyText.append('"').append(massageHistoryField(cursor.getString(0))).append("\",");
            historyText.append('"').append(massageHistoryField(cursor.getString(1))).append("\",");
            historyText.append('"').append(massageHistoryField(cursor.getString(2))).append("\",");
            historyText.append('"').append(massageHistoryField(cursor.getString(3))).append("\",");

            // Add timestamp again, formatted
            long timestamp = cursor.getLong(3);
            historyText.append('"')
                    .append(massageHistoryField(EXPORT_DATE_TIME_FORMAT.format(new Date(timestamp))))
                    .append("\",");

            // Above we're preserving the old ordering of columns which had
            // formatted data in position 5

            historyText.append('"').append(massageHistoryField(cursor.getString(4))).append("\"\r\n");
        }
        return historyText;
    } finally {
        close(cursor, db);
    }
}

From source file:com.wiret.arbrowser.AbstractArchitectCamActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == KmlFileBrowserActivity.FILE_SELECT_CODE) {
        if (resultCode == RESULT_OK) {
            try {
                String filename = "";
                Uri uri = data.getData();

                if (false) {
                    Toast.makeText(this,
                            "The selected file is too large. Selet a new file with size less than 2mb",
                            Toast.LENGTH_LONG).show();
                } else {
                    String mimeType = getContentResolver().getType(uri);
                    if (mimeType == null) {
                        String path = getPath(this, uri);
                        if (path == null) {
                            filename = FilenameUtils.getName(uri.toString());
                        } else {
                            File file = new File(path);
                            filename = file.getName();
                        }/*from   w  ww .  j a va  2s. c  om*/
                    } else {
                        Uri returnUri = data.getData();
                        Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
                        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                        returnCursor.moveToFirst();
                        filename = returnCursor.getString(nameIndex);
                        String size = Long.toString(returnCursor.getLong(sizeIndex));
                    }
                    String sourcePath = getExternalFilesDir(null).toString();
                    try {
                        File outputPath = new File(sourcePath + "/" + filename);
                        copyFileStream(outputPath, uri, this);
                        importData(outputPath.getAbsolutePath());

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.hhunj.hhudata.ForegroundService.java

private String updatedb(List<SearchBookContentsResult> items) {

    String sMessage = "";
    ContentResolver resolver = getApplicationContext().getContentResolver();

    ContentValues values = new ContentValues();

    for (int i = 0; i < items.size(); i++) {

        SearchBookContentsResult res = items.get(i);
        if (res == null)
            continue;
        long stationid = Long.parseLong(res.getPageNumber());

        values.put(NotePad.Notes.TITLE, res.getName());
        values.put(NotePad.Notes.NOTE, "");

        values.put(NotePad.Notes.LONGITUTE, 108.0);
        values.put(NotePad.Notes.LATITUDE, 32.0);
        values.put(NotePad.Notes.SPEED, 55);
        values.put(NotePad.Notes.ALTITUDE, 55);

        values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime());

        values.put(NotePad.Notes._ID, stationid);// id

        Uri urlNote = NotePad.Notes.CONTENT_URI;

        Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid);

        //?????//from www.  j a  va2 s. com
        Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null);
        if (cur == null) {
            // 
        }
        if (cur != null && cur.moveToFirst()) {
            long id = cur.getLong(NotePad.Notes._ID_COLUMN);
            Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE)));
            boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true;

            long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000);

            // 
            dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000);
            boolean newalarm = false;//
            if (dif > m_alamspan) {
                // ...
                if (oldalarm == false) {
                    Log.w(TAG, "over time err--------");
                    // String phoneNumber ="13338620269";
                    sMessage += "---" + id + "---";
                    newalarm = true;
                } else {
                    newalarm = true;
                }

            }

            values.put(NotePad.Notes.ALARM, newalarm);
            int count = resolver.update(myUri, values, null, null);
            if (count == 0) {

            }

        } else {
            values.put(NotePad.Notes.ALARM, false);
            try {
                myUri = resolver.insert(urlNote, values);
            } catch (IllegalArgumentException e) {
                throw e;
            } catch (SQLException e2) {
                int aa = 0;
                throw e2;
            }
        }
    }
    return sMessage;
}