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:de.langerhans.wallet.ExchangeRatesProvider.java

public static ExchangeRate getExchangeRate(@Nonnull final Cursor cursor) {
    final String currencyCode = cursor
            .getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_CURRENCY_CODE));
    final Coin rateCoin = Coin
            .valueOf(cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE_COIN)));
    final Fiat rateFiat = Fiat.valueOf(currencyCode,
            cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE_FIAT)));
    final String source = cursor.getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_SOURCE));

    return new ExchangeRate(new com.dogecoin.dogecoinj.utils.ExchangeRate(rateCoin, rateFiat), source);
}

From source file:at.bitfire.davdroid.resource.LocalGroup.java

/**
 * Processes all groups with non-null {@link #COLUMN_PENDING_MEMBERS}: the pending memberships
 * are (if possible) applied, keeping cached memberships in sync.
 * @param addressBook    address book to take groups from
 * @throws ContactsStorageException on contact provider errors
 *//*from   ww  w  . ja  v  a2  s  .  c  om*/
public static void applyPendingMemberships(LocalAddressBook addressBook) throws ContactsStorageException {
    try {
        @Cleanup
        Cursor cursor = addressBook.provider.query(addressBook.syncAdapterURI(Groups.CONTENT_URI),
                new String[] { Groups._ID, COLUMN_PENDING_MEMBERS }, COLUMN_PENDING_MEMBERS + " IS NOT NULL",
                new String[] {}, null);

        BatchOperation batch = new BatchOperation(addressBook.provider);
        while (cursor != null && cursor.moveToNext()) {
            long id = cursor.getLong(0);
            Constants.log.fine("Assigning members to group " + id);

            // delete all memberships and cached memberships for this group
            batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                    .newDelete(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI))
                    .withSelection(
                            "(" + GroupMembership.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID
                                    + "=?) OR (" + CachedGroupMembership.MIMETYPE + "=? AND "
                                    + CachedGroupMembership.GROUP_ID + "=?)",
                            new String[] { GroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id),
                                    CachedGroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id) })
                    .withYieldAllowed(true)));

            // extract list of member UIDs
            List<String> members = new LinkedList<>();
            byte[] raw = cursor.getBlob(1);
            @Cleanup("recycle")
            Parcel parcel = Parcel.obtain();
            parcel.unmarshall(raw, 0, raw.length);
            parcel.setDataPosition(0);
            parcel.readStringList(members);

            // insert memberships
            for (String uid : members) {
                Constants.log.fine("Assigning member: " + uid);
                try {
                    LocalContact member = addressBook.findContactByUID(uid);
                    member.addToGroup(batch, id);
                } catch (FileNotFoundException e) {
                    Constants.log.log(Level.WARNING, "Group member not found: " + uid, e);
                }
            }

            // remove pending memberships
            batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                    .newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, id)))
                    .withValue(COLUMN_PENDING_MEMBERS, null).withYieldAllowed(true)));

            batch.commit();
        }
    } catch (RemoteException e) {
        throw new ContactsStorageException("Couldn't get pending memberships", e);
    }
}

From source file:Main.java

/**
 * Return the data stored in the cursor at the given index and given position
 * (ie the given row which the cursor is currently on) as null OR a String.
 * <p>//from ww w.  j  a v a  2  s  .c  o m
 * NB: Currently only checks for Strings, long, int, and double.
 *
 * @param c
 * @param i
 * @return
 */
@SuppressLint("NewApi")
public static String getIndexAsString(Cursor c, int i) {
    // If you add additional return types here be sure to modify the javadoc.
    if (i == -1)
        return null;
    if (c.isNull(i)) {
        return null;
    }
    switch (c.getType(i)) {
    case Cursor.FIELD_TYPE_STRING:
        return c.getString(i);
    case Cursor.FIELD_TYPE_FLOAT: {
        // the static version of this seems to have problems...
        Double d = c.getDouble(i);
        String v = d.toString();
        return v;
    }
    case Cursor.FIELD_TYPE_INTEGER: {
        // the static version of this seems to have problems...
        Long l = c.getLong(i);
        String v = l.toString();
        return v;
    }
    case Cursor.FIELD_TYPE_NULL:
        return c.getString(i);
    default:
    case Cursor.FIELD_TYPE_BLOB:
        throw new IllegalStateException("Unexpected data type in SQLite table");
    }
}

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

public static Date geLastUpdate(Context context, PublicScript script, String trollId) {

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Cursor cursor = database.rawQuery(SQL_LAST_UPDATE,
            new String[] { trollId, script.name(), MhDlaSQLHelper.STATUS_SUCCESS });
    Date result = null;//from  w  w w  .  j ava2  s .co m
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        long resultTimestamp = cursor.getLong(0);
        result = new Date(resultTimestamp);
    }

    cursor.close();
    database.close();

    String format = "Last update for category %s (script=%s) and troll=%s is: '%s'";
    String message = String.format(format, script.category, script, trollId, result);
    Log.d(TAG, message);

    return result;
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

private static long getCalendar(Account account) {
    // Find the Last.fm calendar if we've got one
    Uri calenderUri = Calendars.CONTENT_URI.buildUpon()
            .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name)
            .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type).build();
    Cursor c1 = mContentResolver.query(calenderUri, new String[] { BaseColumns._ID }, null, null, null);
    if (c1.moveToNext()) {
        long ret = c1.getLong(0);
        c1.close();//  w  ww.ja va2 s  . co m
        return ret;
    } else {
        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();

        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Calendars.CONTENT_URI
                .buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name)
                .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type).build());
        builder.withValue(Calendars.ACCOUNT_NAME, account.name);
        builder.withValue(Calendars.ACCOUNT_TYPE, account.type);
        builder.withValue(Calendars.NAME, "Pizza Hut Shifts");
        builder.withValue(Calendars.CALENDAR_DISPLAY_NAME, "Pizza Hut Shifts");
        builder.withValue(Calendars.CALENDAR_COLOR, 0xD51007);
        builder.withValue(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);
        builder.withValue(Calendars.OWNER_ACCOUNT, account.name);
        builder.withValue(Calendars.SYNC_EVENTS, 1);
        operationList.add(builder.build());
        try {
            mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return -1;
        }
        c1.close();
        return getCalendar(account);
    }
}

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

public static Map<PublicScript, Date> geLastUpdates(Context context, String trollId,
        Set<PublicScript> scripts) {

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Map<PublicScript, Date> result = new HashMap<PublicScript, Date>();

    for (PublicScript script : scripts) {

        Cursor cursor = database.rawQuery(SQL_LAST_UPDATE,
                new String[] { trollId, script.name(), MhDlaSQLHelper.STATUS_SUCCESS });
        Date lastUpdate = null;/*from   w w w. ja  v a 2  s .c  om*/
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            long resultTimestamp = cursor.getLong(0);
            lastUpdate = new Date(resultTimestamp);
        }

        result.put(script, lastUpdate);
        cursor.close();
    }
    database.close();

    String format = "Last updates for troll=%s are: '%s'";
    String message = String.format(format, trollId, result);
    Log.i(TAG, message);

    return result;
}

From source file:Main.java

public static Uri getAllCallLogs(ContentResolver cr, Uri internal, Context context, String timeStamp) {
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm");
    String[] callLogArray = new String[3];
    String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
    Uri callUri = Uri.parse("content://call_log/calls");
    Cursor cur = cr.query(callUri, null, null, null, strOrder);

    FileOutputStream fOut = null;
    try {/*from  ww w  .ja va  2 s  . co  m*/
        fOut = context.openFileOutput("call_logs_" + timeStamp + ".txt", Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    OutputStreamWriter osw = new OutputStreamWriter(fOut);

    while (cur.moveToNext()) {
        callLogArray[0] = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
        callLogArray[1] = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));

        int thirdIndex = cur.getColumnIndex(android.provider.CallLog.Calls.DATE);
        long seconds = cur.getLong(thirdIndex);
        String dateString = formatter.format(new Date(seconds));
        callLogArray[2] = dateString;

        writeToOutputStreamArray(callLogArray, osw);
    }

    try {
        osw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return internal;
}

From source file:free.yhc.netmbuddy.share.Json.java

static JSONObject playlistToJson(long plid) {
    final int COLI_ID = 0;
    Cursor c = DB.get().queryVideos(plid, new ColVideo[] { ColVideo.ID }, null, false);
    if (!c.moveToFirst()) {
        c.close();/*from   ww  w .  j  av a2  s  . c o m*/
        return null;
    }

    JSONObject jo = new JSONObject();
    try {
        jo.put(FTITLE, DB.get().getPlaylistInfo(plid, ColPlaylist.TITLE));
        String thumbnailYtvid = (String) DB.get().getPlaylistInfo(plid, ColPlaylist.THUMBNAIL_YTVID);
        if (Utils.isValidValue(thumbnailYtvid))
            jo.put(FTHUMBNAIL_YTVID, thumbnailYtvid);

        JSONArray jarr = new JSONArray();
        do {
            JSONObject jov = videoToJson(c.getLong(COLI_ID));
            eAssert(null != jov);
            jarr.put(jov);
        } while (c.moveToNext());
        jo.put(FVIDEOS, jarr);
    } catch (JSONException e) {
        jo = null;
    }
    c.close();

    return jo;
}

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

/**
 * @param v the view to bind/*www.j  a v  a2 s  . c  om*/
 * @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.rsegismont.androlife.core.utils.AndrolifeUtils.java

public static long getTonightIndex(Cursor mCursor) {
    if (mCursor == null)
        return -1;

    if (mCursor.getCount() <= 0)
        return -1;

    long dateUtc = -1;

    final int initialPosition = mCursor.getPosition();

    mCursor.moveToPosition(0);//w ww. j ava2  s  . c om

    final long initialValue = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));

    final Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(initialValue);
    calendar.set(Calendar.HOUR_OF_DAY, 19);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    for (int i = 0; i < mCursor.getCount(); i++) {
        mCursor.moveToPosition(i);
        final long value = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));

        if (calendar.getTime().getTime() - value < 0) {

            mCursor.moveToPosition(Math.max(0, i - 1));
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }
        if ((i == 0) && (calendar.getTime().getTime() - value < 0)) {

            mCursor.moveToPosition(0);
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }

        if (i == (mCursor.getCount() - 1)) {

            mCursor.moveToPosition(Math.max(0, mCursor.getCount() - 1));
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }
    }

    if (initialPosition >= 0)
        mCursor.moveToPosition(initialPosition);

    return dateUtc;
}