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:com.orm.androrm.migration.MigrationHelper.java

public List<String> getRelationTableNames(String table) {
    List<String> result = new ArrayList<String>();
    String sql = "SELECT name FROM sqlite_master WHERE type='table' AND (name LIKE '" + table
            + "#_%' OR name LIKE '%#_" + table + "' ESCAPE '#')";

    Cursor c = getCursor(sql);

    while (c.moveToNext()) {
        String name = c.getString(c.getColumnIndexOrThrow("name"));

        if (!name.equalsIgnoreCase(table) && (StringUtils.startsWithIgnoreCase(name, table)
                || StringUtils.endsWithIgnoreCase(name, table))) {

            result.add(name);/*ww w.  ja  v a2 s.c  o m*/
        }
    }

    close(c);
    return result;
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static void updateContact(Context context, ContentResolver resolver, RawContact rawContact,
        boolean updateAvatar, boolean inSync, long rawContactId, BatchOperation batchOperation) {

    ContactsSync app = ContactsSync.getInstance();
    boolean existingAvatar = false;

    final Cursor c = resolver.query(DataQuery.CONTENT_URI, DataQuery.PROJECTION, DataQuery.SELECTION,
            new String[] { String.valueOf(rawContactId) }, null);
    final ContactOperations contactOp = ContactOperations.updateExistingContact(context, rawContactId, inSync,
            batchOperation);// ww w.ja v  a 2 s  .co m
    try {
        // Iterate over the existing rows of data, and update each one
        // with the information we received from the server.
        while (c.moveToNext()) {
            final long id = c.getLong(DataQuery.COLUMN_ID);
            final String mimeType = c.getString(DataQuery.COLUMN_MIMETYPE);
            final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, id);
            if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE)) {
                contactOp.updateName(uri, c.getString(DataQuery.COLUMN_GIVEN_NAME),
                        c.getString(DataQuery.COLUMN_FAMILY_NAME), rawContact.getFirstName(),
                        rawContact.getLastName());
                /*   } else if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)) {
                      final int type = c.getInt(DataQuery.COLUMN_PHONE_TYPE);
                      if (type == Phone.TYPE_MOBILE) {
                         existingCellPhone = true;
                         contactOp.updatePhone(
                c.getString(DataQuery.COLUMN_PHONE_NUMBER),
                "5345345", uri);
                      } else if (type == Phone.TYPE_HOME) {
                         existingHomePhone = true;
                         contactOp.updatePhone(
                c.getString(DataQuery.COLUMN_PHONE_NUMBER),
                "5345345", uri);
                      } else if (type == Phone.TYPE_WORK) {
                         existingWorkPhone = true;
                         contactOp.updatePhone(
                c.getString(DataQuery.COLUMN_PHONE_NUMBER),
                "5345345", uri);
                      }
                   */
            } else if (mimeType.equals(Photo.CONTENT_ITEM_TYPE)) {
                existingAvatar = true;
                if (app.getSyncType() == ContactsSync.SyncType.LEGACY) {
                    contactOp.updateAvatar(c.getString(DataQuery.COLUMN_DATA1), rawContact.getAvatarUrl(), uri);
                }
            }
        } // while
    } finally {
        c.close();
    }

    // Add the avatar if we didn't update the existing avatar
    if (app.getSyncType() != ContactsSync.SyncType.HARD && !existingAvatar) {
        contactOp.addAvatar(rawContact.getAvatarUrl());
    }

    // If we don't have a status profile, then create one. This could
    // happen for contacts that were created on the client - we don't
    // create the status profile until after the first sync...
    final String serverId = rawContact.getUid();
    final long profileId = lookupProfile(resolver, serverId);
    if (profileId <= 0) {
        contactOp.addProfileAction(serverId);
    }
}

From source file:com.bourke.kitchentimer.utils.Utils.java

public static boolean exportCSV(Context context, Cursor cursor) {
    if (cursor.getCount() == 0)
        return true;
    // An array to hold the rows that will be written to the CSV file.
    final int rowLenght = FoodMetaData.COLUMNS.length - 1;
    String[] row = new String[rowLenght];
    System.arraycopy(FoodMetaData.COLUMNS, 1, row, 0, rowLenght);
    CSVWriter writer = null;/*from   w w  w  .  ja  va  2s .c  o m*/
    boolean success = false;

    try {
        writer = new CSVWriter(new FileWriter(Constants.CSV_FILE));

        // Write descriptive headers.
        writer.writeNext(row);

        int nameIndex = cursor.getColumnIndex(FoodMetaData.NAME);
        int hoursIndex = cursor.getColumnIndex(FoodMetaData.HOURS);
        int minutesIndex = cursor.getColumnIndex(FoodMetaData.MINUTES);
        int secondsIndex = cursor.getColumnIndex(FoodMetaData.SECONDS);

        if (cursor.requery()) {
            while (cursor.moveToNext()) {
                row[0] = cursor.getString(nameIndex);
                row[1] = cursor.getInt(hoursIndex) + "";
                row[2] = cursor.getInt(minutesIndex) + "";
                row[3] = cursor.getInt(secondsIndex) + "";
                // NOTE: writeNext() handles nulls in row[] gracefully.
                writer.writeNext(row);
            }
        }
        success = true;
    } catch (Exception ex) {
        Log.e("Utils", "exportCSV", ex);
    } finally {
        try {
            if (null != writer)
                writer.close();
        } catch (IOException ex) {

        }
    }
    return success;
}

From source file:org.npr.android.news.StationListAdapter.java

public void initializeList(Cursor cursor) {
    data = new ArrayList<Station>();

    while (cursor.moveToNext()) {
        Station.StationBuilder builder = new Station.StationBuilder(
                cursor.getString(cursor.getColumnIndex(FavoriteStationsProvider.Items.STATION_ID)));
        builder.withName(cursor.getString(cursor.getColumnIndex(FavoriteStationsProvider.Items.NAME)));
        builder.withMarketCity(cursor.getString(cursor.getColumnIndex(FavoriteStationsProvider.Items.MARKET)));
        builder.withFrequency(/*from   w w  w .ja va2s. c o m*/
                cursor.getString(cursor.getColumnIndex(FavoriteStationsProvider.Items.FREQUENCY)));
        builder.withBand(cursor.getString(cursor.getColumnIndex(FavoriteStationsProvider.Items.BAND)));
        data.add(builder.build());
    }
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static Vector<Long> getUnreadNoncatchedArticleList(String group, Context context) {
    int groupid = getGroupIdFromName(group, context);

    Vector<Long> artList = null;
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

    String q = "SELECT server_article_number FROM headers WHERE subscribed_group_id=" + groupid
            + " AND read=0 AND catched=0";
    Cursor c = dbread.rawQuery(q, null);

    int count = c.getCount();
    artList = new Vector<Long>(count);

    c.moveToFirst();//from   w w w  .ja v a 2  s  .  c om

    for (int i = 0; i < count; i++) {
        artList.add(c.getLong(0));
        c.moveToNext();
    }

    c.close();
    dbread.close();
    db.close();
    return artList;
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static HashSet<String> getGroupSentMessagesSet(String group, Context context) {
    int groupid = getGroupIdFromName(group, context);

    HashSet<String> retVal = null;
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

    String q = "SELECT server_article_id FROM sent_posts_log WHERE subscribed_group_id=" + groupid;
    Cursor c = dbread.rawQuery(q, null);
    int count = c.getCount();

    retVal = new HashSet<String>(count);
    c.moveToFirst();/*w w w  .  j  a  v a 2 s  .com*/

    for (int i = 0; i < count; i++) {
        retVal.add(c.getString(0));
        c.moveToNext();
    }

    c.close();
    dbread.close();
    db.close();

    return retVal;
}

From source file:org.thomnichols.android.gmarks.WebViewCookiesDB.java

List<Cookie> getCookies() {
    List<Cookie> cookies = new ArrayList<Cookie>();
    SQLiteDatabase db = openDatabase(SQLiteDatabase.OPEN_READONLY);
    if (db == null)
        return cookies;

    try {/*w w  w.ja v  a 2 s.c o  m*/
        db.execSQL("PRAGMA read_uncommitted = true;");
        Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null, null, null);

        while (cursor.moveToNext()) {
            BasicClientCookie c = new BasicClientCookie(cursor.getString(COL_NAME),
                    cursor.getString(COL_VALUE));
            c.setDomain(cursor.getString(COL_DOMAIN));
            c.setPath(cursor.getString(COL_PATH));
            Long expiry = cursor.getLong(COL_EXPIRES);
            if (expiry != null)
                c.setExpiryDate(new Date(expiry));
            c.setSecure(cursor.getShort(COL_SECURE) == 1);
            Log.d(TAG, "Got cookie: " + c.getName());
            cookies.add(c);
        }
        cursor.close();

        //         cursor = db.query(TABLE_NAME, new String[] {"count(name)"}, null, null, null, null, null);
        //         cursor.moveToFirst();
        //         Log.d("WEBVIEW DB QUERY", "COunt: " + cursor.getLong(0) );
        //          cursor.close();
        return cookies;
    } finally {
        db.close();
    }
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side contacts. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account/*from ww  w .  j  a  v a  2  s  . c om*/
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyContacts A list of the contacts to send to the server
 * @return A list of contacts that we need to update locally
 */
public static void syncCalendar(Context context, Account account, String authtoken, long serverSyncState)
        throws JSONException, ParseException, IOException, AuthenticationException {
    ArrayList<SerializableCookie> myCookies;
    CookieStore cookieStore = new BasicCookieStore();
    DefaultHttpClient hClient = getHttpClient(context);
    mContentResolver = context.getContentResolver();
    final String[] weeknames = { "rota_this_week", "rota_next_week" };

    long calendar_id = getCalendar(account);
    if (calendar_id == -1) {
        Log.e("CalendarSyncAdapter", "Unable to create HutSync event calendar");
        return;
    }

    try {
        myCookies = (ArrayList<SerializableCookie>) fromString(authtoken);
    } catch (final IOException e) {
        Log.e(TAG, "IOException when expanding authtoken", e);
        return;
    } catch (final ClassNotFoundException e) {
        Log.e(TAG, "ClassNotFoundException when expanding authtoken", e);
        return;
    }

    for (SerializableCookie cur_cookie : myCookies) {
        cookieStore.addCookie(cur_cookie.getCookie());
    }

    hClient.setCookieStore(cookieStore);
    Log.i(TAG, "Syncing to: " + SYNC_CONTACTS_URI);
    HttpGet httpget = new HttpGet(SYNC_CONTACTS_URI);
    final HttpResponse resp = hClient.execute(httpget);
    final String response = EntityUtils.toString(resp.getEntity());
    HashMap<Long, SyncEntry> localEvents = new HashMap<Long, SyncEntry>();
    ArrayList<Event> events = new ArrayList<Event>();
    Pattern p = Pattern.compile("background-color:(#[[a-f][A-F][0-9]]{6})");
    Pattern ps = Pattern
            .compile(".calendar-key span.(\\S+) \\{ background-color:(#[[a-f][A-F][0-9]]{6}); color:#fff; \\}");

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        //check we are still logged in
        //if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        //    Log.e(TAG, "Authentication exception in sending dirty contacts");
        //    throw new AuthenticationException();
        //}

        //if we are logged in
        Map<String, String> shift_types = new HashMap<String, String>();
        int length = weeknames.length;
        Document doc = Jsoup.parse(response);
        String full_name = doc.select("a[href*=" + account.name + "/profile]").first().text();

        AccountManager mAccountManager = AccountManager.get(context);
        Account[] the_accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
        boolean multiple_accounts = (the_accounts.length > 1);

        Elements the_styles = doc.select("style");
        for (Element the_style : the_styles) {
            String st_txt = the_style.html();
            Matcher ms = ps.matcher(st_txt);
            while (ms.find()) { // Find each match in turn; String can't do this.
                String cname = ms.group(1); // Access a submatch group; String can't do this.
                String ccol = ms.group(2);
                String rname = doc.select("span." + cname).first().text();
                Log.i(TAG, "LOOK: " + cname + ", " + ccol + ", " + rname);
                shift_types.put(ccol, rname);
            }
        }

        for (int w = 0; w < weeknames.length; w++) {

            Elements the_dates = doc.select("div.homepage div.accord-content table[id=" + weeknames[w]
                    + "] tr.heading th:not(.skipStyles)");
            //for (Element hidden : the_dates) { //0 is Mon, 6 is Sun
            Element the_date = the_dates.first(); //figure out the year for the Monday.
            String str_v = the_date.text();
            String[] str_sub = str_v.split(" ");
            str_sub[1] = str_sub[1].trim();
            String[] date_split = str_sub[1].split("/");
            Calendar c = Calendar.getInstance();
            int this_month = c.get(Calendar.MONTH) + 1;
            int monday_month = Integer.parseInt(date_split[1]);
            int this_year = c.get(Calendar.YEAR);
            int monday_year = this_year;
            if (this_month > monday_month) {
                monday_year++;
            } else if (this_month < monday_month) {
                monday_year--;
            }

            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
            Date date = new Date();
            if (str_v != null && !str_v.isEmpty()) {
                String this_date = str_sub[1] + "/" + monday_year; //we need to figure out the year - sometimes its next year

                try {
                    date = format.parse(this_date);
                } catch (Exception e) {
                    // TODO Auto-generated catch block  
                    e.printStackTrace();
                }
                Log.i(TAG, "Dates: " + this_date + " - " + date);
            }
            //}

            for (int i = 1; i < 8; ++i) { //1 is monday, 7 is sunday
                Elements hiddens = doc.select("div.homepage div.accord-content table[id=" + weeknames[w]
                        + "] td:eq(" + Integer.toString(i) + "):not(.skipStyles) div.timeElem");
                int add_days = i - 1;
                for (Element hidden : hiddens) {
                    String str = hidden.text();
                    if (str != null && !str.isEmpty()) {
                        String style = hidden.attr("style");
                        String bg_col = "";
                        Matcher m = p.matcher(style);
                        if (m.find()) {
                            bg_col = m.group(1); // Access a submatch group; String can't do this.
                        }

                        Log.i(TAG, "Time: " + str + "(" + bg_col + ")");
                        String ev_description = ""; //Location too?
                        if (multiple_accounts)
                            ev_description += full_name + "\n\n";
                        String[] times = str.split(" - ");
                        String[] start_time = times[0].split(":");
                        String[] end_time = times[1].split(":");
                        int add_start_hours = Integer.parseInt(start_time[0]);
                        int add_start_minutes = Integer.parseInt(start_time[1]);
                        int add_finish_hours = Integer.parseInt(end_time[0]);
                        int add_finish_minutes = Integer.parseInt(end_time[1]);
                        String ev_shiftType = "";
                        if (bg_col != null && !bg_col.isEmpty()) {
                            ev_shiftType = (String) shift_types.get(bg_col);
                        } else {
                            ev_shiftType = "Other";
                        }
                        String ev_title = ev_shiftType + " Shift";

                        c.setTime(date);
                        c.add(Calendar.DATE, add_days);
                        c.add(Calendar.HOUR_OF_DAY, add_start_hours);
                        c.add(Calendar.MINUTE, add_start_minutes);
                        Date startDate = c.getTime();
                        long ev_id = startDate.getTime();

                        c.setTime(date);
                        c.add(Calendar.DATE, add_days);
                        if (add_finish_hours < add_start_hours) { //shift rolls to next day
                            c.add(Calendar.HOUR_OF_DAY, 24);
                            ev_description += "Shift finishes at " + times[1] + " on the next day\n\n";
                        } else {
                            c.add(Calendar.HOUR_OF_DAY, add_finish_hours);
                            c.add(Calendar.MINUTE, add_finish_minutes);
                        }
                        Date endDate = c.getTime();

                        Event ev = new Event(ev_id, ev_title, startDate, endDate, ev_description, ev_shiftType);
                        events.add(ev);
                        Log.i(TAG, "Event: " + ev);
                    }
                }
            }
        }

        //next merge adjacent shifts
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        Event prev_event = null;
        for (Iterator<Event> it = events.iterator(); it.hasNext();) {
            Event cur_event = it.next();
            if (prev_event != null) {
                if (prev_event.getEndDate().compareTo(cur_event.getStartDate()) == 0) {
                    prev_event.setDescription(prev_event.getDescription() + "Merged consecutive shifts:\n"
                            + timeFormat.format(prev_event.getStartDate()) + " to "
                            + timeFormat.format(prev_event.getEndDate()) + " (" + prev_event.getShiftType()
                            + ")\n" + timeFormat.format(cur_event.getStartDate()) + " to "
                            + timeFormat.format(cur_event.getEndDate()) + " (" + cur_event.getShiftType()
                            + ")\n\n");
                    prev_event.setEndDate(cur_event.getEndDate()); //TODO: only merge if other + FOH/BOH, note times in new description
                    it.remove();
                }
            }
            prev_event = cur_event;
        }

        //next, load local events
        Cursor c1 = mContentResolver.query(
                Events.CONTENT_URI.buildUpon().appendQueryParameter(Events.ACCOUNT_NAME, account.name)
                        .appendQueryParameter(Events.ACCOUNT_TYPE, account.type).build(),
                new String[] { Events._ID, Events._SYNC_ID }, Events.CALENDAR_ID + "=?",
                new String[] { String.valueOf(calendar_id) }, null);
        while (c1 != null && c1.moveToNext()) {
            //if(is_full_sync) {
            //   deleteEvent(context, account, c1.getLong(0));
            //} else {
            SyncEntry entry = new SyncEntry();
            entry.raw_id = c1.getLong(0);
            localEvents.put(c1.getLong(1), entry);
            //}
        }
        c1.close();
        try {
            ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
            for (Event event : events) {

                if (localEvents.containsKey(Long.valueOf(event.getId()))) {
                    SyncEntry entry = localEvents.get(Long.valueOf(event.getId()));
                    operationList.add(updateEvent(calendar_id, account, event, entry.raw_id));
                } else {
                    operationList.add(updateEvent(calendar_id, account, event, -1));
                }

                if (operationList.size() >= 50) {
                    try {
                        mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    operationList.clear();
                }
            }

            if (operationList.size() > 0) {
                try {
                    mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return;
        }

    } else {
        Log.e(TAG, "Server error in sending dirty contacts: " + resp.getStatusLine());
        throw new IOException();
    }
}

From source file:com.money.manager.ex.datalayer.StockRepository.java

private List<Stock> getEntities(Cursor c) {
    List<Stock> result = new ArrayList<>();
    while (c.moveToNext()) {
        result.add(Stock.from(c));/*from  www.  ja  v  a 2  s  . c  om*/
    }
    c.close();

    return result;
}

From source file:com.android.unit_tests.CheckinProviderTest.java

@MediumTest
public void testStatsUpdate() {
    ContentResolver r = getContext().getContentResolver();

    // First, delete any existing data associated with the TEST tag.
    Uri uri = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 0, 0);
    assertNotNull(uri);//from w  ww .  ja  v a  2 s.c o  m
    assertEquals(1, r.delete(uri, null, null));
    assertFalse(r.query(uri, null, null, null, null).moveToNext());

    // Now, add a known quantity to the TEST tag.
    Uri u2 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 1, 0.5);
    assertFalse(uri.equals(u2));

    Cursor c = r.query(u2, null, null, null, null);
    assertTrue(c.moveToNext());
    assertEquals(1, c.getInt(c.getColumnIndex(Checkin.Stats.COUNT)));
    assertEquals(0.5, c.getDouble(c.getColumnIndex(Checkin.Stats.SUM)));
    assertFalse(c.moveToNext()); // Only one.

    // Add another known quantity to TEST (should sum with the first).
    Uri u3 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 2, 1.0);
    assertEquals(u2, u3);
    c.requery();
    assertTrue(c.moveToNext());
    assertEquals(3, c.getInt(c.getColumnIndex(Checkin.Stats.COUNT)));
    assertEquals(1.5, c.getDouble(c.getColumnIndex(Checkin.Stats.SUM)));
    assertFalse(c.moveToNext()); // Only one.

    // Now subtract the values; the whole row should disappear.
    Uri u4 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, -3, -1.5);
    assertNull(u4);
    c.requery();
    assertFalse(c.moveToNext()); // Row has been deleted.
    c.close();
}