Example usage for android.database Cursor moveToNext

List of usage examples for android.database Cursor moveToNext

Introduction

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

Prototype

boolean moveToNext();

Source Link

Document

Move the cursor to the next row.

Usage

From source file:org.ohmage.sync.OhmageSyncAdapter.java

private void synchronizeOhmlets(final String userId, ContentProviderClient provider)
        throws AuthenticationException, RemoteException, InterruptedException {
    Log.d(TAG, "state of ohmlets sync");

    final CountDownLatch upload;

    // First, sync ohmlet join state. As described by the people field.
    Cursor cursor = null;
    try {/*from w  ww  .jav  a  2s.  com*/
        cursor = provider.query(OhmageContract.Ohmlets.CONTENT_URI,
                new String[] { OhmageContract.Ohmlets.OHMLET_ID, OhmageContract.Ohmlets.OHMLET_MEMBERS },
                Ohmlets.OHMLET_DIRTY + "=1", null, null);

        upload = new CountDownLatch(cursor.getCount());

        while (cursor.moveToNext()) {
            Member.List members = gson.fromJson(cursor.getString(1), Member.List.class);
            Member m = members.getMember(userId);
            if (m == null) {
                m = members.getMember("me");
                if (m != null) {
                    m.memberId = userId;
                }
            }
            final Member localMember = m;
            ohmageService.getOhmlet(cursor.getString(0)).first(new Func1<Ohmlet, Boolean>() {
                @Override
                public Boolean call(Ohmlet ohmlet) {
                    Member remoteMember = ohmlet.people.getMember(userId);
                    try {
                        if (localMember != null) {
                            if (remoteMember == null || localMember.role != remoteMember.role) {
                                // Check for join verification code to send
                                if (localMember.code != null) {
                                    String code = localMember.code;
                                    localMember.code = null;
                                    ohmageService.updateMemberForOhmlet(ohmlet.ohmletId, localMember, code);
                                } else {
                                    ohmageService.updateMemberForOhmlet(ohmlet.ohmletId, localMember);
                                }
                            }
                        }
                        if (localMember == null && remoteMember != null) {
                            ohmageService.removeUserFromOhmlet(ohmlet.ohmletId, userId);
                        }
                    } catch (AuthenticationException e) {
                        Log.e(TAG, "Error authenticating user", e);
                        Crashlytics.logException(e);
                        mSyncResult.stats.numAuthExceptions++;
                    } catch (RetrofitError e) {
                        Log.e(TAG, "Error synchronizing ohmlet member state", e);
                        Crashlytics.logException(e);
                        mSyncResult.stats.numIoExceptions++;
                    }
                    return true;
                }
            }).finallyDo(new Action0() {
                @Override
                public void call() {
                    upload.countDown();
                }
            }).subscribe();
        }
        cursor.close();

        // Wait for the upload sync operation to finish before downloading the user state
        upload.await();

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.seneca.android.senfitbeta.DbHelper.java

public ArrayList<Muscle> getMuscles() {
    Log.d("MUSCLE_GET", "Geting muscles");

    String fetchMus = "select * from " + RIP_TABLE + " ORDER BY " + RIP_NAME + " ASC";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(fetchMus, null);
    cursor.moveToFirst();//  ww w. jav  a  2s  .  c  o  m

    if (cursor == null) {
        Log.d("exiting", "NOTHING");
    }
    if (cursor.getCount() == 0) {
        Log.d("NOTHING", "0 nothing");
    }

    ArrayList<Muscle> temp = new ArrayList<Muscle>();

    cursor.moveToFirst();
    do {
        Muscle ex = new Muscle();
        ex.setId(cursor.getInt(cursor.getColumnIndex(RIP_ID)));
        ex.setName(cursor.getString(cursor.getColumnIndex(RIP_NAME)));

        temp.add(ex);
    } while (cursor.moveToNext());

    cursor.close();
    getReadableDatabase().close();
    return temp;

}

From source file:app.com.example.kiran.sunshine.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.
 * <p/>/*from ww  w . ja  va  2 s  .c om*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
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) {
            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(cur);
        //return resultStrs;

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

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

private void processDeletedGroups(ContentProviderClient provider, String authToken, Account account,
        SyncResult syncResult) throws RemoteException, ClientProtocolException, IOException, JSONException {
    Cursor cursor = null;
    try {// ww w.j  av  a  2  s .co m
        cursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup.CLOUD_ID },
                GMSGroup.STATUS + "=?", new String[] { String.valueOf(GMSGroup.STATUS_DELETED) }, null);
        if (cursor == null) {
            syncResult.databaseError = true;
            return;
        }
        while (cursor.moveToNext()) {
            if (NetworkUtilities.deleteGroup(authToken, cursor.getString(0)) != null) {
                syncResult.stats.numDeletes++;
            } else {
                syncResult.stats.numIoExceptions++;
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.trellmor.berrymotes.sync.EmoteDownloader.java

public void deleteSubreddit(String subreddit, ContentResolver contentResolver) throws IOException {

    Log.info(" Removing emotes of " + subreddit);
    Cursor c = contentResolver.query(EmotesContract.Emote.CONTENT_URI_DISTINCT,
            new String[] { EmotesContract.Emote.COLUMN_IMAGE }, EmotesContract.Emote.COLUMN_SUBREDDIT + "=?",
            new String[] { subreddit }, null);

    if (c.moveToFirst()) {
        final int POS_IMAGE = c.getColumnIndex(EmotesContract.Emote.COLUMN_IMAGE);

        do {/*from ww w.  j av a  2  s  .com*/
            checkStorageAvailable();
            File file = new File(c.getString(POS_IMAGE));
            if (file.exists()) {
                file.delete();
            }
        } while (c.moveToNext());
    }

    c.close();

    int deletes = mContentResolver.delete(EmotesContract.Emote.CONTENT_URI,
            EmotesContract.Emote.COLUMN_SUBREDDIT + "=?", new String[] { subreddit });
    Log.info("Removed emotes: " + Integer.toString(deletes));
    synchronized (mSyncResult) {
        mSyncResult.stats.numDeletes += deletes;
    }
}

From source file:com.gimranov.zandy.app.data.Item.java

/**
 * Identifies dirty items in the database and queues them for syncing
 *//*from   w w  w  .j a  va2 s.  c  om*/
public static void queue(Database db) {
    Log.d(TAG, "Clearing item dirty queue before repopulation");
    queue.clear();
    Item item;
    String[] cols = Database.ITEMCOLS;
    String[] args = { APIRequest.API_CLEAN };
    Cursor cur = db.query("items", cols, "dirty!=?", args, null, null, null, null);

    if (cur == null) {
        Log.d(TAG, "No dirty items found in database");
        queue.clear();
        return;
    }

    do {
        Log.d(TAG, "Adding item to dirty queue");
        item = load(cur);
        queue.add(item);
    } while (cur.moveToNext() != false);

    if (cur != null)
        cur.close();
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactField JSONArray/* w w w  .j  ava  2 s.  c  o m*/
 * @param cr database access object
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactFields
 */
private JSONArray phoneQuery(ContentResolver cr, String contactId) {
    Cursor cursor = cr.query(Phones.CONTENT_URI, null, Phones.PERSON_ID + " = ?", new String[] { contactId },
            null);
    JSONArray phones = new JSONArray();
    JSONObject phone;
    while (cursor.moveToNext()) {
        phone = new JSONObject();
        try {
            phone.put("id", cursor.getString(cursor.getColumnIndex(Phones._ID)));
            phone.put("perf", false);
            phone.put("value", cursor.getString(cursor.getColumnIndex(Phones.NUMBER)));
            phone.put("type", getPhoneType(cursor.getInt(cursor.getColumnIndex(Phones.TYPE))));
            phones.put(phone);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return phones;
}

From source file:com.ubikod.urbantag.model.TagManager.java

/**
 * Get all tags from db//from   w w  w . j  a  v a2  s.co  m
 * @return
 */
private HashMap<Integer, Tag> dbGetAll() {
    open();

    Cursor c = mDB.query(
            DatabaseHelper.TABLE_TAGS, new String[] { DatabaseHelper.TAG_COL_ID, DatabaseHelper.TAG_COL_NAME,
                    DatabaseHelper.TAG_COL_COLOR, DatabaseHelper.TAG_COL_NOTIFY },
            null, null, null, null, null);
    HashMap<Integer, Tag> tags = new HashMap<Integer, Tag>();

    if (c.getCount() == 0) {
        c.close();
        close();
        return tags;
    }

    c.moveToFirst();
    do {
        Tag t = this.cursorToTag(c);
        tags.put(t.getId(), t);
    } while (c.moveToNext());

    c.close();
    close();
    return tags;
}

From source file:com.example.igorklimov.popularmoviesdemo.fragments.DetailFragment.java

private void getSavedData(Cursor query) {
    mStrings = new String[5];
    ArrayList<String> author = new ArrayList<>();
    ArrayList<String> review = new ArrayList<>();

    String length = Utility.getLength(query);
    String budget = Utility.getBudget(query);
    String cast = Utility.getCast(query);
    String director = Utility.getDirector(query);
    String trailerUrl = Utility.getTrailerUrl(query);
    mStrings[0] = length;/* ww w . j av a 2  s.c o  m*/
    mStrings[1] = budget;
    mStrings[2] = trailerUrl;
    mStrings[3] = cast;
    mStrings[4] = director;

    Cursor r = mResolver.query(Review.CONTENT_URI, null, MovieContract.COLUMN_TITLE + "=?",
            new String[] { title }, null);
    if (r != null) {
        while (r.moveToNext()) {
            author.add(Utility.getAuthor(r));
            review.add(Utility.getReviewText(r));
        }
        r.close();
    }

    for (int i = 0; i < author.size(); i++) {
        HashMap<String, String> map = new HashMap<>();
        map.put(AUTHOR, author.get(i));
        map.put(REVIEW_TEXT, review.get(i));
        reviewsList.add(map);
    }
    setExtraData(mStrings);
}

From source file:com.calgen.prodek.sunshine.Data.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.
 * <p/>//from ww w  .  j a v  a  2  s.  com
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private String[] 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());

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

        cVVector = new Vector<>(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;
}