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:edu.stanford.mobisocial.dungbeetle.ui.fragments.AppsViewFragment.java

void showMenuForObj(int position) {
    //this first cursor is the internal one
    Cursor cursor = (Cursor) mObjects.getItem(position);
    long objId = cursor.getLong(0);

    DbObj obj = App.instance().getMusubi().objForId(objId);
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment prev = getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);//from   w  ww .  j  a v a  2 s  . co  m
    }
    ft.addToBackStack(null);

    // Create and show the dialog.
    DialogFragment newFragment = ObjMenuDialogFragment.newInstance(obj);
    newFragment.show(ft, "dialog");
}

From source file:com.geniusgithub.contact.contact.calllog.ContactInfoHelper.java

/**
 * Looks up a contact using the given URI.
 * <p>//  w  ww  .j av a 2  s .c o m
 * It returns null if an error occurs, {@link ContactInfo#EMPTY} if no matching contact is
 * found, or the {@link ContactInfo} for the given contact.
 * <p>
 * The {@link ContactInfo#formattedNumber} field is always set to {@code null} in the returned
 * value.
 */
private ContactInfo lookupContactFromUri(Uri uri) {
    final ContactInfo info;
    Cursor phonesCursor = mContext.getContentResolver().query(uri, PhoneQuery._PROJECTION, null, null, null);

    if (phonesCursor != null) {
        try {
            if (phonesCursor.moveToFirst()) {
                info = new ContactInfo();
                long contactId = phonesCursor.getLong(PhoneQuery.PERSON_ID);
                String lookupKey = phonesCursor.getString(PhoneQuery.LOOKUP_KEY);
                info.lookupKey = lookupKey;
                info.lookupUri = Contacts.getLookupUri(contactId, lookupKey);
                info.name = phonesCursor.getString(PhoneQuery.NAME);
                info.type = phonesCursor.getInt(PhoneQuery.PHONE_TYPE);
                info.label = phonesCursor.getString(PhoneQuery.LABEL);
                info.number = phonesCursor.getString(PhoneQuery.MATCHED_NUMBER);
                info.normalizedNumber = phonesCursor.getString(PhoneQuery.NORMALIZED_NUMBER);
                info.photoId = phonesCursor.getLong(PhoneQuery.PHOTO_ID);
                info.photoUri = UriUtils.parseUriOrNull(phonesCursor.getString(PhoneQuery.PHOTO_URI));
                info.formattedNumber = null;
            } else {
                info = ContactInfo.EMPTY;
            }
        } finally {
            phonesCursor.close();
        }
    } else {
        // Failed to fetch the data, ignore this request.
        info = null;
    }
    return info;
}

From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java

@Override
protected Boolean doInBackground(Long... noteid) {
    // First, send the note user asked for:
    Boolean result = true;/*from  ww  w  . j av a  2  s  . c  o m*/
    if (noteid.length != 0) {
        result = uploadOneNote(noteid[0]);
    }

    // Then, automatically try and send previously-completed notes
    // that were not sent successfully.
    Vector<Long> unsentNotes = new Vector<Long>();

    mDb.openReadOnly();
    Cursor cur = mDb.fetchUnsentNotes();
    if (cur != null && cur.getCount() > 0) {
        // pd.setMessage("Sent. You have previously unsent notes; submitting those now.");
        while (!cur.isAfterLast()) {
            unsentNotes.add(Long.valueOf(cur.getLong(0)));
            cur.moveToNext();
        }
        cur.close();
    }
    mDb.close();

    for (Long note : unsentNotes) {
        result &= uploadOneNote(note);
    }
    return result;
}

From source file:com.jll.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  ww.  ja v  a2 s .  c  o m*/
 * @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

    String selection = WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?" + " AND "
            + WeatherContract.LocationEntry.COLUMN_CITY_NAME + "= ?" + " AND "
            + WeatherContract.LocationEntry.COLUMN_COORD_LAT + "= ?" + " AND "
            + WeatherContract.LocationEntry.COLUMN_COORD_LONG + "= ?";
    String[] selectionArgs = new String[] { locationSetting, cityName, String.valueOf(lat),
            String.valueOf(lon) };

    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID }, selection, selectionArgs, null);

    long id = -1;
    if (cursor.moveToFirst()) {
        id = cursor.getLong(0);
    } else {
        ContentValues values = new ContentValues();
        values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        Uri newRow = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, values);
        id = ContentUris.parseId(newRow);
    }

    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    return id;
}

From source file:com.riasayu.gosuke.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 .  j  a  v  a 2 s.  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 locationRowId = -1;
    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);
    if (cursor.moveToFirst()) {
        locationRowId = cursor.getLong(cursor.getColumnIndex(WeatherContract.LocationEntry._ID));
    } else {
        ContentValues locationValues = new ContentValues();
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        Uri locationUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);
        locationRowId = ContentUris.parseId(locationUri);
    }
    return locationRowId;
}

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

@Override
public void restore(Cursor cursor) {
    mBaseUri = CONTENT_URI;/* w  ww.j a  v a 2  s  . c o  m*/
    mId = cursor.getLong(CONTENT_ID_COLUMN);
    mProtocol = cursor.getString(CONTENT_PROTOCOL_COLUMN);
    mAddress = cursor.getString(CONTENT_ADDRESS_COLUMN);
    mPort = cursor.getInt(CONTENT_PORT_COLUMN);
    mFlags = cursor.getInt(CONTENT_FLAGS_COLUMN);
    mLogin = cursor.getString(CONTENT_LOGIN_COLUMN);
    mPassword = cursor.getString(CONTENT_PASSWORD_COLUMN);
    mDomain = cursor.getString(CONTENT_DOMAIN_COLUMN);
    mClientCertAlias = cursor.getString(CONTENT_CLIENT_CERT_ALIAS_COLUMN);
    mCredentialKey = cursor.getLong(CONTENT_CREDENTIAL_KEY_COLUMN);
    if (mCredentialKey != -1) {
        mFlags |= FLAG_OAUTH;
    }
}

From source file:com.radioactiveyak.location_best_practices.services.PlaceCheckinService.java

/**
 * {@inheritDoc}//from   www . j av  a2 s . co m
 * Perform a checkin the specified venue. If the checkin fails, add it to the queue and
 * set an alarm to retry.
 * 
 * Query the checkin queue to see if there are pending checkins to be retried.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Retrieve the details for the checkin to perform.
    String reference = intent.getStringExtra(PlacesConstants.EXTRA_KEY_REFERENCE);
    String id = intent.getStringExtra(PlacesConstants.EXTRA_KEY_ID);
    long timeStamp = intent.getLongExtra(PlacesConstants.EXTRA_KEY_TIME_STAMP, 0);

    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = sharedPreferences.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (reference != null && !backgroundAllowed && inBackground) {
        addToQueue(timeStamp, reference, id);
        return;
    }

    // Check to see if we are connected to a data network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver
    // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen
    // for when we connect to a network and start this service to retry the checkins.
    if (!isConnected) {
        // No connection so no point triggering an alarm to retry until we're connected.
        alarmManager.cancel(retryQueuedCheckinsPendingIntent);

        // Enable the Connectivity Changed Receiver to listen for connection to a network
        // so we can commit the pending checkins.
        PackageManager pm = getPackageManager();
        ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class);
        pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        // Add this checkin to the queue.
        addToQueue(timeStamp, reference, id);
    } else {
        // Execute the checkin. If it fails, add it to the retry queue.
        if (reference != null) {
            if (!checkin(timeStamp, reference, id))
                addToQueue(timeStamp, reference, id);
        }

        // Retry the queued checkins.
        ArrayList<String> successfulCheckins = new ArrayList<String>();
        Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null,
                null, null);
        try {
            // Retry each checkin.
            while (queuedCheckins.moveToNext()) {
                long queuedTimeStamp = queuedCheckins
                        .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP));
                String queuedReference = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE));
                String queuedId = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID));
                if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId))
                    successfulCheckins.add(queuedReference);
            }

            // Delete the queued checkins that were successful.
            if (successfulCheckins.size() > 0) {
                StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='"
                        + successfulCheckins.get(0) + "'");
                for (int i = 1; i < successfulCheckins.size(); i++)
                    sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '"
                            + successfulCheckins.get(i) + "'");
                sb.append(")");
                int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI,
                        sb.toString(), null);
                Log.d(TAG, "Deleted: " + deleteCount);
            }

            // If there are still queued checkins then set a non-waking alarm to retry them.
            queuedCheckins.requery();
            if (queuedCheckins.getCount() > 0) {
                long triggerAtTime = System.currentTimeMillis() + PlacesConstants.CHECKIN_RETRY_INTERVAL;
                alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                        retryQueuedCheckinsPendingIntent);
            } else
                alarmManager.cancel(retryQueuedCheckinsPendingIntent);
        } finally {
            queuedCheckins.close();
        }
    }
}

From source file:com.android.transmart.services.PlaceCheckinService.java

/**
 * {@inheritDoc}/*from w w w . ja v  a2s  . c om*/
 * Perform a checkin the specified venue. If the checkin fails, add it to the queue and
 * set an alarm to retry.
 * 
 * Query the checkin queue to see if there are pending checkins to be retried.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Retrieve the details for the checkin to perform.
    String reference = intent.getStringExtra(LocationConstants.EXTRA_KEY_REFERENCE);
    String id = intent.getStringExtra(LocationConstants.EXTRA_KEY_ID);
    long timeStamp = intent.getLongExtra(LocationConstants.EXTRA_KEY_TIME_STAMP, 0);

    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = sharedPreferences.getBoolean(LocationConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (reference != null && !backgroundAllowed && inBackground) {
        addToQueue(timeStamp, reference, id);
        return;
    }

    // Check to see if we are connected to a data network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver
    // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen
    // for when we connect to a network and start this service to retry the checkins.
    if (!isConnected) {
        // No connection so no point triggering an alarm to retry until we're connected.
        alarmManager.cancel(retryQueuedCheckinsPendingIntent);

        // Enable the Connectivity Changed Receiver to listen for connection to a network
        // so we can commit the pending checkins.
        PackageManager pm = getPackageManager();
        ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class);
        pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        // Add this checkin to the queue.
        addToQueue(timeStamp, reference, id);
    } else {
        // Execute the checkin. If it fails, add it to the retry queue.
        if (reference != null) {
            if (!checkin(timeStamp, reference, id))
                addToQueue(timeStamp, reference, id);
        }

        // Retry the queued checkins.
        ArrayList<String> successfulCheckins = new ArrayList<String>();
        Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null,
                null, null);
        try {
            // Retry each checkin.
            while (queuedCheckins.moveToNext()) {
                long queuedTimeStamp = queuedCheckins
                        .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP));
                String queuedReference = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE));
                String queuedId = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID));
                if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId))
                    successfulCheckins.add(queuedReference);
            }

            // Delete the queued checkins that were successful.
            if (successfulCheckins.size() > 0) {
                StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='"
                        + successfulCheckins.get(0) + "'");
                for (int i = 1; i < successfulCheckins.size(); i++)
                    sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '"
                            + successfulCheckins.get(i) + "'");
                sb.append(")");
                int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI,
                        sb.toString(), null);
                Log.d(TAG, "Deleted: " + deleteCount);
            }

            // If there are still queued checkins then set a non-waking alarm to retry them.
            queuedCheckins.requery();
            if (queuedCheckins.getCount() > 0) {
                long triggerAtTime = System.currentTimeMillis() + LocationConstants.CHECKIN_RETRY_INTERVAL;
                alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                        retryQueuedCheckinsPendingIntent);
            } else
                alarmManager.cancel(retryQueuedCheckinsPendingIntent);
        } finally {
            queuedCheckins.close();
        }
    }
}

From source file:github.popeen.dsub.util.SongDBHandler.java

public synchronized Long[] getLastPlayed(int serverKey, String id) {
    SQLiteDatabase db = this.getReadableDatabase();

    String[] columns = { SONGS_LAST_PLAYED, SONGS_LAST_COMPLETED };
    Cursor cursor = db.query(TABLE_SONGS, columns, SONGS_SERVER_KEY + " = ? AND " + SONGS_SERVER_ID + " = ?",
            new String[] { Integer.toString(serverKey), id }, null, null, null, null);

    try {//ww  w  . j  av  a2 s.  c om
        cursor.moveToFirst();

        Long[] dates = new Long[2];
        dates[0] = cursor.getLong(0);
        dates[1] = cursor.getLong(1);
        return dates;
    } catch (Exception e) {
        return null;
    } finally {
        db.close();
    }
}

From source file:com.getmarco.weatherstationviewer.gcm.StationGcmListenerService.java

/**
 * Helper method to handle insertion of a station in the database if it doesn't already exist.
 *
 * @param stationTag the station//from w ww  .jav a 2s. c  o  m
 * @return the row ID of the station (new or existing)
 */
long addStation(String stationTag) {
    long stationId;

    // First, check if a station with this tag exists in the db
    Cursor stationCursor = getContentResolver().query(StationContract.StationEntry.CONTENT_URI,
            new String[] { StationContract.StationEntry._ID }, StationContract.StationEntry.COLUMN_TAG + " = ?",
            new String[] { stationTag }, null);

    if (stationCursor.moveToFirst()) {
        int stationIdIndex = stationCursor.getColumnIndex(StationContract.StationEntry._ID);
        stationId = stationCursor.getLong(stationIdIndex);
    } else {
        ContentValues locationValues = new ContentValues();
        locationValues.put(StationContract.StationEntry.COLUMN_TAG, stationTag);
        locationValues.put(StationContract.StationEntry.COLUMN_NAME, stationTag);
        locationValues.put(StationContract.StationEntry.COLUMN_TEMP_HIGH, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_TEMP_LOW, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_HUMIDITY_HIGH, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_HUMIDITY_LOW, 0.0);

        // Finally, insert location data into the database.
        Uri insertedUri = getContentResolver().insert(StationContract.StationEntry.CONTENT_URI, locationValues);

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

    stationCursor.close();
    return stationId;
}