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.mythtv.service.dvr.v27.RecordingRuleHelperV27.java

private void processRecordingRule(final Context context, final LocationProfile locationProfile,
        ArrayList<ContentProviderOperation> ops, org.mythtv.services.api.v027.beans.RecRule recRule) {
    Log.d(TAG, "processRecordingRule : enter");

    String recRuleSelection = RecordingRuleConstants.FIELD_REC_RULE_ID + " = ?";

    recRuleSelection = appendLocationHostname(context, locationProfile, recRuleSelection,
            RecordingRuleConstants.TABLE_NAME);

    ContentValues recRuleValues = convertRecRuleToContentValues(locationProfile, recRule);
    Cursor recRuleCursor = context.getContentResolver().query(RecordingRuleConstants.CONTENT_URI,
            recRuleProjection, recRuleSelection, new String[] { String.valueOf(recRule.getId()) }, null);
    if (recRuleCursor.moveToFirst()) {
        Long id = recRuleCursor.getLong(recRuleCursor.getColumnIndexOrThrow(RecordingRuleConstants._ID));
        Log.v(TAG, "processRecordingRule : updating recRule " + id + ":" + recRule.getId() + ":"
                + recRule.getTitle());/*from  w w  w . ja v a2s  .c  o  m*/

        ops.add(ContentProviderOperation
                .newUpdate(ContentUris.withAppendedId(RecordingRuleConstants.CONTENT_URI, id))
                .withValues(recRuleValues).build());

    } else {
        Log.v(TAG, "processRecordingRule : adding recRule " + recRule.getId() + ":" + recRule.getTitle());

        ops.add(ContentProviderOperation.newInsert(RecordingRuleConstants.CONTENT_URI).withValues(recRuleValues)
                .build());

    }
    recRuleCursor.close();

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

From source file:gov.wa.wsdot.android.wsdot.service.BorderWaitSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";

    /** //from w  w w  .j  a v a2  s .  co  m
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "border_wait" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min");
            shouldUpdate = (Math.abs(now - lastUpdated) > (15 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();

        try {
            URL url = new URL(BORDER_WAIT_URL);
            URLConnection urlConn = url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String jsonFile = "";
            String line;

            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("waittimes");
            JSONArray items = result.getJSONArray("items");
            List<ContentValues> times = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                ContentValues timesValues = new ContentValues();
                timesValues.put(BorderWait.BORDER_WAIT_ID, item.getInt("id"));
                timesValues.put(BorderWait.BORDER_WAIT_TITLE, item.getString("name"));
                timesValues.put(BorderWait.BORDER_WAIT_UPDATED, item.getString("updated"));
                timesValues.put(BorderWait.BORDER_WAIT_LANE, item.getString("lane"));
                timesValues.put(BorderWait.BORDER_WAIT_ROUTE, item.getInt("route"));
                timesValues.put(BorderWait.BORDER_WAIT_DIRECTION, item.getString("direction"));
                timesValues.put(BorderWait.BORDER_WAIT_TIME, item.getInt("wait"));

                if (starred.contains(item.getInt("id"))) {
                    timesValues.put(BorderWait.BORDER_WAIT_IS_STARRED, 1);
                }

                times.add(timesValues);

            }

            // Purge existing border wait times covered by incoming data
            resolver.delete(BorderWait.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(BorderWait.CONTENT_URI, times.toArray(new ContentValues[times.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?",
                    new String[] { "border_wait" });

            responseString = "OK";

        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.BORDER_WAIT_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);

}

From source file:org.mythtv.service.dvr.v27.RecordedHelperV27.java

private void processProgramGroups(final Context context, final LocationProfile locationProfile,
        Program[] programs) throws RemoteException, OperationApplicationException {
    Log.v(TAG, "processProgramGroups : enter");

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

    Map<String, ProgramGroup> programGroups = new TreeMap<String, ProgramGroup>();
    for (Program program : programs) {

        if (null != program.getRecording()) {

            if (null != program.getRecording().getRecGroup()
                    && !"livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                    && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
                String cleaned = ArticleCleaner.clean(program.getTitle());
                if (!programGroups.containsKey(cleaned)) {

                    ProgramGroup programGroup = new ProgramGroup();
                    programGroup.setTitle(program.getTitle());
                    programGroup.setCategory(program.getCategory());
                    programGroup.setInetref(program.getInetref());
                    programGroup.setSort(0);

                    programGroups.put(cleaned, programGroup);
                }/*  w w  w. java2s  . c o m*/

            }

        }

    }

    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    Log.v(TAG, "processProgramGroups : adding 'All' program group in programGroups");
    ProgramGroup all = new ProgramGroup(null, "All", "All", "All", "", 1);
    programGroups.put(all.getProgramGroup(), all);

    String[] programGroupProjection = new String[] { ProgramGroupConstants._ID };
    String programGroupSelection = ProgramGroupConstants.FIELD_PROGRAM_GROUP + " = ?";

    programGroupSelection = appendLocationHostname(context, locationProfile, programGroupSelection, null);

    for (String key : programGroups.keySet()) {
        Log.v(TAG, "processProgramGroups : processing programGroup '" + key + "'");

        ProgramGroup programGroup = programGroups.get(key);

        ContentValues programValues = convertProgramGroupToContentValues(locationProfile, programGroup);
        Cursor programGroupCursor = context.getContentResolver().query(ProgramGroupConstants.CONTENT_URI,
                programGroupProjection, programGroupSelection, new String[] { key }, null);
        if (programGroupCursor.moveToFirst()) {

            Long id = programGroupCursor
                    .getLong(programGroupCursor.getColumnIndexOrThrow(ProgramGroupConstants._ID));
            ops.add(ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(ProgramGroupConstants.CONTENT_URI, id))
                    .withValues(programValues).withYieldAllowed(true).build());

        } else {

            ops.add(ContentProviderOperation.newInsert(ProgramGroupConstants.CONTENT_URI)
                    .withValues(programValues).withYieldAllowed(true).build());
        }
        programGroupCursor.close();
        count++;

        if (count > 100) {
            Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);
        }

    }

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : remove deleted program groups");
    ops = new ArrayList<ContentProviderOperation>();

    DateTime lastModified = new DateTime();
    lastModified = lastModified.minusHours(1);

    String deleteProgramGroupSelection = ProgramGroupConstants.FIELD_LAST_MODIFIED_DATE + " < ?";
    String[] deleteProgramGroupArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deleteProgramGroupSelection = appendLocationHostname(context, locationProfile, deleteProgramGroupSelection,
            ProgramGroupConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(ProgramGroupConstants.CONTENT_URI)
            .withSelection(deleteProgramGroupSelection, deleteProgramGroupArgs).withYieldAllowed(true).build());

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : exit");
}

From source file:com.android.emailcommon.provider.EmailContent.java

static public <T extends EmailContent> T getContent(final Context context, final Cursor cursor,
        final Class<T> klass) {
    try {// w  w  w .  j  av  a  2 s  . c  om
        T content = klass.newInstance();
        content.mId = cursor.getLong(0);
        content.restore(context, cursor);
        return content;
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.android.contacts.list.ContactEntryListAdapter.java

protected void bindQuickContact(final ContactListItemView view, int partitionIndex, Cursor cursor,
        int photoIdColumn, int contactIdColumn, int lookUpKeyColumn) {
    long photoId = 0;
    if (!cursor.isNull(photoIdColumn)) {
        photoId = cursor.getLong(photoIdColumn);
    }/*from  w  w w.  j av  a  2 s.co m*/

    //Begin by gangzhou.qi at 2012-7-11 ?10:53:05

    accountType = null;
    accountSet = null;
    accountIconDraw = null;
    accountQuerySelectionArgs = new String[] { cursor.getString(0) };
    Cursor accountCur = null;
    accountCur = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, null, accountQuerySelection,
            accountQuerySelectionArgs, null);
    if (accountCur != null && accountCur.getCount() > 0) {
        try {
            accountCur.moveToFirst();
            accountType = accountCur
                    .getString(accountCur.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
            accountSet = accountCur.getString(accountCur.getColumnIndex(ContactsContract.RawContacts.DATA_SET));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            accountCur.close();
        }
    }

    if (accountType != null) {
        accountIconDraw = AccountTypeManager.getInstance(mContext)
                .getAccountType(AccountTypeWithDataSet.get(accountType, accountSet)).getDisplayIcon(mContext);
    }
    Log.d(TAG, "accountIconDraw:" + accountIconDraw);
    QuickContactBadgeWithAccount quickContact = view.getQuickContact();

    //if(accountIconDraw != null){
    quickContact.setAccountDrawable(accountIconDraw);
    //}
    //Ended by gangzhou.qi at 2012-7-11 ?10:53:05

    quickContact.assignContactUri(getContactUri(partitionIndex, cursor, contactIdColumn, lookUpKeyColumn));
    getPhotoLoader().loadPhoto(quickContact, photoId, false, mDarkTheme);
}

From source file:com.ryansmertz.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//w  w  w  .  j  a  v  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;

    //Check if lcoatoin with this city name is 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 {
        ContentValues locationValues = new ContentValues();
        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);

        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        locationId = ContentUris.parseId(insertedUri);
    }

    return locationId;
}

From source file:org.mythtv.service.dvr.v26.RecordedHelperV26.java

private int load(final Context context, final LocationProfile locationProfile, final Program[] programs)
        throws RemoteException, OperationApplicationException {
    Log.d(TAG, "load : enter");

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

    processProgramGroups(context, locationProfile, programs);

    String tag = UUID.randomUUID().toString();
    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    boolean inError;

    List<Integer> channelsChecked = new ArrayList<Integer>();

    for (Program program : programs) {

        if (null != program.getRecording() && "livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
            Log.w(TAG,/*w w  w .  j a v a 2 s .co m*/
                    "load : program has no recording or program is in livetv or deleted recording groups:"
                            + program.getTitle() + ":" + program.getSubTitle() + ":"
                            + program.getChannel().getChanId() + ":" + program.getStartTime() + ":"
                            + program.getHostName() + " ("
                            + (null == program.getRecording() ? "No Recording"
                                    : ("livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                                            ? "LiveTv"
                                            : "Deleted"))
                            + ")");

            continue;
        }

        if (null == program.getStartTime() || null == program.getEndTime()) {
            Log.w(TAG, "load : null starttime and or endtime");

            inError = true;
        } else {
            inError = false;
        }

        ProgramHelperV26.getInstance().processProgram(context, locationProfile,
                ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED, ops, program, tag);
        count++;

        if (null != program.getChannel()) {

            if (!channelsChecked.contains(program.getChannel().getChanId())) {

                if (null == mChannelDaoHelper.findByChannelId(context, locationProfile,
                        Long.parseLong(String.valueOf(program.getChannel().getChanId())))) {

                    ChannelHelperV26.getInstance().processChannel(context, locationProfile, ops,
                            program.getChannel());
                    count++;

                }

                channelsChecked.add(program.getChannel().getChanId());

            }

        }

        if (!inError && null != program.getRecording()) {

            if (program.getRecording().getRecordId() > 0) {

                RecordingHelperV26.getInstance().processRecording(context, locationProfile, ops,
                        RecordingConstants.ContentDetails.RECORDED, program, tag);
                count++;

            }

        }

        if (count > BATCH_COUNT_LIMIT) {
            Log.i(TAG, "load : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);

            count = 0;

        }

    }

    if (!ops.isEmpty()) {
        Log.i(TAG, "load : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    ProgramHelperV26.getInstance().findAllPrograms(context, locationProfile,
            ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED);

    Log.v(TAG, "load : remove deleted recording live streams");
    String[] deletedProjection = new String[] { ProgramConstants.FIELD_CHANNEL_ID,
            ProgramConstants.FIELD_START_TIME, ProgramConstants.FIELD_TITLE, ProgramConstants.FIELD_SUB_TITLE,
            ProgramConstants.FIELD_LAST_MODIFIED_DATE };
    String deletedSelection = "not " + ProgramConstants.TABLE_NAME_RECORDED + "."
            + ProgramConstants.FIELD_LAST_MODIFIED_TAG + " = ?";
    String[] deletedSelectionArgs = new String[] { tag };

    deletedSelection = appendLocationHostname(context, locationProfile, deletedSelection,
            ProgramConstants.TABLE_NAME_RECORDED);

    int deleteCount = 0;
    Cursor deletedCursor = context.getContentResolver().query(ProgramConstants.CONTENT_URI_RECORDED,
            deletedProjection, deletedSelection, deletedSelectionArgs, null);
    while (deletedCursor.moveToNext()) {

        long channelId = deletedCursor.getLong(deletedCursor.getColumnIndex(ProgramConstants.FIELD_CHANNEL_ID));
        long startTime = deletedCursor.getLong(deletedCursor.getColumnIndex(ProgramConstants.FIELD_START_TIME));

        // Delete any live stream details
        String liveStreamSelection = LiveStreamConstants.FIELD_CHAN_ID + " = ? AND "
                + LiveStreamConstants.FIELD_START_TIME + " = ?";
        String[] liveStreamSelectionArgs = new String[] { String.valueOf(channelId),
                String.valueOf(startTime) };

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

        Cursor liveStreamCursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, null,
                liveStreamSelection, liveStreamSelectionArgs, null);
        if (liveStreamCursor.moveToFirst()) {
            Log.v(TAG, "load : remove live stream");

            int liveStreamId = liveStreamCursor.getInt(liveStreamCursor
                    .getColumnIndex(LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants.FIELD_ID));

            RemoveStreamTask removeStreamTask = new RemoveStreamTask(context, locationProfile);
            removeStreamTask.execute(liveStreamId);
        }
        liveStreamCursor.close();

        deleteCount++;
    }
    deletedCursor.close();
    Log.v(TAG, "load : queued deleted programs - " + deleteCount);

    ProgramHelperV26.getInstance().deletePrograms(context, locationProfile,
            ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED, tag);
    //      RecordingHelperV26.getInstance().deleteRecordings( context, locationProfile, ops, RecordingConstants.ContentDetails.RECORDED, lastModified );

    if (!ops.isEmpty()) {
        Log.i(TAG, "load : applying delete batch for transactions");

        processBatch(context, ops, processed, count);
    }

    //      Log.v( TAG, "load : exit" );
    return processed;
}

From source file:com.tigerbase.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//from   w w w . ja  v  a 2 s .  com
 * @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
    Log.v(LOG_TAG, "addLocation");
    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);
    long locationId = 0;
    if (locationCursor.moveToFirst()) {
        Log.v(LOG_TAG, "addLocation: Found location");
        int idColumnIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(idColumnIndex);
    }
    locationCursor.close();
    if (locationId > 0) {
        Log.v(LOG_TAG, "addLocation: Return Location " + locationId);
        return locationId;
    }

    ContentValues newLocationValues = new ContentValues();
    newLocationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
    newLocationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
    newLocationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
    newLocationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

    Uri newLocationUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
            newLocationValues);

    locationId = ContentUris.parseId(newLocationUri);

    Log.v(LOG_TAG, "addLocation: Created location " + locationId);
    return locationId;
}

From source file:org.mythtv.service.dvr.v25.RecordedHelperV25.java

private int load(final Context context, final LocationProfile locationProfile, final Program[] programs)
        throws RemoteException, OperationApplicationException {
    Log.d(TAG, "load : enter");

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

    processProgramGroups(context, locationProfile, programs);

    String tag = UUID.randomUUID().toString();
    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    boolean inError;

    List<Integer> channelsChecked = new ArrayList<Integer>();

    for (Program program : programs) {

        if (null != program.getRecording() && "livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
            Log.w(TAG,//w  w w.  ja  va2s .  co  m
                    "load : program has no recording or program is in livetv or deleted recording groups:"
                            + program.getTitle() + ":" + program.getSubTitle() + ":"
                            + program.getChannel().getChanId() + ":" + program.getStartTime() + ":"
                            + program.getHostName() + " ("
                            + (null == program.getRecording() ? "No Recording"
                                    : ("livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                                            ? "LiveTv"
                                            : "Deleted"))
                            + ")");

            continue;
        }

        if (null == program.getStartTime() || null == program.getEndTime()) {
            Log.w(TAG, "load : null starttime and or endtime");

            inError = true;
        } else {
            inError = false;
        }

        ProgramHelperV25.getInstance().processProgram(context, locationProfile,
                ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED, ops, program, tag);
        count++;

        if (null != program.getChannel()) {

            if (!channelsChecked.contains(program.getChannel().getChanId())) {

                if (null == mChannelDaoHelper.findByChannelId(context, locationProfile,
                        Long.parseLong(String.valueOf(program.getChannel().getChanId())))) {

                    ChannelHelperV25.getInstance().processChannel(context, locationProfile, ops,
                            program.getChannel());
                    count++;

                }

                channelsChecked.add(program.getChannel().getChanId());

            }

        }

        if (!inError && null != program.getRecording()) {

            if (program.getRecording().getRecordId() > 0) {

                RecordingHelperV25.getInstance().processRecording(context, locationProfile, ops,
                        RecordingConstants.ContentDetails.RECORDED, program, tag);
                count++;

            }

        }

        if (count > BATCH_COUNT_LIMIT) {
            Log.i(TAG, "load : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);

            count = 0;

        }

    }

    if (!ops.isEmpty()) {
        Log.i(TAG, "load : applying final batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    ProgramHelperV25.getInstance().findAllPrograms(context, locationProfile,
            ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED);

    Log.v(TAG, "load : remove deleted recording live streams");
    String[] deletedProjection = new String[] { ProgramConstants.FIELD_CHANNEL_ID,
            ProgramConstants.FIELD_START_TIME, ProgramConstants.FIELD_TITLE, ProgramConstants.FIELD_SUB_TITLE,
            ProgramConstants.FIELD_LAST_MODIFIED_DATE };
    String deletedSelection = "not " + ProgramConstants.TABLE_NAME_RECORDED + "."
            + ProgramConstants.FIELD_LAST_MODIFIED_TAG + " = ?";
    String[] deletedSelectionArgs = new String[] { tag };

    deletedSelection = appendLocationHostname(context, locationProfile, deletedSelection,
            ProgramConstants.TABLE_NAME_RECORDED);

    int deleteCount = 0;
    Cursor deletedCursor = context.getContentResolver().query(ProgramConstants.CONTENT_URI_RECORDED,
            deletedProjection, deletedSelection, deletedSelectionArgs, null);
    while (deletedCursor.moveToNext()) {

        long channelId = deletedCursor.getLong(deletedCursor.getColumnIndex(ProgramConstants.FIELD_CHANNEL_ID));
        long startTime = deletedCursor.getLong(deletedCursor.getColumnIndex(ProgramConstants.FIELD_START_TIME));

        // Delete any live stream details
        String liveStreamSelection = LiveStreamConstants.FIELD_CHAN_ID + " = ? AND "
                + LiveStreamConstants.FIELD_START_TIME + " = ?";
        String[] liveStreamSelectionArgs = new String[] { String.valueOf(channelId),
                String.valueOf(startTime) };

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

        Cursor liveStreamCursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, null,
                liveStreamSelection, liveStreamSelectionArgs, null);
        if (liveStreamCursor.moveToFirst()) {
            Log.v(TAG, "load : remove live stream");

            int liveStreamId = liveStreamCursor.getInt(liveStreamCursor
                    .getColumnIndex(LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants.FIELD_ID));

            RemoveStreamTask removeStreamTask = new RemoveStreamTask(context, locationProfile);
            removeStreamTask.execute(liveStreamId);
        }
        liveStreamCursor.close();

        deleteCount++;
    }
    deletedCursor.close();
    Log.v(TAG, "load : queued deleted programs - " + deleteCount);

    ProgramHelperV25.getInstance().deletePrograms(context, locationProfile,
            ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED, tag);
    //      RecordingHelperV25.getInstance().deleteRecordings( context, locationProfile, ops, RecordingConstants.ContentDetails.RECORDED, lastModified );

    if (!ops.isEmpty()) {
        Log.i(TAG, "load : applying delete batch for transactions");

        processBatch(context, ops, processed, count);
    }

    //      Log.v( TAG, "load : exit" );
    return processed;
}

From source file:com.amirhashemei.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//w ww . j  a v  a2s . com
 * @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
    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 locationIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIndex);
    } else {
        ContentValues locationValues = new ContentValues();

        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);

        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();
    // Otherwise, insert it using the content resolver and the base URI
    return locationId;
}