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:at.bitfire.ical4android.AndroidEvent.java

@SuppressWarnings("Recycle")
protected void populateExceptions() throws FileNotFoundException, RemoteException {
    @Cleanup
    Cursor c = calendar.provider.query(calendar.syncAdapterURI(Events.CONTENT_URI), new String[] { Events._ID },
            Events.ORIGINAL_ID + "=?", new String[] { String.valueOf(id) }, null);
    while (c != null && c.moveToNext()) {
        long exceptionId = c.getLong(0);
        try {/*ww w . ja va2s  . c  o  m*/
            AndroidEvent exception = calendar.eventFactory.newInstance(calendar, exceptionId, null);
            event.getExceptions().add(exception.getEvent());
        } catch (CalendarStorageException e) {
            Log.e(TAG, "Couldn't find exception details, ignoring", e);
        }
    }
}

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

/**
 * Finds deleted resources (resources which have been marked for deletion).
 * Deleted resources have the "deleted" flag set.
 * Only records matching sqlFilter will be returned.
 * /*from ww  w  .  ja  va2s .co  m*/
 * @return IDs of deleted resources
 * @throws LocalStorageException when the content provider couldn't be queried
 */
public long[] findDeleted() throws LocalStorageException {
    String where = entryColumnDeleted() + "=1";
    if (entryColumnParentID() != null)
        where += " AND " + entryColumnParentID() + "=" + String.valueOf(getId());
    if (sqlFilter != null)
        where += " AND (" + sqlFilter + ")";
    try {
        @Cleanup
        Cursor cursor = providerClient.query(entriesURI(),
                new String[] { entryColumnID(), entryColumnRemoteName(), entryColumnETag() }, where, null,
                null);
        if (cursor == null)
            throw new LocalStorageException("Couldn't query dirty records");

        long deleted[] = new long[cursor.getCount()];
        for (int idx = 0; cursor.moveToNext(); idx++)
            deleted[idx] = cursor.getLong(0);
        return deleted;
    } catch (RemoteException ex) {
        throw new LocalStorageException(ex);
    }
}

From source file:app.com.example.kiran.sunshine.FetchWeatherTask.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   ww w. j a v a 2  s . co m
public 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 = mContext.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 = mContext.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:at.bitfire.davdroid.resource.LocalCollection.java

/**
 * Finds updated resources (resources which have already been uploaded, but have changed locally).
 * Updated resources are 1) dirty, and 2) already have an ETag. Only records matching sqlFilter
 * will be returned./*from  w w  w . ja  v  a2s .  com*/
 * 
 * @return IDs of updated resources
 * @throws LocalStorageException when the content provider couldn't be queried
 */
public long[] findUpdated() throws LocalStorageException {
    String where = entryColumnDirty() + "=1 AND " + entryColumnETag() + " IS NOT NULL";
    if (entryColumnParentID() != null)
        where += " AND " + entryColumnParentID() + "=" + String.valueOf(getId());
    if (sqlFilter != null)
        where += " AND (" + sqlFilter + ")";
    try {
        @Cleanup
        Cursor cursor = providerClient.query(entriesURI(),
                new String[] { entryColumnID(), entryColumnRemoteName(), entryColumnETag() }, where, null,
                null);
        if (cursor == null)
            throw new LocalStorageException("Couldn't query updated records");

        long[] updated = new long[cursor.getCount()];
        for (int idx = 0; cursor.moveToNext(); idx++)
            updated[idx] = cursor.getLong(0);
        return updated;
    } catch (RemoteException ex) {
        throw new LocalStorageException(ex);
    }
}

From source file:com.morphoss.acal.service.UpdateTimezones.java

private void refreshTimezoneData() {
    try {/* w  w  w .  jav a2s  .  c om*/
        HashMap<String, Long> currentZones = new HashMap<String, Long>();
        HashMap<String, Long> updatedZones = new HashMap<String, Long>();
        HashMap<String, Long> insertedZones = new HashMap<String, Long>();
        Cursor allZones = cr.query(Timezones.CONTENT_URI,
                new String[] { Timezones.TZID, Timezones.LAST_MODIFIED }, null, null, null);
        Long maxModified = 0L;
        for (allZones.moveToFirst(); !allZones.isAfterLast(); allZones.moveToNext()) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found existing zone of '" + allZones.getString(0)
                        + "' modified: " + AcalDateTime.fromMillis(allZones.getLong(1) * 1000L).toString());
            currentZones.put(allZones.getString(0), allZones.getLong(1));
            if (allZones.getLong(1) > maxModified)
                maxModified = allZones.getLong(1);
        }
        AcalDateTime mostRecentChange = AcalDateTime.getUTCInstance().setEpoch(maxModified);
        Log.println(Constants.LOGI, TAG, "Found " + allZones.getCount()
                + " existing timezones, most recent change on " + mostRecentChange.toString());
        if (allZones.getCount() > 350 && mostRecentChange.after(AcalDateTime.getUTCInstance().addDays(-30))) {
            Log.println(Constants.LOGI, TAG, "Skipping update - our database is pretty recent");
            return;
        }

        requestor.interpretUriString(tzUrl("list", null));
        JSONObject root = requestor.doJsonRequest("GET", null, null, null);
        if (requestor.wasRedirected()) {
            Uri tzUri = Uri.parse(requestor.fullUrl());
            String redirectedUrl = tzUri.getScheme() + "://" + tzUri.getAuthority() + tzUri.getPath();
            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Redirected to Timezone Server at " + redirectedUrl);
            tzServerBaseUrl = redirectedUrl;
            AcalApplication.setPreferenceString(PrefNames.tzServerBaseUrl, redirectedUrl);
        }
        if (requestor.getStatusCode() >= 399) {
            Log.println(Constants.LOGI, TAG, "Bad response " + requestor.getStatusCode()
                    + " from Timezone Server at " + tzUrl("list", null));
        }
        if (root == null) {
            Log.println(Constants.LOGI, TAG, "No JSON from GET " + tzUrl("list", null));
            return;
        }

        String tzid;
        String tzData = "";
        long lastModified;
        StringBuilder localNames;
        StringBuilder aliases;
        ContentValues zoneValues = new ContentValues();

        String tzDateStamp = root.getString("dtstamp");
        JSONArray tzArray = root.getJSONArray("timezones");
        for (int i = 0; i < tzArray.length(); i++) {
            JSONObject zoneNode = tzArray.getJSONObject(i);
            tzid = zoneNode.getString("tzid");
            if (updatedZones.containsKey(tzid) || insertedZones.containsKey(tzid))
                continue;

            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Working on " + tzid);

            lastModified = AcalDateTime.fromString(zoneNode.getString("last-modified")).getEpoch();
            if (currentZones.containsKey(tzid) && currentZones.get(tzid) <= lastModified) {
                currentZones.remove(tzid);
                continue;
            }

            tzData = getTimeZone(tzid);
            if (tzData == null)
                continue;

            localNames = new StringBuilder();
            try {
                JSONArray nameNodes = zoneNode.getJSONArray("local_names");
                for (int j = 0; j < nameNodes.length(); j++) {
                    if (localNames.length() > 0)
                        localNames.append("\n");
                    localNames.append(nameNodes.getJSONObject(j).getString("lang")).append('~')
                            .append(nameNodes.getJSONObject(j).getString("lname"));
                }
            } catch (JSONException je) {
            }

            aliases = new StringBuilder();
            try {
                JSONArray aliasNodes = zoneNode.getJSONArray("aliases");
                for (int j = 0; j < aliasNodes.length(); j++) {
                    if (aliases.length() > 0)
                        aliases.append("\n");
                    aliases.append(aliasNodes.getString(j));
                }
            } catch (JSONException je) {
            }

            zoneValues.put(Timezones.TZID, tzid);
            zoneValues.put(Timezones.ZONE_DATA, tzData);
            zoneValues.put(Timezones.LAST_MODIFIED, lastModified);
            zoneValues.put(Timezones.TZ_NAMES, localNames.toString());
            zoneValues.put(Timezones.TZID_ALIASES, aliases.toString());

            Uri tzUri = Uri.withAppendedPath(Timezones.CONTENT_URI,
                    "tzid/" + StaticHelpers.urlescape(tzid, false));

            if (currentZones.containsKey(tzid)) {
                if (cr.update(tzUri, zoneValues, null, null) != 1) {
                    Log.e(TAG, "Failed update for TZID '" + tzid + "'");
                }
                updatedZones.put(tzid, currentZones.get(tzid));
                currentZones.remove(tzid);
            } else {
                if (cr.insert(tzUri, zoneValues) == null)
                    Log.e(TAG, "Failed insert for TZID '" + tzid + "'");
                insertedZones.put(tzid, currentZones.get(tzid));
            }

            if (context.workWaiting()) {
                Log.println(Constants.LOGI, TAG, "Something is waiting - deferring timezone sync until later.");
                deferMe = true;
                break;
            }
            // Let other stuff have a chance
            Thread.sleep(350);
        }
        int removed = 0;

        if (currentZones.size() > 0) {
            StringBuilder s = new StringBuilder();
            for (String tz : currentZones.keySet()) {
                if (s.length() > 0)
                    s.append(',');
                s.append("'").append(tz).append("'");
            }
            removed = cr.delete(Timezones.CONTENT_URI, Timezones.TZID + " IN (" + s + ")", null);
        }

        Log.println(Constants.LOGI, TAG, "Updated data for " + updatedZones.size() + " zones, added data for "
                + insertedZones.size() + " new zones, removed data for " + removed);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:com.polyvi.xface.extension.telephony.XTelephonyExt.java

/**
 * Cursor?JSON/* w w w  .  ja  v a  2  s  . co m*/
 */
private JSONObject getCallRecordFromCursor(Cursor cursor) {
    String callRecordId = cursor.getString(cursor.getColumnIndex(CallLog.Calls._ID));
    String callRecordAddress = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
    String callRecordName = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
    int callRecordTypeInt = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
    long startTime = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
    long durationSeconds = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION));
    JSONObject callRecord = new JSONObject();
    try {
        callRecord.put("callRecordId", callRecordId);
        callRecord.put("callRecordAddress", callRecordAddress);
        callRecord.put("callRecordName", callRecordName);
        callRecord.put("callRecordType", getCallRecordTypeStr(callRecordTypeInt));
        callRecord.put("startTime", startTime);
        callRecord.put("durationSeconds", durationSeconds);
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, e.toString());
    }
    return callRecord;
}

From source file:com.example.tahmina.sunshine.app.FetchWeatherTask.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/*from   ww  w .j  av  a 2s  . c om*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    long locationId;

    // First, check if the location with this city name exists in the db
    Cursor locationCursor = mContext.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 = mContext.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.polyvi.xface.extension.XMessagingExt.java

/**
 * ?message?//from w ww .  j  a  va  2  s . c om
 */
private JSONObject getMessageFromCursor(Cursor cursor) throws JSONException {
    //??
    String msgId = cursor.getString(cursor.getColumnIndex("_id"));
    String subject = cursor.getString(cursor.getColumnIndex("subject"));
    String smsBody = cursor.getString(cursor.getColumnIndex("body"));
    long date = cursor.getLong(cursor.getColumnIndex("date"));
    boolean isRead = cursor.getInt(cursor.getColumnIndex("read")) == 0 ? false : true;
    String destAddress = cursor.getString(cursor.getColumnIndex("address"));
    JSONObject message = new JSONObject();
    message.put("messageId", msgId);
    message.put("subject", subject);
    message.put("body", smsBody);
    message.put("destinationAddresses", destAddress);
    message.put("messageType", MESSAGE_TYPE_SMS);
    message.put("date", date);
    message.put("isRead", isRead);
    return message;
}

From source file:danga.sunshine.async_task.FetchWeatherTask.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  ww .j ava 2 s . co  m*/
public long addLocation(String locationSetting, String cityName, double lat, double lon) {

    // First, check if the location with this city name exists in the db
    long locationId;
    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_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_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 = mContext.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:io.github.the_dagger.sunshine.data.FetchWeatherTask.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/* w ww .j a v  a2s  .c o  m*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
public long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    long locationId;
    Cursor locationCursor = mContext.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 {
        ContentValues contentValues = new ContentValues();
        contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        Uri insertLocationUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                contentValues);
        locationId = ContentUris.parseId(insertLocationUri);
    }
    locationCursor.close();
    return locationId;
}