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:org.dvbviewer.controller.ui.fragments.ChannelList.java

/**
 * Reads the current cursorposition to a Channel.
 *
 * @param c the c/*from   ww  w . j ava2 s .c  om*/
 * @return the Channel
 * @author RayBa
 * @date 13.05.2012
 */
private Channel cursorToChannel(Cursor c) {
    Channel channel = new Channel();
    channel.setId(c.getLong(c.getColumnIndex(ChannelTbl._ID)));
    channel.setEpgID(c.getLong(c.getColumnIndex(ChannelTbl.EPG_ID)));
    String name = c.getString(c.getColumnIndex(ChannelTbl.NAME));
    channel.setName(name);
    channel.setPosition(c.getInt(c.getColumnIndex(ChannelTbl.POSITION)));
    return channel;
}

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

public List<Long> findNotes(String query) {
    String[] tokens = _tokenize(query);
    Pair<String, String[]> res1 = _where(tokens);
    String preds = res1.first;//from   w w w .ja  va2s. c o m
    String[] args = res1.second;
    List<Long> res = new ArrayList<Long>();
    if (preds == null) {
        return res;
    }
    if (preds.equals("")) {
        preds = "1";
    } else {
        preds = "(" + preds + ")";
    }
    String sql = "select distinct(n.id) from cards c, notes n where c.nid=n.id and " + preds;
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase().rawQuery(sql, args);
        while (cur.moveToNext()) {
            res.add(cur.getLong(0));
        }
    } catch (SQLException e) {
        // invalid grouping
        return new ArrayList<Long>();
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    return res;
}

From source file:com.zegoggles.smssync.CursorToMessage.java

public ConversionResult cursorToMessages(final Cursor cursor, final int maxEntries, DataType dataType)
        throws MessagingException {
    final String[] columns = cursor.getColumnNames();
    final ConversionResult result = new ConversionResult(dataType);
    do {//from   ww w  . j a v a2  s . c o  m
        final long date = cursor.getLong(cursor.getColumnIndex(SmsConsts.DATE));
        if (date > result.maxDate) {
            result.maxDate = date;
        }
        final Map<String, String> msgMap = new HashMap<String, String>(columns.length);
        for (int i = 0; i < columns.length; i++) {
            msgMap.put(columns[i], cursor.getString(i));
        }

        Message m = null;
        switch (dataType) {
        case SMS:
            m = messageFromMapSms(msgMap);
            break;
        case MMS:
            m = messageFromMapMms(msgMap);
            break;
        case CALLLOG:
            m = messageFromMapCallLog(msgMap);
            break;
        }
        if (m != null) {
            result.messageList.add(m);
            result.mapList.add(msgMap);
        }
    } while (result.messageList.size() < maxEntries && cursor.moveToNext());

    return result;
}

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

/** Return a list of card ids for QUERY */
public List<Long> findCards(String query, String _order) {
    String[] tokens = _tokenize(query);
    Pair<String, String[]> res1 = _where(tokens);
    String preds = res1.first;//from  w ww  .  j ava 2  s.  com
    String[] args = res1.second;
    List<Long> res = new ArrayList<Long>();
    if (preds == null) {
        return res;
    }
    Pair<String, Boolean> res2 = _order(_order);
    String order = res2.first;
    boolean rev = res2.second;
    String sql = _query(preds, order, false);
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase().rawQuery(sql, args);
        while (cur.moveToNext()) {
            res.add(cur.getLong(0));
        }
    } catch (SQLException e) {
        // invalid grouping
        return new ArrayList<Long>();
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (rev) {
        Collections.reverse(res);
    }
    return res;
}

From source file:com.gvccracing.android.tttimer.Tabs.RaceInfoTab.java

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://www.gvccracing.com/?page_id=2525&pass=com.gvccracing.android.tttimer");

    try {//www  .j  av a2s  .  co m
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        InputStream is = response.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20);

        int current = 0;

        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        String text = new String(baf.toByteArray());

        JSONObject mainJson = new JSONObject(text);
        JSONArray jsonArray = mainJson.getJSONArray("members");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);

            String firstName = json.getString("fname");
            String lastName = json.getString("lname");
            String licenseStr = json.getString("license");
            Integer license = 0;
            try {
                license = Integer.parseInt(licenseStr);
            } catch (Exception ex) {
                Log.e(LOG_TAG(), "Unable to parse license string");
            }
            long age = json.getLong("age");
            String categoryStr = json.getString("category");
            Integer category = 5;
            try {
                category = Integer.parseInt(categoryStr);
            } catch (Exception ex) {
                Log.e(LOG_TAG(), "Unable to parse category string");
            }
            String phone = json.getString("phone");
            long phoneNumber = 0;
            try {
                phoneNumber = Long.parseLong(phone.replace("-", "").replace("(", "").replace(")", "")
                        .replace(" ", "").replace(".", "").replace("*", ""));
            } catch (Exception e) {
                Log.e(LOG_TAG(), "Unable to parse phone number");
            }
            String gender = json.getString("gender");
            String econtact = json.getString("econtact");
            String econtactPhone = json.getString("econtact_phone");
            long eContactPhoneNumber = 0;
            try {
                eContactPhoneNumber = Long.parseLong(econtactPhone.replace("-", "").replace("(", "")
                        .replace(")", "").replace(" ", "").replace(".", "").replace("*", ""));
            } catch (Exception e) {
                Log.e(LOG_TAG(), "Unable to parse econtact phone number");
            }
            Long member_id = json.getLong("member_id");

            String gvccCategory;
            switch (category) {
            case 1:
            case 2:
            case 3:
                gvccCategory = "A";
                break;
            case 4:
                gvccCategory = "B4";
                break;
            case 5:
                gvccCategory = "B5";
                break;
            default:
                gvccCategory = "B5";
                break;
            }

            Log.w(LOG_TAG(), lastName);
            Cursor racerInfo = Racer.Instance().Read(getActivity(),
                    new String[] { Racer._ID, Racer.FirstName, Racer.LastName, Racer.USACNumber,
                            Racer.PhoneNumber, Racer.EmergencyContactName, Racer.EmergencyContactPhoneNumber },
                    Racer.USACNumber + "=?", new String[] { license.toString() }, null);
            if (racerInfo.getCount() > 0) {
                racerInfo.moveToFirst();
                Long racerID = racerInfo.getLong(racerInfo.getColumnIndex(Racer._ID));
                Racer.Instance().Update(getActivity(), racerID, firstName, lastName, license, 0l, phoneNumber,
                        econtact, eContactPhoneNumber, gender);
                Cursor racerClubInfo = RacerClubInfo.Instance().Read(getActivity(),
                        new String[] { RacerClubInfo._ID, RacerClubInfo.GVCCID, RacerClubInfo.RacerAge,
                                RacerClubInfo.Category },
                        RacerClubInfo.Racer_ID + "=? AND " + RacerClubInfo.Year + "=? AND "
                                + RacerClubInfo.Upgraded + "=?",
                        new String[] { racerID.toString(), "2013", "0" }, null);
                if (racerClubInfo.getCount() > 0) {
                    racerClubInfo.moveToFirst();
                    long racerClubInfoID = racerClubInfo
                            .getLong(racerClubInfo.getColumnIndex(RacerClubInfo._ID));
                    String rciCategory = racerClubInfo
                            .getString(racerClubInfo.getColumnIndex(RacerClubInfo.Category));

                    boolean upgraded = gvccCategory != rciCategory;
                    if (upgraded) {
                        RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null,
                                null, null, null, null, null, upgraded);
                        RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0,
                                0, age, member_id, false);
                    } else {
                        RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null,
                                null, null, null, age, member_id, upgraded);
                    }

                } else {
                    RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0,
                            age, member_id, false);
                }
                if (racerClubInfo != null) {
                    racerClubInfo.close();
                }
            } else {
                // TODO: Better birth date
                Uri resultUri = Racer.Instance().Create(getActivity(), firstName, lastName, license, 0l,
                        phoneNumber, econtact, eContactPhoneNumber, gender);
                long racerID = Long.parseLong(resultUri.getLastPathSegment());
                RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age,
                        member_id, false);
            }
            if (racerInfo != null) {
                racerInfo.close();
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e(LOG_TAG(), e.getMessage());
    }
}

From source file:ch.ethz.twimight.net.tds.TDSRequestMessage.java

public void createDisTweetsObject(Cursor tweets) throws JSONException {

    if (tweets != null && tweets.getCount() > 0) {

        tweets.moveToFirst();/*from w w w  .j  av  a 2s.  c  om*/
        disTweetsObject = new JSONObject();
        JSONArray disTweetsArray = new JSONArray();
        CertificateManager cm = new CertificateManager(context.getApplicationContext());

        while (!tweets.isAfterLast()) {

            if (!tweets.isNull(tweets.getColumnIndex(Tweets.COL_SIGNATURE))) {
                JSONObject row = new JSONObject();
                row.put(Tweets.COL_TEXT_PLAIN, tweets.getString(tweets.getColumnIndex(Tweets.COL_TEXT_PLAIN)));
                row.put(Tweets.COL_USER_TID, tweets.getLong(tweets.getColumnIndex(Tweets.COL_USER_TID)));
                row.put(Tweets.COL_DISASTER_ID, tweets.getLong(tweets.getColumnIndex(Tweets.COL_DISASTER_ID)));
                row.put(Tweets.COL_SIGNATURE, tweets.getString(tweets.getColumnIndex(Tweets.COL_SIGNATURE)));

                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                row.put(Tweets.COL_CREATED_AT + "_phone", simpleFormat
                        .format(new Date(tweets.getLong(tweets.getColumnIndex(Tweets.COL_CREATED_AT)))));
                // add picture if available
                if (tweets.getString(tweets.getColumnIndex(Tweets.COL_MEDIA_URIS)) != null) {
                    SDCardHelper sdCardHelper = new SDCardHelper();
                    String base64Photo = sdCardHelper.getImageAsBas64Jpeg(
                            tweets.getString(tweets.getColumnIndex(Tweets.COL_MEDIA_URIS)), null);
                    Log.d(TAG, base64Photo);
                    row.put(PHOTO, base64Photo);
                }

                disTweetsArray.put(row);
            }

            tweets.moveToNext();
        }
        tweets.close();

        if (disTweetsArray.length() > 0)
            disTweetsObject.put("content", disTweetsArray);
        else
            disTweetsObject = null;

    }
}

From source file:com.hichinaschool.flashcards.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 {/*from w w w. j  a v  a2s .c o 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();
        int i = 0;
        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;
            publishProgress(true, i * 100 / total, 0, false);
        }
    } 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.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

/**
 * We know that the group exists locally, so we can use the data in the JSON group as gold
 * @param group//  w w  w  . j a  v a  2  s . c o  m
 * @param provider
 * @param authToken
 * @param account
 * @param syncResult
 * @throws JSONException
 * @throws RemoteException
 * @throws OperationApplicationException
 */
private void optimisticallyAddContactsToExistingGroup(JSONObject group, ContentProviderClient provider,
        String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException {

    if (!group.has(JSONKeys.KEY_MEMBERS)) {
        return;
    }
    String groupCloudId = group.getString(JSONKeys.KEY_ID);
    Cursor groupCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID, GMSGroup.CLOUD_ID },
            GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }, null);
    try {
        if (groupCursor == null || 1 != groupCursor.getCount() || !groupCursor.moveToFirst()) {
            syncResult.databaseError = true;
            return;
        }
        long groupId = groupCursor.getLong(0);
        if (groupId < 0L) {
            syncResult.databaseError = true;
            return;
        }
        // Optimistically add the contacts
        JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS);
        for (int j = 0; j < membersArray.length(); ++j) {
            JSONObject member = membersArray.getJSONObject(j);
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // If the first operation asserts it means the contact exists already
            // Operation 0
            ContentProviderOperation op = ContentProviderOperation.newAssertQuery(GMSContacts.CONTENT_URI)
                    .withSelection(GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) })
                    .withExpectedCount(0).build();
            ops.add(op);
            op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI)
                    .withValues(GMSApplication.getMemberValues(member)).withValue(GMSContact.GROUP_ID, groupId)
                    .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).build();
            ops.add(op);
            try {
                @SuppressWarnings("unused")
                ContentProviderResult[] results = provider.applyBatch(ops);
            } catch (OperationApplicationException e) {
                // The contact already exists, so we'll optionally update it, based on its version
                Cursor contactCursor = null;
                try {
                    contactCursor = provider.query(GMSContacts.CONTENT_URI,
                            new String[] { GMSContact._ID, GMSContact.CLOUD_ID, GMSContact.GROUP_ID },
                            GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) }, null);
                    if (contactCursor == null || !contactCursor.moveToFirst()) {
                        syncResult.databaseError = true;
                        return;
                    }
                    // The member already exists, so optinally update it
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists. If its the right version, we don't need to do the update
                    // So we assert that we'll find zero records with the current version and if that's right, we'll update our
                    // record, including the version with the new record data
                    op = ContentProviderOperation
                            .newAssertQuery(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withSelection(GMSContact.VERSION + "=?",
                                    new String[] { member.getString(JSONKeys.KEY_VERSION) })
                            .withExpectedCount(0).build();
                    ops.add(op);
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValues(GMSApplication.getMemberValues(member))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    provider.applyBatch(ops);
                } catch (OperationApplicationException l) {
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists and is of the current version, so no update of attributes is needed
                    // We still have to update the status to SYNCED so we don't blow it away later.
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    try {
                        provider.applyBatch(ops);
                    } catch (OperationApplicationException e1) {
                        syncResult.stats.numSkippedEntries++;
                        e1.printStackTrace();
                    }
                } finally {
                    if (contactCursor != null) {
                        contactCursor.close();
                    }
                }
            }
        }
    } finally {
        if (groupCursor != null) {
            groupCursor.close();
        }
    }
}

From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName        A human-readable city name, e.g "Mountain View"
 * @param lat             the latitude of the city
 * @param lon             the longitude of the city
 * @return the row ID of the added location.
 *//*from w  w w .j  a  v a  2s  . c  om*/
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    long locationId;

    // First, check if the location with this city name exists in the db
    Cursor locationCursor = getContext().getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);

    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIdIndex);
    } else {
        // Now that the content provider is set up, inserting rows of data is pretty simple.
        // First create a ContentValues object to hold the data you want to insert.
        ContentValues locationValues = new ContentValues();

        // Then add the data, along with the corresponding name of the data type,
        // so the content provider knows what kind of value is being inserted.
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Finally, insert location data into the database.
        Uri insertedUri = getContext().getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        // The resulting URI contains the ID for the row.  Extract the locationId from the Uri.
        locationId = ContentUris.parseId(insertedUri);
    }

    locationCursor.close();
    // Wait, that worked?  Yes!
    return locationId;
}

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

/**
 * Test query to decks table//  www  .ja  va  2  s .c om
 * @throws Exception
 */
public void testQueryAllDecks() throws Exception {
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    Decks decks = col.getDecks();

    Cursor decksCursor = getContext().getContentResolver().query(FlashCardsContract.Deck.CONTENT_ALL_URI,
            FlashCardsContract.Deck.DEFAULT_PROJECTION, null, null, null);

    assertNotNull(decksCursor);
    try {
        assertEquals("Check number of results", decks.count(), decksCursor.getCount());
        while (decksCursor.moveToNext()) {
            long deckID = decksCursor.getLong(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_ID));
            String deckName = decksCursor
                    .getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_NAME));

            JSONObject deck = decks.get(deckID);
            assertNotNull("Check that the deck we received actually exists", deck);
            assertEquals("Check that the received deck has the correct name", deck.getString("name"), deckName);
        }
    } finally {
        decksCursor.close();
    }
}