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.andrew.apollo.utils.MusicUtils.java

/**
 * @param cursor The {@link Cursor} used to perform our query.
 * @return The song list for a MIME type.
 *///from   w w  w .jav  a2 s. c om
public static long[] getSongListForCursor(Cursor cursor) {
    if (cursor == null) {
        return sEmptyList;
    }
    final int len = cursor.getCount();
    final long[] list = new long[len];
    cursor.moveToFirst();
    int columnIndex;
    try {
        columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
    } catch (final IllegalArgumentException notaplaylist) {
        columnIndex = cursor.getColumnIndexOrThrow(BaseColumns._ID);
    }
    for (int i = 0; i < len; i++) {
        list[i] = cursor.getLong(columnIndex);
        cursor.moveToNext();
    }
    cursor.close();
    return list;
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

private Pair<List<String>, List<String>> _changes() {
    Map<String, Pair<String, Long>> cache = new HashMap<String, Pair<String, Long>>();
    Map<String, Boolean> used = new HashMap<String, Boolean>();
    Cursor cur = null;
    try {/*  w  w  w . j  a v  a 2s  .c om*/
        cur = mMediaDb.getDatabase().query("media", new String[] { "fname", "csum", "mod" }, null, null, null,
                null, null);
        while (cur.moveToNext()) {
            cache.put(cur.getString(0), new Pair<String, Long>(cur.getString(1), cur.getLong(1)));
            used.put(cur.getString(0), false);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (cur != null) {
            cur.close();
        }
    }

    List<String> added = new ArrayList<String>();
    List<String> removed = new ArrayList<String>();

    File mediaDir = new File(getDir());
    for (File f : mediaDir.listFiles()) {
        // ignore folders and thumbs.db
        if (f.isDirectory()) {
            continue;
        }
        String fname = f.getName();
        if (fname.compareTo("thumbs.db") == 0) {
            continue;
        }
        // and files with invalid chars
        boolean bad = false;
        for (String c : new String[] { "\0", "/", "\\", ":" }) {
            if (fname.contains(c)) {
                bad = true;
                break;
            }
        }
        if (bad) {
            continue;
        }
        // empty files are invalid; clean them up and continue
        if (f.length() == 0) {
            f.delete();
            continue;
        }
        // newly added?
        if (!cache.containsKey(fname)) {
            added.add(fname);
        } else {
            // modified since last time?
            if ((f.lastModified() / 1000) != cache.get(fname).second) {
                // and has different checksum?
                if (_checksum(f.getAbsolutePath()).compareTo(cache.get(fname).first) != 0) {
                    added.add(fname);
                }
            }
            // mark as used
            used.put(fname, true);
        }
    }

    // look for any entries in the cache that no longer exist on disk
    for (String fname : used.keySet()) {
        if (!used.get(fname)) {
            removed.add(fname);
        }
    }
    return new Pair<List<String>, List<String>>(added, removed);
}

From source file:org.mythtv.service.content.v25.LiveStreamHelperV25.java

private boolean save(final Context context, final LocationProfile locationProfile,
        LiveStreamInfo liveStreamInfo, int channelId, DateTime startTime) {
    Log.d(TAG, "save : enter");

    if (null == context)
        throw new RuntimeException("LiveStreamHelperV25 is not initialized");

    DateTime lastModified = new DateTime(DateTimeZone.UTC);

    boolean saved = false;

    ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStreamInfo, lastModified,
            channelId, startTime);//from ww w .  j a va 2  s  .c om

    String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID };
    String selection = LiveStreamConstants.FIELD_ID + " = ?";
    String[] selectionArgs = new String[] { String.valueOf(liveStreamInfo.getId()) };

    selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME);

    Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection, selection,
            selectionArgs, null);
    if (cursor.moveToFirst()) {
        Log.v(TAG, "save : updating existing liveStream info");
        long id = cursor.getLong(
                cursor.getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID));

        int updated = context.getContentResolver()
                .update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id), values, null, null);
        if (updated == 1) {
            saved = true;
        }
    } else {
        Log.v(TAG, "save : inserting new liveStream info");
        Uri url = context.getContentResolver().insert(LiveStreamConstants.CONTENT_URI, values);
        if (ContentUris.parseId(url) > 0) {
            saved = true;
        }
    }
    cursor.close();

    Log.d(TAG, "save : exit");
    return saved;
}

From source file:org.mythtv.service.content.v26.LiveStreamHelperV26.java

private boolean save(final Context context, final LocationProfile locationProfile,
        LiveStreamInfo liveStreamInfo, int channelId, DateTime startTime) {
    Log.d(TAG, "save : enter");

    if (null == context)
        throw new RuntimeException("LiveStreamHelperV26 is not initialized");

    DateTime lastModified = new DateTime(DateTimeZone.UTC);

    boolean saved = false;

    ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStreamInfo, lastModified,
            channelId, startTime);//from   w  ww  .ja  va  2 s .  co m

    String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID };
    String selection = LiveStreamConstants.FIELD_ID + " = ?";
    String[] selectionArgs = new String[] { String.valueOf(liveStreamInfo.getId()) };

    selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME);

    Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection, selection,
            selectionArgs, null);
    if (cursor.moveToFirst()) {
        Log.v(TAG, "save : updating existing liveStream info");
        long id = cursor.getLong(
                cursor.getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID));

        int updated = context.getContentResolver()
                .update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id), values, null, null);
        if (updated == 1) {
            saved = true;
        }
    } else {
        Log.v(TAG, "save : inserting new liveStream info");
        Uri url = context.getContentResolver().insert(LiveStreamConstants.CONTENT_URI, values);
        if (ContentUris.parseId(url) > 0) {
            saved = true;
        }
    }
    cursor.close();

    Log.d(TAG, "save : exit");
    return saved;
}

From source file:org.mythtv.service.content.v27.LiveStreamHelperV27.java

private boolean save(final Context context, final LocationProfile locationProfile,
        LiveStreamInfo liveStreamInfo, int channelId, DateTime startTime) {
    Log.d(TAG, "save : enter");

    if (null == context)
        throw new RuntimeException("LiveStreamHelperV27 is not initialized");

    DateTime lastModified = new DateTime(DateTimeZone.UTC);

    boolean saved = false;

    ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStreamInfo, lastModified,
            channelId, startTime);//from w  w  w . j a v a 2s  . c  o m

    String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID };
    String selection = LiveStreamConstants.FIELD_ID + " = ?";
    String[] selectionArgs = new String[] { String.valueOf(liveStreamInfo.getId()) };

    selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME);

    Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection, selection,
            selectionArgs, null);
    if (cursor.moveToFirst()) {
        Log.v(TAG, "save : updating existing liveStream info");
        long id = cursor.getLong(
                cursor.getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID));

        int updated = context.getContentResolver()
                .update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id), values, null, null);
        if (updated == 1) {
            saved = true;
        }
    } else {
        Log.v(TAG, "save : inserting new liveStream info");
        Uri url = context.getContentResolver().insert(LiveStreamConstants.CONTENT_URI, values);
        if (ContentUris.parseId(url) > 0) {
            saved = true;
        }
    }
    cursor.close();

    Log.d(TAG, "save : exit");
    return saved;
}

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

/**
 * Cursor to timer./*w ww.j  av  a2  s.  com*/
 *
 * @param c the c
 * @return the timer
 * @author RayBa
 * @date 07.04.2013
 */
private Timer cursorToTimer(Cursor c) {
    String name = c.getString(c.getColumnIndex(ChannelTbl.NAME));
    long channelID = c.getLong(c.getColumnIndex(ChannelTbl._ID));
    String epgTitle = !c.isNull(c.getColumnIndex(EpgTbl.TITLE)) ? c.getString(c.getColumnIndex(EpgTbl.TITLE))
            : name;
    long epgStart = c.getLong(c.getColumnIndex(EpgTbl.START));
    long epgEnd = c.getLong(c.getColumnIndex(EpgTbl.END));
    DVBViewerPreferences prefs = new DVBViewerPreferences(getSherlockActivity());
    int epgBefore = prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_TIME_BEFORE, 5);
    int epgAfter = prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_TIME_AFTER, 5);
    Date start = epgStart > 0 ? new Date(epgStart) : new Date();
    Date end = epgEnd > 0 ? new Date(epgEnd) : new Date(start.getTime() + (1000 * 60 * 120));
    Log.i(ChannelList.class.getSimpleName(), "start: " + start.toString());
    Log.i(ChannelList.class.getSimpleName(), "end: " + end.toString());
    start = DateUtils.addMinutes(start, 0 - epgBefore);
    end = DateUtils.addMinutes(end, epgAfter);
    Timer timer = new Timer();
    timer.setTitle(epgTitle);
    timer.setChannelId(channelID);
    timer.setChannelName(name);
    timer.setStart(start);
    timer.setEnd(end);
    timer.setTimerAction(prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_DEF_AFTER_RECORD, 0));
    return timer;
}

From source file:com.ichi2.libanki.importer.Anki2Importer.java

/** Notes */
// should note new for wizard

private void _importNotes() {
    // build guid -> (id,mod,mid) hash & map of existing note ids
    mNotes = new HashMap<String, Object[]>();
    HashMap<Long, Boolean> existing = new HashMap<Long, Boolean>();
    Cursor cursor = null;
    try {/*  w  ww.  jav a 2 s. co m*/
        // "SELECT id, guid, mod, mid FROM notes"
        cursor = mDst.getDb().getDatabase().query("notes", new String[] { "id", "guid", "mod", "mid" }, null,
                null, null, null, null);
        while (cursor.moveToNext()) {
            long id = cursor.getLong(0);
            mNotes.put(cursor.getString(1), new Object[] { id, cursor.getLong(2), cursor.getLong(3) });
            existing.put(id, true);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    // we may need to rewrite the guid if the model schemas don't match,
    // so we need to keep track of the changes for the card import stage
    mChangedGuids = new HashMap<String, String>();
    // iterate over source collection
    ArrayList<Object[]> add = new ArrayList<Object[]>();
    ArrayList<Long> dirty = new ArrayList<Long>();
    int usn = mDst.usn();
    int dupes = 0;
    try {
        // "SELECT * FROM notes"
        cursor = mSrc.getDb().getDatabase().query("notes", new String[] { "id", "guid", "mid", "mod", "usn",
                "tags", "flds", "sfld", "csum", "flags", "data" }, null, null, null, null, null);
        int total = cursor.getCount();
        boolean largeCollection = total > 100;
        int onePercent = total / 100;
        int i = 0;
        // Use transactions for media db to increase performance
        mDst.getMedia().getDb().getDatabase().beginTransaction();
        try {
            while (cursor.moveToNext()) {
                Object[] note = new Object[] { cursor.getLong(0), cursor.getString(1), cursor.getLong(2),
                        cursor.getLong(3), cursor.getInt(4), cursor.getString(5), cursor.getString(6),
                        cursor.getString(7), cursor.getLong(8), cursor.getInt(9), cursor.getString(10) };
                boolean shouldAdd = _uniquifyNote(note);
                if (shouldAdd) {
                    // ensure id is unique
                    while (existing.containsKey(note[0])) {
                        note[0] = ((Long) note[0]) + 999;
                    }
                    existing.put((Long) note[0], true);
                    // bump usn
                    note[4] = usn;
                    // update media references in case of dupes
                    note[6] = _mungeMedia((Long) note[MID], (String) note[6]);
                    add.add(note);
                    dirty.add((Long) note[0]);
                    // note we have the added guid
                    mNotes.put((String) note[GUID], new Object[] { note[0], note[3], note[MID] });
                } else {
                    dupes += 1;
                    // // update existing note - not yet tested; for post 2.0
                    // boolean newer = note[3] > mod;
                    // if (mAllowUpdate && _mid(mid) == mid && newer) {
                    // note[0] = localNid;
                    // note[4] = usn;
                    // add.add(note);
                    // dirty.add(note[0]);
                    // }
                }
                ++i;
                if (!largeCollection || i % onePercent == 0) {
                    // Calls to publishProgress are reasonably expensive due to res.getString()
                    publishProgress(true, i * 100 / total, 0, false);
                }
            }
            mDst.getMedia().getDb().getDatabase().setTransactionSuccessful();
        } finally {
            mDst.getMedia().getDb().getDatabase().endTransaction();
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    if (dupes != 0) {
        // TODO: notify about dupes
    }
    // add to col
    mDst.getDb().executeMany("INSERT OR REPLACE INTO NOTES VALUES (?,?,?,?,?,?,?,?,?,?,?)", add);
    long[] dis = Utils.arrayList2array(dirty);
    mDst.updateFieldCache(dis);
    mDst.getTags().registerNotes(dis);
}

From source file:com.borqs.browser.combo.BookmarksPageCallbacks.java

private void populateBookmarkItem(Cursor cursor, BookmarkItem item, boolean isFolder) {
    item.setName(cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE));
    if (isFolder) {
        item.setUrl(null);//from   w  w w.  j a v  a 2  s  . c o  m
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_folder_holo_dark);
        item.setFavicon(bitmap);
        new LookupBookmarkCount(this, item).execute(cursor.getLong(BookmarksLoader.COLUMN_INDEX_ID));
    } else {
        String url = cursor.getString(BookmarksLoader.COLUMN_INDEX_URL);
        item.setUrl(url);
        Bitmap bitmap = getBitmap(cursor, BookmarksLoader.COLUMN_INDEX_FAVICON);
        item.setFavicon(bitmap);
    }
}

From source file:org.mythtv.android.db.dvr.ProgramHelperV27.java

public void processProgram(final Context context, final LocationProfile locationProfile, Uri uri, String table,
        ArrayList<ContentProviderOperation> ops, Program program, String tag) {
    //      Log.d( TAG, "processProgram : enter" );

    ContentValues programValues = convertProgramToContentValues(locationProfile, program, tag);

    if (table.equals(ProgramConstants.TABLE_NAME_RECORDED) || table.equals(ProgramConstants.TABLE_NAME_UPCOMING)
            || table.equals(ProgramConstants.TABLE_NAME_GUIDE)) {

        //Log.v( TAG, "processProgram : INSERT PROGRAM : " + program.getTitle() + ":" + program.getSubTitle() + ":" + program.getChannel().getChanId() + ":" + program.getStartTime() + ":" + program.getEndTime() + ":" + program.getHostName() + ":" + table );
        ops.add(ContentProviderOperation.newInsert(uri).withValues(programValues).withYieldAllowed(true)
                .build());/*  w  ww.j  av a2 s  .  c om*/

    } else {

        String programSelection = table + "." + ProgramConstants.FIELD_CHANNEL_ID + " = ? AND " + table + "."
                + ProgramConstants.FIELD_START_TIME + " = ?";
        String[] programSelectionArgs = new String[] { String.valueOf(program.getChannel().getChanId()),
                String.valueOf(program.getStartTime().getMillis()) };

        programSelection = appendLocationHostname(context, locationProfile, programSelection, table);

        Cursor programCursor = context.getContentResolver().query(uri, programProjection, programSelection,
                programSelectionArgs, null);
        if (programCursor.moveToFirst()) {
            Log.v(TAG,
                    "processProgram : UPDATE PROGRAM : " + program.getTitle() + ":" + program.getSubTitle()
                            + ":" + program.getChannel().getChanId() + ":" + program.getStartTime() + ":"
                            + program.getEndTime() + ":" + program.getHostName() + ":" + table);

            Long id = programCursor.getLong(programCursor.getColumnIndexOrThrow(ProgramConstants._ID));
            ops.add(ContentProviderOperation.newUpdate(ContentUris.withAppendedId(uri, id))
                    .withValues(programValues).withYieldAllowed(true).build());

        } else {
            //Log.v( TAG, "processProgram : INSERT PROGRAM : " + program.getTitle() + ":" + program.getSubTitle() + ":" + program.getChannel().getChanId() + ":" + program.getStartTime() + ":" + program.getEndTime() + ":" + program.getHostName() + ":" + table );

            ops.add(ContentProviderOperation.newInsert(uri).withValues(programValues).withYieldAllowed(true)
                    .build());

        }
        programCursor.close();

    }

    //      Log.d( TAG, "processProgram : exit" );
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public MessageArrayContent getMessage(String buddyId, long messageId) {
    int index = buddyId.indexOf('@');
    if (index >= 0) {
        buddyId = buddyId.substring(0, index);
    }/*from   w w w.j a v  a 2  s. c o m*/
    MessageArrayContent mac = null;
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    String[] columns = new String[] { MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP,
            MessageHistoryContract.MessageEntry._ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID };
    String sel = MessageHistoryContract.MessageEntry._ID + "=?";
    Cursor message = db.query(buddyId, columns, sel, new String[] { String.valueOf(messageId) }, null, null,
            null);

    message.moveToFirst();
    String from = message.getString(0);
    SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES, 0);
    String me = preferences.getString(Constants.USERNAME, "");
    String type = message.getString(1);
    String content = message.getString(2);
    String url = message.getString(3);
    int progress = 0;
    String status = message.getString(4);
    long time = message.getLong(5);
    long _ID = message.getLong(6);
    long othersId = message.getLong(7);
    switch (type) {
    case (MessageHistory.TYPE_TEXT):
        mac = new TextMessage(!me.equals(from), content, time, status, _ID, othersId);
        break;
    case (MessageHistory.TYPE_IMAGE):
        try {
            JSONArray contentJSON = new JSONArray(content);
            mac = new ImageMessage(!me.equals(from), //left
                    contentJSON.getString(0), //File
                    contentJSON.getString(1), //description
                    url, //url
                    progress, //progress
                    time, //timeStamp
                    status, //status
                    _ID, //_ID
                    buddyId, //buddyID
                    othersId); //othersId
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    }
    db.close();
    return mac;
}