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:Main.java

/**
 * Retourner la liste des calendriers/* w  w w .j  a v a2  s.c om*/
 * 
 * @return Liste des calendriers
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Map<Integer, String> getCalendars(ContentResolver contentResolver) {
    Map<Integer, String> calendars = new HashMap<Integer, String>();
    String[] projection;
    Uri calendarUri;
    Cursor cursor;
    String accessLevelCol;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        calendarUri = CalendarContract.Calendars.CONTENT_URI;
        projection = new String[] { CalendarContract.Calendars._ID,
                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME };
        accessLevelCol = CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL;
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        calendarUri = Uri.parse("content://com.android.calendar/calendars");
        projection = new String[] { "_id", "displayname" };
        accessLevelCol = "ACCESS_LEVEL";
    } else {
        calendarUri = Uri.parse("content://calendar/calendars");
        projection = new String[] { "_id", "displayname" };
        accessLevelCol = "ACCESS_LEVEL";
    }

    cursor = contentResolver.query(calendarUri, projection, accessLevelCol + "=700", null, null);

    if (cursor != null && cursor.moveToFirst()) {
        while (cursor.isAfterLast() == false) {
            calendars.put(cursor.getInt(0), cursor.getString(1));
            cursor.moveToNext();
        }
        cursor.close();
    }

    return calendars;
}

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

public static List<Pair<String, List<Long>>> findDupes(Collection col, String fieldName, String search) {
    // limit search to notes with applicable field name
    if (search != null && search.length() > 0) {
        search = "(" + search + ") ";
    }/*  ww w . j  av  a2  s.  c o  m*/
    search += "'" + fieldName + ":*'";
    // go through notes

    String sql = "select id, mid, flds from notes where id in "
            + Utils.ids2str(col.findNotes(search).toArray(new Long[] {}));
    Cursor cur = null;
    Map<Long, Integer> fields = new HashMap<Long, Integer>();
    Map<String, List<Long>> vals = new HashMap<String, List<Long>>();
    List<Pair<String, List<Long>>> dupes = new ArrayList<Pair<String, List<Long>>>();
    try {
        cur = col.getDb().getDatabase().rawQuery(sql, null);
        while (cur.moveToNext()) {
            long nid = cur.getLong(0);
            long mid = cur.getLong(1);
            String[] flds = Utils.splitFields(cur.getString(2));
            // inlined ordForMid(mid)
            if (!fields.containsKey(mid)) {
                JSONObject model = col.getModels().get(mid);
                fields.put(mid, col.getModels().fieldMap(model).get(fieldName).first);
            }
            String val = flds[fields.get(mid)];
            // empty does not count as duplicate
            if (val.equals("")) {
                continue;
            }
            if (!vals.containsKey(val)) {
                vals.put(val, new ArrayList<Long>());
            }
            vals.get(val).add(nid);
            if (vals.get(val).size() == 2) {
                dupes.add(new Pair<String, List<Long>>(val, vals.get(val)));
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    return dupes;
}

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

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

    HashSet<String> readSet = null;

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

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

    if (count > 0) {
        readSet = new HashSet<String>(c.getCount());
        c.moveToFirst();/*from   w  w  w. j a  v a 2  s . co m*/

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

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

    if (readSet == null)
        readSet = new HashSet<String>(0);
    return readSet;
}

From source file:com.ichi2.libanki.Finder.java

public static int findReplace(Collection col, List<Long> nids, String src, String dst, boolean isRegex,
        String field, boolean fold) {
    Map<Long, Integer> mmap = new HashMap<Long, Integer>();
    if (field != null) {
        try {// w  ww. jav  a  2  s  .  c o  m
            for (JSONObject m : col.getModels().all()) {
                JSONArray flds = m.getJSONArray("flds");
                for (int fi = 0; fi < flds.length(); ++fi) {
                    JSONObject f = flds.getJSONObject(fi);
                    if (f.getString("name").equals(field)) {
                        mmap.put(m.getLong("id"), f.getInt("ord"));
                    }
                }
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        if (mmap.isEmpty()) {
            return 0;
        }
    }
    // find and gather replacements
    if (!isRegex) {
        src = Pattern.quote(src);
    }
    if (fold) {
        src = "(?i)" + src;
    }
    Pattern regex = Pattern.compile(src);

    ArrayList<Object[]> d = new ArrayList<Object[]>();
    String snids = Utils.ids2str(nids);
    nids = new ArrayList<Long>();
    Cursor cur = null;
    try {
        cur = col.getDb().getDatabase().rawQuery("select id, mid, flds from notes where id in " + snids, null);
        while (cur.moveToNext()) {
            String flds = cur.getString(2);
            String origFlds = flds;
            // does it match?
            String[] sflds = Utils.splitFields(flds);
            if (field != null) {
                long mid = cur.getLong(1);
                if (!mmap.containsKey(mid)) {
                    // note doesn't have that field
                    continue;
                }
                int ord = mmap.get(mid);
                sflds[ord] = regex.matcher(sflds[ord]).replaceAll(dst);
            } else {
                for (int i = 0; i < sflds.length; ++i) {
                    sflds[i] = regex.matcher(sflds[i]).replaceAll(dst);
                }
            }
            flds = Utils.joinFields(sflds);
            if (!flds.equals(origFlds)) {
                long nid = cur.getLong(0);
                nids.add(nid);
                d.add(new Object[] { flds, Utils.intNow(), col.usn(), nid }); // order based on query below
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (d.isEmpty()) {
        return 0;
    }
    // replace
    col.getDb().executeMany("update notes set flds=?,mod=?,usn=? where id=?", d);
    long[] pnids = Utils.toPrimitive(nids);
    col.updateFieldCache(pnids);
    col.genCards(pnids);
    return d.size();
}

From source file:com.liferay.alerts.database.DatabaseHelper.java

private void _convertMessageToJSONObject(SQLiteDatabase database) {
    StringBuilder select = new StringBuilder();

    select.append("SELECT ");
    select.append(Alert.ID);/*ww w  .  j a  v  a 2 s  .co  m*/
    select.append(", ");
    select.append(Alert.PAYLOAD);
    select.append(" FROM ");
    select.append(AlertDAO.TABLE_NAME);

    Cursor cursor = database.rawQuery(select.toString(), null);

    while (cursor.moveToNext()) {
        try {
            long id = cursor.getLong(cursor.getColumnIndex(Alert.ID));
            String payload = cursor.getString(cursor.getColumnIndex(Alert.PAYLOAD));

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(Alert.MESSAGE, payload);

            ContentValues values = new ContentValues();
            values.put(Alert.PAYLOAD, jsonObject.toString());

            StringBuilder sb = new StringBuilder();

            sb.append(Alert.ID);
            sb.append(CharPool.SPACE);
            sb.append("= ?");

            String whereClause = sb.toString();

            String[] whereArgs = { String.valueOf(id) };

            database.update(AlertDAO.TABLE_NAME, values, whereClause, whereArgs);
        } catch (JSONException je) {
            Log.e(_TAG, "Couldn't convert message.", je);
        }
    }
}

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

public static HashSet<String> getBannedTrolls(Context context) {

    HashSet<String> bannedTrolls = null;

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    String q = "SELECT name FROM banned_users WHERE bandisabled=0";

    Cursor c = dbwrite.rawQuery(q, null);

    int count = c.getCount();
    if (count > 0) {

        bannedTrolls = new HashSet<String>(c.getColumnCount());
        c.moveToFirst();/* w  w  w.j a  v  a 2 s .co  m*/

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

    c.close();
    dbwrite.close();
    db.close();

    if (bannedTrolls == null)
        bannedTrolls = new HashSet<String>(0);
    return bannedTrolls;
}

From source file:com.ichi2.libanki.Finder.java

/**
 * @return List of Pair("dupestr", List[nids])
 *//*from   www  . ja  v a 2s  .  c om*/
public static List<Pair<String, List<Long>>> findDupes(Collection col, String fieldName, String search) {
    // limit search to notes with applicable field name
    if (!TextUtils.isEmpty(search)) {
        search = "(" + search + ") ";
    }
    search += "'" + fieldName + ":*'";
    // go through notes
    Map<String, List<Long>> vals = new HashMap<String, List<Long>>();
    List<Pair<String, List<Long>>> dupes = new ArrayList<Pair<String, List<Long>>>();
    Map<Long, Integer> fields = new HashMap<Long, Integer>();
    Cursor cur = null;
    try {
        cur = col.getDb().getDatabase().rawQuery(
                "select id, mid, flds from notes where id in " + Utils.ids2str(col.findNotes(search)), null);
        while (cur.moveToNext()) {
            long nid = cur.getLong(0);
            long mid = cur.getLong(1);
            String[] flds = Utils.splitFields(cur.getString(2));
            Integer ord = ordForMid(col, fields, mid, fieldName);
            if (ord == null) {
                continue;
            }
            String val = flds[fields.get(mid)];
            val = Utils.stripHTMLMedia(val);
            // empty does not count as duplicate
            if (TextUtils.isEmpty(val)) {
                continue;
            }
            if (!vals.containsKey(val)) {
                vals.put(val, new ArrayList<Long>());
            }
            vals.get(val).add(nid);
            if (vals.get(val).size() == 2) {
                dupes.add(new Pair<String, List<Long>>(val, vals.get(val)));
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    return dupes;
}

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

public static HashSet<String> getBannedThreads(String group, Context context) {

    HashSet<String> bannedThreads = null;

    int groupid = getGroupIdFromName(group, context);

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

    String q = "SELECT clean_subject FROM banned_threads WHERE subscribed_group_id=" + groupid
            + " AND bandisabled=0";

    Cursor c = dbread.rawQuery(q, null);
    if (c.getCount() > 0) {

        bannedThreads = new HashSet<String>(c.getCount());
        c.moveToFirst();//from   w w w . ja  va 2 s . c om

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

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

    if (bannedThreads == null)
        bannedThreads = new HashSet<String>(0);
    return bannedThreads;
}

From source file:cc.vileda.sipgatesync.contacts.SipgateContactSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*  ww  w .j a v a  2 s.  c o m*/
    Log.d("SipgateContactSyncAdapt", "onPerformSync()");
    AccountManager accountManager = AccountManager.get(getContext());
    final String oauth = accountManager.peekAuthToken(account, "oauth");
    Log.d("SipgateContactSyncAdapt", oauth == null ? "NO oauth!" : "Got token");
    final JSONArray users = SipgateApi.getContacts(oauth);
    assert users != null;

    Log.d("SipgateContactSyncAdapt", String.format("fetched %d contacts", users.length()));

    Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon()
            .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, account.name)
            .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type).build();
    Cursor c1 = mContentResolver.query(rawContactUri, null, null, null, null);
    Map<String, Boolean> localContacts = new HashMap<>();
    while (c1 != null && c1.moveToNext()) {
        localContacts.put(c1.getString(c1.getColumnIndex(ContactsContract.RawContacts.SOURCE_ID)), false);
    }

    for (int i = 0; i < users.length(); i++) {
        try {
            final JSONObject user = users.getJSONObject(i);
            final String id = user.getString("uuid");
            if (localContacts.containsKey(id)) {
                localContacts.put(id, true);
                continue;
            }
            final String firstname = user.getString("firstname");

            final JSONArray emails = user.getJSONArray("emails");
            final JSONArray mobile = user.getJSONArray("mobile");
            final JSONArray landline = user.getJSONArray("landline");
            final JSONArray fax = user.getJSONArray("fax");

            Log.d("SipgateContactSyncAdapt", String.format("adding id: %s %s", id, firstname));

            ContactManager.addContact(id, firstname, user.getString("lastname"), jsonArrayToList(emails),
                    jsonArrayToList(mobile), jsonArrayToList(landline), jsonArrayToList(fax), mContentResolver,
                    account.name);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    for (Map.Entry<String, Boolean> contact : localContacts.entrySet()) {
        if (!contact.getValue()) {
            ContactManager.deleteContact(contact.getKey(), mContentResolver, account.name);
        }
    }
}

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

public static HashSet<String> getStarredSubjectsSet(Context context) {
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();
    Cursor c;

    String query = "SELECT clean_subject FROM starred_threads";
    c = dbread.rawQuery(query, null);/*ww  w  .  j  a  v  a  2  s  .c om*/
    HashSet<String> set = new HashSet<String>(c.getCount());

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

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