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.hichinaschool.flashcards.libanki.Card.java

/**
 * Reload Card details from db./*from w  ww.ja  v  a2  s.co m*/
 * @return True if the load was successful, false if no card with such id was found.
 */
public boolean load() {
    Cursor cursor = null;
    try {
        cursor = mCol.getDb().getDatabase().rawQuery("SELECT * FROM cards WHERE id = " + mId, null);
        if (!cursor.moveToFirst()) {
            Log.w(AnkiDroidApp.TAG, "Card.load: No card with id " + mId);
            return false;
        }
        mId = cursor.getLong(0);
        mNid = cursor.getLong(1);
        mDid = cursor.getLong(2);
        mOrd = cursor.getInt(3);
        mMod = cursor.getLong(4);
        mUsn = cursor.getInt(5);
        mType = cursor.getInt(6);
        mQueue = cursor.getInt(7);
        mDue = cursor.getInt(8);
        mIvl = cursor.getInt(9);
        mFactor = cursor.getInt(10);
        mReps = cursor.getInt(11);
        mLapses = cursor.getInt(12);
        mLeft = cursor.getInt(13);
        mODue = cursor.getLong(14);
        mODid = cursor.getLong(15);
        mFlags = cursor.getInt(16);
        mData = cursor.getString(17);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    mQA = null;
    mNote = null;
    return true;
}

From source file:com.samknows.measurement.storage.DBHelper.java

private JSONObject cursorPassiveMetricToJSONObject(Cursor c) {
    JSONObject ret = new JSONObject();
    // PM_COLUMN_ID, PM_COLUMN_METRIC, PM_COLUMN_DTIME, PM_COLUMN_VALUE,
    // PM_COLUMN_TYPE, PM_COLUMN_BATCH_ID
    try {//from www.j a va  2 s .c  om
        ret.put(SKSQLiteHelper.PM_COLUMN_ID, c.getLong(0));
        ret.put(SKSQLiteHelper.PM_COLUMN_METRIC, c.getString(1));
        ret.put(SKSQLiteHelper.PM_COLUMN_DTIME, c.getLong(2));
        ret.put(SKSQLiteHelper.PM_COLUMN_VALUE, c.getString(3));
        ret.put(SKSQLiteHelper.PM_COLUMN_TYPE, c.getString(4));
        ret.put(SKSQLiteHelper.PM_COLUMN_BATCH_ID, c.getLong(5));
    } catch (JSONException je) {
        Logger.e(DBHelper.class, "Error in converting passive metric entry into JSONObject" + je.getMessage());
    }
    return ret;
}

From source file:com.example.diego.sunshine.FetchWeatherTask.java

private Long getLocationIdByLocationSetting(String locationSetting) {
    // A cursor is your primary interface to the query results.
    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID }, // leaving "columns" null just returns all the columns.
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? ", // cols for "where" clause
            new String[] { locationSetting }, // values for "where" clause
            null // sort order
    );//from w  w w  .  j  av  a2s .c  o m
    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        return cursor.getLong(locationIdIndex);
    }
    return null;
}

From source file:com.ubuntuone.android.files.provider.MetaUtilities.java

public static U1Node getNodeByResourcePath(String resourcePath) {
    String[] selectionArgs = new String[] { resourcePath };
    String selection = Nodes.NODE_RESOURCE_PATH + "=?";
    String[] projection = Nodes.getDefaultProjection();
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
    if (c != null) {
        try {//from   www.j ava2 s.  c  om
            if (c.moveToFirst()) {
                String key;
                U1NodeKind kind;
                Boolean isLive = true;
                String path;
                String parentPath;
                String volumePath;
                Date whenCreated;
                Date whenChanged;
                Long generation;
                Long generationCreated;
                String contentPath;

                key = c.getString(c.getColumnIndex(Nodes.NODE_KEY));
                kind = U1NodeKind
                        .valueOf(c.getString(c.getColumnIndex(Nodes.NODE_KIND)).toUpperCase(Locale.US));
                isLive = c.getInt(c.getColumnIndex(Nodes.NODE_IS_LIVE)) != 0;
                path = c.getString(c.getColumnIndex(Nodes.NODE_PATH));
                parentPath = c.getString(c.getColumnIndex(Nodes.NODE_PARENT_PATH));
                volumePath = c.getString(c.getColumnIndex(Nodes.NODE_VOLUME_PATH));
                whenCreated = new Date(c.getLong(c.getColumnIndex(Nodes.NODE_WHEN_CREATED)));
                whenChanged = new Date(c.getLong(c.getColumnIndex(Nodes.NODE_WHEN_CHANGED)));
                generation = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION));
                generationCreated = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION_CREATED));
                contentPath = c.getString(c.getColumnIndex(Nodes.NODE_CONTENT_PATH));

                return new U1Node(resourcePath, kind, isLive, path, parentPath, volumePath, key, whenCreated,
                        whenChanged, generation, generationCreated, contentPath);
            } else {
                return null;
            }
        } finally {
            c.close();
        }
    }
    return null;
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";
    DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a");

    /** /*  w w w  .ja v a 2 s .  c o  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[] { "ferries_schedules" }, 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) > (30 * 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(FERRIES_SCHEDULES_URL);
            URLConnection urlConn = url.openConnection();

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String jsonFile = "";
            String line;

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

            JSONArray items = new JSONArray(jsonFile);
            List<ContentValues> schedules = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int i = 0; i < numItems; i++) {
                JSONObject item = items.getJSONObject(i);
                ContentValues schedule = new ContentValues();
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ID, item.getInt("RouteID"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_TITLE, item.getString("Description"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_DATE, item.getString("Date"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ALERT, item.getString("RouteAlert"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_UPDATED, dateFormat
                        .format(new Date(Long.parseLong(item.getString("CacheDate").substring(6, 19)))));

                if (starred.contains(item.getInt("RouteID"))) {
                    schedule.put(FerriesSchedules.FERRIES_SCHEDULE_IS_STARRED, 1);
                }

                schedules.add(schedule);
            }

            // Purge existing travel times covered by incoming data
            resolver.delete(FerriesSchedules.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(FerriesSchedules.CONTENT_URI,
                    schedules.toArray(new ContentValues[schedules.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[] { "ferries_schedules" });

            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.FERRIES_SCHEDULES_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);

}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferRecord.java

/**
 * Updates all the fields from database using the given Cursor.
 *
 * @param c A Cursor pointing to a transfer record.
 *///from   w  w w . j a v a2  s  .  c  om
public void updateFromDB(Cursor c) {
    this.id = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_ID));
    this.mainUploadId = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_MAIN_UPLOAD_ID));
    this.type = TransferType.getType(c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_TYPE)));
    this.state = TransferState.getState(c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_STATE)));
    this.bucketName = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_BUCKET_NAME));
    this.key = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_KEY));
    this.versionId = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_VERSION_ID));
    this.bytesTotal = c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_BYTES_TOTAL));
    this.bytesCurrent = c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_BYTES_CURRENT));
    this.speed = c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_SPEED));
    this.isRequesterPays = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_IS_REQUESTER_PAYS));
    this.isMultipart = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_IS_MULTIPART));
    this.isLastPart = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_IS_LAST_PART));
    this.isEncrypted = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_IS_ENCRYPTED));
    this.partNumber = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_PART_NUM));
    this.eTag = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_ETAG));
    this.file = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_FILE));
    this.multipartId = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_MULTIPART_ID));
    this.rangeStart = c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_DATA_RANGE_START));
    this.rangeLast = c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_DATA_RANGE_LAST));
    this.fileOffset = c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_FILE_OFFSET));
    this.headerContentType = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_HEADER_CONTENT_TYPE));
    this.headerContentLanguage = c
            .getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_HEADER_CONTENT_LANGUAGE));
    this.headerContentDisposition = c
            .getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_HEADER_CONTENT_DISPOSITION));
    this.headerContentEncoding = c
            .getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_HEADER_CONTENT_ENCODING));
    this.headerCacheControl = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_HEADER_CACHE_CONTROL));
    this.headerExpire = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_HEADER_EXPIRE));
    this.userMetadata = JsonUtils
            .jsonToMap(c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_USER_METADATA)));
    this.expirationTimeRuleId = c
            .getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_EXPIRATION_TIME_RULE_ID));
    this.httpExpires = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_HTTP_EXPIRES_DATE));
    this.sseAlgorithm = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_SSE_ALGORITHM));
    this.sseKMSKey = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_SSE_KMS_KEY));
    this.md5 = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_CONTENT_MD5));
    this.cannedAcl = c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_CANNED_ACL));
}

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

/**
 * Query .../models URI//from   ww  w.  j av a2s. co m
 */
public void testQueryAllModels() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available models
    final Cursor allModels = cr.query(FlashCardsContract.Model.CONTENT_URI, null, null, null, null);
    assertNotNull(allModels);
    try {
        assertTrue("Check that there is at least one result", allModels.getCount() > 0);
        while (allModels.moveToNext()) {
            long modelId = allModels.getLong(allModels.getColumnIndex(FlashCardsContract.Model._ID));
            Uri modelUri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, Long.toString(modelId));
            final Cursor singleModel = cr.query(modelUri, null, null, null, null);
            assertNotNull(singleModel);
            try {
                assertEquals("Check that there is exactly one result", 1, singleModel.getCount());
                assertTrue("Move to beginning of cursor", singleModel.moveToFirst());
                String nameFromModels = allModels
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME));
                String nameFromModel = singleModel
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME));
                assertEquals("Check that model names are the same", nameFromModel, nameFromModels);
                String flds = allModels
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES));
                assertTrue("Check that valid number of fields", Utils.splitFields(flds).length >= 1);
                Integer numCards = allModels
                        .getInt(allModels.getColumnIndex(FlashCardsContract.Model.NUM_CARDS));
                assertTrue("Check that valid number of cards", numCards >= 1);
            } finally {
                singleModel.close();
            }
        }
    } finally {
        allModels.close();
    }
}

From source file:com.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * get the music info//from w ww.  ja v a  2 s.  c  om
 * 
 * @param musicFile
 * @return
 */
public static SongModel getMusicInfo(File musicFile) {
    SongModel model = new SongModel();
    // retrun null if music file is null or is or directory
    if (musicFile == null || !musicFile.isFile()) {
        return null;
    }

    byte[] buf = new byte[128];
    try {
        Log.d(LOG_TAG, "process music file{" + musicFile.getAbsolutePath() + "}");
        // tag_v1
        RandomAccessFile music = new RandomAccessFile(musicFile, "r");

        music.seek(music.length() - 128);
        music.read(buf);// read tag to buffer
        // tag_v2
        byte[] header = new byte[10];
        music.seek(0);
        music.read(header, 0, 10);
        // if ("ID3".equalsIgnoreCase(new String(header, 0, 3))) {
        // int ID3V2_frame_size = (int) (header[6] & 0x7F) * 0x200000
        // | (int) (header[7] & 0x7F) * 0x400
        // | (int) (header[8] & 0x7F) * 0x80
        // | (int) (header[9] & 0x7F);
        // byte[] FrameHeader = new byte[4];
        // music.seek(ID3V2_frame_size + 10);
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, ID3V2_frame_size, musicFile);
        // } else {
        // byte[] FrameHeader = new byte[4];
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, 0, musicFile);
        // }

        music.close();// close file
        // check length
        // if (buf.length != 128) {
        // throw new
        // ErrorMusicLength(String.format("error music info length, length is:%i",
        // buf.length));
        // }
        //
        // if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {
        // throw new UnknownTagException("unknown tag exception");
        // }
        String songName = null;
        // try {
        // songName = new String(buf, 3, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // e.printStackTrace();
        // songName = new String(buf, 3, 30).trim();
        // }
        String singerName = "";
        // try {
        // singerName = new String(buf, 33, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // singerName = new String(buf, 33, 30).trim();
        // }
        String ablum = "";
        // try {
        // ablum = new String(buf, 63, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // ablum = new String(buf, 63, 30).trim();
        // }
        String year = "";
        // try {
        // year = new String(buf, 93, 4, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // year = new String(buf, 93, 4).trim();
        // // TODO: handle exception
        // }

        String reamrk = "";
        ContentResolver contentResolver = sContext.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "_data=?",
                new String[] { musicFile.getAbsolutePath() }, null);
        cursor.moveToFirst();
        if (cursor != null && cursor.getCount() != 0) {
            try {
                if (TextUtils.isEmpty(songName)) {
                    songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
                    singerName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));
                    ablum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM));
                    year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
                }

                long secs = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));
                model.setTime(secs);
                secs /= 1000;
                model.setHours((int) secs / 3600);
                model.setMinutes(((int) secs % 3600) / 60);
                model.setSeconds(((int) secs % 3600) % 60);
                cursor.close();
            } catch (CursorIndexOutOfBoundsException e) {
                // TODO: handle exception
                if (null != cursor) {
                    cursor.close();
                    cursor = null;
                }
                Log.d(LOG_TAG, "CursorIndexOutOfBoundsException:" + e.getMessage());
                try {
                    songName = new String(buf, 3, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e0) {
                    // TODO: handle exception
                    e.printStackTrace();
                    songName = new String(buf, 3, 30).trim();
                }
                try {
                    singerName = new String(buf, 33, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e1) {
                    // TODO: handle exception
                    singerName = new String(buf, 33, 30).trim();
                }
                try {
                    ablum = new String(buf, 63, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e2) {
                    // TODO: handle exception
                    ablum = new String(buf, 63, 30).trim();
                }
                try {
                    year = new String(buf, 93, 4, "gbk").trim();
                } catch (UnsupportedEncodingException e3) {
                    year = new String(buf, 93, 4).trim();
                    // TODO: handle exception
                }

                try {
                    reamrk = new String(buf, 97, 28, "gbk").trim();
                } catch (UnsupportedEncodingException e4) {
                    // TODO: handle exception
                    reamrk = new String(buf, 97, 28).trim();
                }

            }
        }

        //

        // get the time len

        model.setSongName(songName);
        model.setSingerName(singerName);
        model.setAblumName(ablum);
        model.setFile(musicFile.getAbsolutePath());
        model.setRemark("");
        Log.d(LOG_TAG, String.format("scaned music file[%s],album name[%s],song name[%s],singer name[%s]",
                model.getFile(), model.getAblumName(), model.getSingerName(), model.getSingerName()));

        mSongs.add(model);

        return model;
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return model;
}

From source file:com.vrj.udacity.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//ww w  . j  a va 2 s .co 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
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    long retID = -1L;

    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, // location db
            new String[] { WeatherContract.LocationEntry._ID }, // We want the ID column  
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?", // Must add = ? param or will not match up
            new String[] { locationSetting }, null);

    if (true == cursor.moveToFirst()) { // If we got something back look for id
        // retID = cursor.getLong(0);       // Return the ID
        int location_index = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        retID = cursor.getLong(location_index);
    } else { // Do an insert of the parameter values

        // Creation of ContentValues for insert
        // TODO: Fixup, order is different, if causes trouble
        ContentValues cValues = new ContentValues();
        cValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        cValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        cValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        cValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Insert new location in db
        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                cValues);

        // Extract the locationId from the Uri you got back from .insert().
        retID = ContentUris.parseId(insertedUri);

    }

    cursor.close(); // REMEMEBER to close your cursors.

    return retID;
}

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

/**
 * Test query to specific deck ID/*from   w w w  . j  a  va2s  .  c o  m*/
 * @throws Exception
 */
public void testQueryCertainDeck() throws Exception {
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());

    long deckId = mTestDeckIds[0];
    Uri deckUri = Uri.withAppendedPath(FlashCardsContract.Deck.CONTENT_ALL_URI, Long.toString(deckId));
    Cursor decksCursor = getContext().getContentResolver().query(deckUri, null, null, null, null);
    try {
        if (decksCursor == null || !decksCursor.moveToFirst()) {
            fail("No deck received. Should have delivered deck with id " + deckId);
        } else {
            long returnedDeckID = decksCursor
                    .getLong(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_ID));
            String returnedDeckName = decksCursor
                    .getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_NAME));

            JSONObject realDeck = col.getDecks().get(deckId);
            assertEquals("Check that received deck ID equals real deck ID", deckId, returnedDeckID);
            assertEquals("Check that received deck name equals real deck name", realDeck.getString("name"),
                    returnedDeckName);
        }
    } finally {
        decksCursor.close();
    }
}