Example usage for android.database Cursor getCount

List of usage examples for android.database Cursor getCount

Introduction

In this page you can find the example usage for android.database Cursor getCount.

Prototype

int getCount();

Source Link

Document

Returns the numbers of rows in the cursor.

Usage

From source file:org.noorganization.instalistsynch.controller.synch.impl.TagSynch.java

@Override
public void indexLocal(int _groupId, Date _lastIndexTime) {
    String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000");
    boolean isLocal = false;
    GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup();
    if (groupAuth != null) {
        isLocal = groupAuth.getGroupId() == _groupId;
    }//from w  ww.j  a  v  a  2 s.  c  o m
    Cursor tagLogCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType);
    if (tagLogCursor.getCount() == 0) {
        tagLogCursor.close();
        return;
    }

    try {
        while (tagLogCursor.moveToNext()) {
            // fetch the action type
            int actionId = tagLogCursor.getInt(tagLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION));
            eActionType actionType = eActionType.getTypeById(actionId);

            List<ModelMapping> modelMappingList = mTagModelMappingController.get(
                    ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID
                            + " LIKE ?",
                    new String[] { String.valueOf(_groupId),
                            tagLogCursor.getString(tagLogCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) });
            ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0);

            switch (actionType) {
            case INSERT:
                // skip insertion because this should be decided by the user if the non local groups should have access to the category
                // and also skip if a mapping for this case already exists!
                if (!isLocal || modelMapping != null) {
                    continue;
                }

                String clientUuid = tagLogCursor
                        .getString(tagLogCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID));
                Date clientDate = ISO8601Utils.parse(
                        tagLogCursor.getString(tagLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)),
                        new ParsePosition(0));
                modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid,
                        new Date(Constants.INITIAL_DATE), clientDate, false);
                mTagModelMappingController.insert(modelMapping);
                break;
            case UPDATE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                String timeString = tagLogCursor
                        .getString(tagLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mTagModelMappingController.update(modelMapping);
                break;
            case DELETE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                modelMapping.setDeleted(true);
                timeString = tagLogCursor.getString(tagLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mTagModelMappingController.update(modelMapping);
                break;
            default:
            }

        }
    } catch (Exception e) {
        tagLogCursor.close();
    }
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * @param context The {@link Context} to use
 * @return The song list for the last added playlist
 *///  w  w w  .  j  a v a2s .c  o m
public static long[] getSongListForLastAdded(final Context context) {
    final Cursor cursor = LastAddedLoader.makeLastAddedCursor(context);
    if (cursor != null) {
        final int count = cursor.getCount();
        final long[] list = new long[count];
        for (int i = 0; i < count; i++) {
            cursor.moveToNext();
            list[i] = cursor.getLong(0);
        }
        return list;
    }
    return sEmptyList;
}

From source file:com.rjfun.cordova.sms.SMSPlugin.java

protected void createContentObserver() {
    Activity ctx = this.cordova.getActivity();
    this.mObserver = new ContentObserver(new Handler()) {

        public void onChange(boolean selfChange) {
            this.onChange(selfChange, null);
        }//from w  w w  .ja v  a 2 s .co m

        public void onChange(boolean selfChange, Uri uri) {
            ContentResolver resolver = cordova.getActivity().getContentResolver();
            Log.d(LOGTAG, ("onChange, selfChange: " + selfChange + ", uri: " + (Object) uri));
            int id = -1;
            String str;
            if (uri != null && (str = uri.toString()).startsWith(SMS_URI_ALL)) {
                try {
                    id = Integer.parseInt(str.substring(SMS_URI_ALL.length()));
                    Log.d(LOGTAG, ("sms id: " + id));
                } catch (NumberFormatException var6_6) {
                    // empty catch block
                }
            }
            if (id == -1) {
                uri = Uri.parse(SMS_URI_INBOX);
            }
            Cursor cur = resolver.query(uri, null, null, null, "_id desc");
            if (cur != null) {
                int n = cur.getCount();
                Log.d(LOGTAG, ("n = " + n));
                if (n > 0 && cur.moveToFirst()) {
                    JSONObject json;
                    if ((json = SMSPlugin.this.getJsonFromCursor(cur)) != null) {
                        onSMSArrive(json);
                    } else {
                        Log.d(LOGTAG, "fetch record return null");
                    }
                }
                cur.close();
            }
        }
    };
    ctx.getContentResolver().registerContentObserver(Uri.parse(SMS_URI_INBOX), true, this.mObserver);
    Log.d(LOGTAG, "sms inbox observer registered");
}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.SqliteGroupAccessDbControllerTest.java

License:asdf

public void testUpdateToken() throws Exception {
    Date currentDate = new Date();
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(GroupAccess.COLUMN.GROUP_ID, 1);
    cv.put(GroupAccess.COLUMN.INTERRUPTED, false);
    cv.put(GroupAccess.COLUMN.SYNCHRONIZE, true);
    cv.put(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.LAST_TOKEN_REQUEST, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.TOKEN, "fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.");

    assertTrue(db.insert(GroupAccess.TABLE_NAME, null, cv) >= 0);

    assertTrue(mGroupAuthAccessDbController.updateToken(1, "fdskhbvvkddscddueasdfeSAdnandk3229df-dFSJDKMds."));

    Cursor cursor = db.query(GroupAccess.TABLE_NAME, GroupAccess.COLUMN.ALL_COLUMNS,
            GroupAccess.COLUMN.GROUP_ID + " = ? ", new String[] { String.valueOf(1) }, null, null, null);
    int count = cursor.getCount();
    if (count == 0)
        cursor.close();// www  .jav a 2  s.c  o m

    assertTrue(cursor.moveToFirst());
    int groupId = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.GROUP_ID));
    boolean synchronize = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.SYNCHRONIZE)) == 1;
    boolean interrupted = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.INTERRUPTED)) == 1;
    Date lastTokenRequestDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_TOKEN_REQUEST)),
            new ParsePosition(0));
    Date lastUpdateDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER)),
            new ParsePosition(0));
    String token = cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.TOKEN));
    cursor.close();

    assertEquals(1, groupId);
    assertEquals(true, synchronize);
    assertEquals(false, interrupted);

    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastTokenRequestDate));
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastUpdateDate));
    assertEquals("fdskhbvvkddscddueasdfeSAdnandk3229df-dFSJDKMds.", token);
}

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

@Override
protected Boolean doInBackground(Long... tripid) {
    // First, send the trip user asked for:
    Boolean result = true;/*from   www. j a va  2 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) {
        // Reades all unsent trips
        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:com.example.asaldanha.sunshine.app.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from w  w  w .jav  a 2 s.  c o  m*/
 */
//    private String[] getWeatherDataFromJson(String forecastJsonStr,
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting,
                System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert

        Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder);

        cVVector = new Vector<ContentValues>(cur.getCount());
        if (cur.moveToFirst()) {
            do {
                ContentValues cv = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(cur, cv);
                cVVector.add(cv);
            } while (cur.moveToNext());
        }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        //String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        //return resultStrs;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    //return null;
}

From source file:com.intel.xdk.contacts.Contacts.java

public String JSONValueForPerson(String idlk) {
    ContentResolver cr = activity.getContentResolver();
    //PROCESS NAME ELEMENTS FOR CURRENT CONTACT ID
    String firstName = "", lastName = "", compositeName = "", id = "";
    String nameWhere = ContactsContract.Data.LOOKUP_KEY + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
    String[] params = new String[] { idlk, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
    Cursor nameCur = cr.query(ContactsContract.Data.CONTENT_URI, null, nameWhere, params, null);
    if (nameCur.getCount() > 0) {
        nameCur.moveToFirst();/*from  www .  ja  v  a 2 s .  c o  m*/
        id = nameCur.getString(nameCur.getColumnIndex(ContactsContract.Data.CONTACT_ID));

        firstName = nameCur
                .getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
        lastName = nameCur
                .getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
        compositeName = nameCur.getString(
                nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));

        firstName = (firstName == null) ? "" : escapeStuff(firstName);
        lastName = (lastName == null) ? "" : escapeStuff(lastName);
        compositeName = (compositeName == null) ? "" : escapeStuff(compositeName);
    }

    //PROCESS EMAIL ADDRESES FOR CURRENT CONTACT ID
    Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
    String emailAddresses = "[]";
    if (emailCur.getCount() > 0) {
        emailAddresses = "[";
        while (emailCur.moveToNext()) {
            String email = emailCur
                    .getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            email = escapeStuff(email);
            //String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); 

            emailAddresses += "'" + email + "', ";

        }
        emailAddresses += "]";
    }
    emailCur.close();

    //PROCESS PHONE NUMBERS FOR CURRENT CONTACT ID
    Cursor phoneCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);

    String phoneNumbers = "[]";
    if (phoneCur.getCount() > 0) {
        phoneNumbers = "[";
        while (phoneCur.moveToNext()) {
            String phoneNum = phoneCur
                    .getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            phoneNum = escapeStuff(phoneNum);
            phoneNumbers += "'" + phoneNum + "', ";
        }
        phoneNumbers += "]";
    }
    phoneCur.close();

    //PROCESS STREET ADDRESSES FOR CURRENT CONTACT ID
    String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
    String[] addrWhereParams = new String[] { id,
            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
    Cursor addressCur = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, addrWhere,
            addrWhereParams, null);

    String streetAddresses = "[]";
    if (addressCur.getCount() > 0) {
        streetAddresses = "[";
        while (addressCur.moveToNext()) {

            String street = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
            String city = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
            String state = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
            String zip = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
            String country = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));

            street = escapeStuff(street);
            city = escapeStuff(city);
            state = escapeStuff(state);
            zip = escapeStuff(zip);
            country = escapeStuff(country);

            String addressstr = String.format(
                    "{ street:'%s', city:'%s', state:'%s', zip:'%s', country:'%s' }, ", street, city, state,
                    zip, country);
            streetAddresses += addressstr;

        }
        streetAddresses += "]";
    }
    addressCur.close();

    String jsPerson = String.format(
            "{ id:'%s', name:'%s', first:'%s', last:'%s', phones:%s, emails:%s, addresses:%s }, ", idlk,
            compositeName, firstName, lastName, phoneNumbers, emailAddresses, streetAddresses);
    return jsPerson.replaceAll("\\r\\n|\\r|\\n", "\\\\n");

}

From source file:com.mpower.daktar.android.tasks.DownloadFormsTask.java

/**
 * Takes the formName and the URL and attempts to download the specified
 * file. Returns a file object representing the downloaded file.
 *
 * @param formName/*from ww  w. ja  v a  2  s .co m*/
 * @param url
 * @return
 * @throws Exception
 */
private File downloadXform(final String formName, final String url) throws Exception {
    File f = null;

    // clean up friendly form name...
    String rootName = formName.replaceAll("[^\\p{L}\\p{Digit}]", " ");
    rootName = rootName.replaceAll("\\p{javaWhitespace}+", " ");
    rootName = rootName.trim();

    // proposed name of xml file...
    String path = MIntel.FORMS_PATH + "/" + rootName + ".xml";
    int i = 2;
    f = new File(path);
    while (f.exists()) {
        path = MIntel.FORMS_PATH + "/" + rootName + "_" + i + ".xml";
        f = new File(path);
        i++;
    }

    downloadFile(f, url);

    // we've downloaded the file, and we may have renamed it
    // make sure it's not the same as a file we already have
    final String[] projection = { FormsColumns.FORM_FILE_PATH };
    final String[] selectionArgs = { FileUtils.getMd5Hash(f) };
    final String selection = FormsColumns.MD5_HASH + "=?";

    final Cursor c = MIntel.getInstance().getContentResolver().query(FormsColumns.CONTENT_URI, projection,
            selection, selectionArgs, null);
    if (c.getCount() > 0) {
        // Should be at most, 1
        c.moveToFirst();

        // delete the file we just downloaded, because it's a duplicate
        f.delete();

        // set the file returned to the file we already had
        f = new File(c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH)));
    }
    c.close();

    return f;
}

From source file:fr.unix_experience.owncloud_sms.engine.SmsFetcher.java

private void bufferizeMailboxMessages(MailboxID mbID) {
    String mbURI = mapMailboxIDToURI(mbID);

    if (_context == null || mbURI == null) {
        return;/* ww  w.  j  a v a 2s .c  om*/
    }

    if (mbID != MailboxID.INBOX && mbID != MailboxID.SENT && mbID != MailboxID.DRAFTS) {
        Log.e(TAG, "Unhandled MailboxID " + mbID.ordinal());
        return;
    }

    // We generate a ID list for this message box
    String existingIDs = buildExistingMessagesString(mbID);

    Cursor c = null;
    if (existingIDs.length() > 0) {
        c = (new SmsDataProvider(_context)).query(mbURI, "_id NOT IN (" + existingIDs + ")");
    } else {
        c = (new SmsDataProvider(_context)).query(mbURI);
    }

    // Reading mailbox
    if (c != null && c.getCount() > 0) {
        c.moveToFirst();
        do {
            JSONObject entry = new JSONObject();

            try {
                for (int idx = 0; idx < c.getColumnCount(); idx++) {
                    String colName = c.getColumnName(idx);

                    // Id column is must be an integer
                    if (colName.equals(new String("_id")) || colName.equals(new String("type"))) {
                        entry.put(colName, c.getInt(idx));

                        // bufferize Id for future use
                        if (colName.equals(new String("_id"))) {
                        }
                    }
                    // Seen and read must be pseudo boolean
                    else if (colName.equals(new String("read")) || colName.equals(new String("seen"))) {
                        entry.put(colName, c.getInt(idx) > 0 ? "true" : "false");
                    } else {
                        // Special case for date, we need to record last without searching
                        if (colName.equals(new String("date"))) {
                            final Long tmpDate = c.getLong(idx);
                            if (tmpDate > _lastMsgDate) {
                                _lastMsgDate = tmpDate;
                            }
                        }
                        entry.put(colName, c.getString(idx));
                    }
                }

                // Mailbox ID is required by server
                entry.put("mbox", mbID.ordinal());

                _jsonDataDump.put(entry);

            } catch (JSONException e) {
                Log.e(TAG, "JSON Exception when reading SMS Mailbox", e);
                c.close();
            }
        } while (c.moveToNext());

        Log.d(TAG, c.getCount() + " messages read from " + mbURI);

        c.close();
    }
}

From source file:myblog.richard.vewe.launcher3.LauncherApplication.java

public User latestUser() {
    User u = null;/*w  w  w  .  jav  a2 s  . c  o  m*/

    ContentResolver resolver = getContentResolver();

    String selection = UsersContract.TableUsers.Column.NAME + "=" + UsersContract.TableUsers.CURRENT;
    try {
        Cursor cursor = resolver.query(UsersContract.TableUsers.CONTENT_URI,
                UsersContract.TableUsers.BASIC_COLUMNS, selection, null, null);
        if (cursor == null || cursor.getCount() != 1) {
            Log.e(tag, "failed to query current user");
            return null;
        }
        cursor.moveToFirst();
        u = new User(cursor);
        cursor.close();
        if (LOGD) {
            Log.d(tag, "current User " + u);
        }
    } catch (Exception e) {

    } finally {
        return u;
    }
}