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:com.nnm.smsviet.Message.java

/**
 * Default constructor.//ww w .j  ava 2 s.c o  m
 * 
 * @param context
 *            {@link Context} to spawn the {@link SmileyParser}.
 * @param cursor
 *            {@link Cursor} to read the data
 */
private Message(final Context context, final Cursor cursor) {
    this.id = cursor.getLong(INDEX_ID);
    this.threadId = cursor.getLong(INDEX_THREADID);
    this.date = cursor.getLong(INDEX_DATE);
    if (this.date < ConversationListActivity.MIN_DATE) {
        this.date *= ConversationListActivity.MILLIS;
    }
    if (cursor.getColumnIndex(PROJECTION_JOIN[INDEX_TYPE]) >= 0) {
        this.address = cursor.getString(INDEX_ADDRESS);
        this.body = cursor.getString(INDEX_BODY);
        if (ConversationListActivity.showEmoticons && this.body != null) {
            this.body = SmileyParser.getInstance(context).addSmileySpans(this.body);
        }
    } else {
        this.body = null;
        this.address = null;
    }
    this.type = cursor.getInt(INDEX_TYPE);
    this.read = cursor.getInt(INDEX_READ);
    if (this.body == null) {
        this.isMms = true;
        try {
            this.fetchMmsParts(context);
        } catch (OutOfMemoryError e) {
            Log.e(TAG, "error loading parts", e);
            try {
                Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
            } catch (Exception e1) {
                Log.e(TAG, "error creating Toast", e1);
            }
        }
    } else {
        this.isMms = false;
    }
    try {
        this.subject = cursor.getString(INDEX_SUBJECT);
    } catch (IllegalStateException e) {
        this.subject = null;
    }
    try {
        if (cursor.getColumnCount() > INDEX_MTYPE) {
            final int t = cursor.getInt(INDEX_MTYPE);
            if (t != 0) {
                this.type = t;
            }
        }
    } catch (IllegalStateException e) {
        this.subject = null;
    }

    Log.d(TAG, "threadId: " + this.threadId);
    Log.d(TAG, "address: " + this.address);
    // Log.d(TAG, "subject: " + this.subject);
    // Log.d(TAG, "body: " + this.body);
    // Log.d(TAG, "type: " + this.type);
}

From source file:com.swisscom.android.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/*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.
 */
private long addLocation(String locationSetting, String cityName, double lat, double lon) {

    Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

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

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        return cursor.getLong(locationIdIndex);
    } else {
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");
        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTINGS, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_LATITUDE, lat);
        locationValues.put(LocationEntry.COLUMN_LONGITUDE, lon);

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

        return ContentUris.parseId(locationInsertUri);
    }
}

From source file:com.photon.phresco.nativeapp.eshop.activity.CategoryListActivity.java

/**
 * Update the Category VersionNo in local database, if already exists
 *
 * @param appConf//from w  ww . j  av a2s  .c  o  m
 * @param searchCategoryVersionRow
 * @throws IllegalArgumentException
 * @throws NumberFormatException
 */
private void updateCategoryVersionNoInLocalDatabase(AppConfiguration appConf, Cursor searchCategoryVersionRow) {
    try {
        searchCategoryVersionRow.moveToFirst();

        // Get the row id of current categoryVersionNo from SQLite db
        long currentRowId = searchCategoryVersionRow
                .getLong(searchCategoryVersionRow.getColumnIndexOrThrow(AppConfiguration.KEY_ROWID));

        // Get the current categoryVersionNo from SQLite db
        String categoryVersionNo = searchCategoryVersionRow
                .getString(searchCategoryVersionRow.getColumnIndex(AppConfiguration.KEY_META_VALUE));

        PhrescoLogger.info(TAG + " - Existing CategoryVersion = " + categoryVersionNo + " in local database");
        PhrescoLogger.info(TAG + " - appConfigJSONObj.appVersionInfo.configVersionn = "
                + getAppConfigJSONObj().getAppVersionInfo().getConfigVersion());

        if (Integer.parseInt(getAppConfigJSONObj().getAppVersionInfo().getConfigVersion()) != Integer
                .parseInt(categoryVersionNo)) {
            Utility.deleteDir(new File(Constants.CATEGORIES_FOLDER_PATH));
            Utility.createDirectory(new File(Constants.CATEGORIES_FOLDER_PATH));
            downloadCategoryImages();
            appConf.updateRow(currentRowId, "category_version",
                    String.valueOf(getAppConfigJSONObj().getAppVersionInfo().getConfigVersion()));
            PhrescoLogger.info(TAG + " - UPDATE CategoryVersion = "
                    + getAppConfigJSONObj().getAppVersionInfo().getConfigVersion() + " in local database");
        }
        searchCategoryVersionRow.close();
    } catch (Exception ex) {
        PhrescoLogger.info(TAG + "updateCategoryVersionNoInLocalDatabase - Exception : " + ex.toString());
        PhrescoLogger.warning(ex);
    }
}

From source file:com.android.email.provider.EmailMessageCursor.java

public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn,
        final String textColumn) {
    super(cursor);
    mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn);
    mTextColumnIndex = cursor.getColumnIndex(textColumn);
    final int cursorSize = cursor.getCount();
    mHtmlParts = new SparseArray<String>(cursorSize);
    mTextParts = new SparseArray<String>(cursorSize);

    final ContentResolver cr = c.getContentResolver();

    while (cursor.moveToNext()) {
        final int position = cursor.getPosition();
        final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        try {//w  w w  . ja  v  a  2 s  . c om
            if (mHtmlColumnIndex != -1) {
                final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId);
                final InputStream in = cr.openInputStream(htmlUri);
                final String underlyingHtmlString;
                try {
                    underlyingHtmlString = IOUtils.toString(in);
                } finally {
                    in.close();
                }
                final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString);
                mHtmlParts.put(position, sanitizedHtml);
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId);
        }
        try {
            if (mTextColumnIndex != -1) {
                final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId);
                final InputStream in = cr.openInputStream(textUri);
                final String underlyingTextString;
                try {
                    underlyingTextString = IOUtils.toString(in);
                } finally {
                    in.close();
                }
                mTextParts.put(position, underlyingTextString);
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId);
        }
    }
    cursor.moveToPosition(-1);
}

From source file:edu.gatech.ppl.cycleatlanta.TripUploader.java

@Override
protected Boolean doInBackground(Long... tripid) {
    // First, send the trip user asked for:
    Boolean result = true;// ww  w  .ja  v  a2  s .  c  o m
    if (tripid.length != 0) {
        result = uploadOneTrip(tripid[0]);
    }

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

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

    for (Long trip : unsentTrips) {
        result &= uploadOneTrip(trip);
    }
    return result;
}

From source file:ac.robinson.mediaphone.provider.NarrativeAdapter.java

public void bindView(View view, Context context, Cursor cursor) {
    NarrativeViewHolder holder = (NarrativeViewHolder) view.getTag();

    // only load column indices once
    if (mInternalIdIndex < 0) {
        mInternalIdIndex = cursor.getColumnIndexOrThrow(NarrativeItem.INTERNAL_ID);
        mCreationDateIndex = cursor.getColumnIndexOrThrow(NarrativeItem.DATE_CREATED);
        mSequenceIdIndex = cursor.getColumnIndexOrThrow(NarrativeItem.SEQUENCE_ID);
    }//from  ww w  .j  a  v  a2s.c o m

    holder.narrativeInternalId = cursor.getString(mInternalIdIndex);
    holder.narrativeDateCreated = cursor.getLong(mCreationDateIndex);
    holder.narrativeSequenceId = cursor.getInt(mSequenceIdIndex);

    final BrowserActivity activity = mActivity;
    if (activity.getScrollState() == AbsListView.OnScrollListener.SCROLL_STATE_FLING
            || activity.isPendingIconsUpdate()) {
        holder.queryIcons = true;
        holder.frameList.setAdapter(mEmptyAdapter);
    } else {
        attachAdapter(holder);
        holder.queryIcons = false;
    }

    // alternating row colours
    int cursorPosition = cursor.getPosition();
    if ((cursor.getCount() - cursorPosition) % 2 == 0) { // so the colour stays the same when adding a new narrative
        holder.frameList.setBackgroundResource(
                mIsTemplateView ? R.color.template_list_dark : R.color.narrative_list_dark);
    } else {
        holder.frameList.setBackgroundResource(
                mIsTemplateView ? R.color.template_list_light : R.color.narrative_list_light);
    }
}

From source file:com.josenaves.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  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.
 */
private long addLocation(String locationSetting, String cityName, double lat, double lon) {

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

    if (cursor.moveToFirst()) {
        int locationIdIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        return cursor.getLong(locationIdIndex);
    } 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_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

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

        return ContentUris.parseId(locationInsertUri);
    }
}

From source file:me.vancexu.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//  ww  w  .  ja  v  a  2 s .  c  o m
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
private long addLocation(String locationSetting, String cityName, double lat, double lon) {

    long rowId;

    Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

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

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        rowId = cursor.getLong(locationIdIndex);
        cursor.close();
        return rowId;
    } else {
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");
        cursor.close();
        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon);

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

        return ContentUris.parseId(locationInsertUri);
    }

}

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

public void load() {
    Cursor cursor = null;
    try {/*from  ww  w.  j a va2  s .co  m*/
        cursor = mCol.getDb().getDatabase().rawQuery(
                "SELECT guid, mid, mod, usn, tags, flds, flags, data FROM notes WHERE id = " + mId, null);
        if (!cursor.moveToFirst()) {
            Log.w(AnkiDroidApp.TAG, "Notes.load(): No result from query.");
            return;
        }
        mGuId = cursor.getString(0);
        mMid = cursor.getLong(1);
        mMod = cursor.getLong(2);
        mUsn = cursor.getInt(3);
        mFields = Utils.splitFields(cursor.getString(5));
        mTags = mCol.getTags().split(cursor.getString(4));
        mFlags = cursor.getInt(6);
        mData = cursor.getString(7);
        mScm = mCol.getScm();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    mModel = mCol.getModels().get(mMid);
    mFMap = mCol.getModels().fieldMap(mModel);
}

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

/**
 * Finds a specific resource by remote file name. Only records matching sqlFilter are taken into account.
 * @param remoteName   remote file name of the resource
 * @param populate       true: populates all data fields (for instance, contact or event details);
 *                    false: only remote file name and ETag are populated
 * @return resource with either ID/remote file/name/ETag or all fields populated
 * @throws RecordNotFoundException when the resource couldn't be found
 * @throws LocalStorageException when the content provider couldn't be queried
 *//*w  ww  . java  2 s. c  o m*/
public T findByRemoteName(String remoteName, boolean populate) throws LocalStorageException {
    String where = entryColumnRemoteName() + "=?";
    if (sqlFilter != null)
        where += " AND (" + sqlFilter + ")";
    try {
        @Cleanup
        Cursor cursor = providerClient.query(entriesURI(),
                new String[] { entryColumnID(), entryColumnRemoteName(), entryColumnETag() }, where,
                new String[] { remoteName }, null);
        if (cursor != null && cursor.moveToNext()) {
            T resource = newResource(cursor.getLong(0), cursor.getString(1), cursor.getString(2));
            if (populate)
                populate(resource);
            return resource;
        } else
            throw new RecordNotFoundException();
    } catch (RemoteException ex) {
        throw new LocalStorageException(ex);
    }
}