Example usage for android.database.sqlite SQLiteDatabase query

List of usage examples for android.database.sqlite SQLiteDatabase query

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase query.

Prototype

public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy,
        String having, String orderBy) 

Source Link

Document

Query the given table, returning a Cursor over the result set.

Usage

From source file:com.odoo.core.orm.OModel.java

public int count(String selection, String[] args) {
    int count = 0;
    SQLiteDatabase db = getReadableDatabase();
    Cursor cr = db.query(getTableName(), new String[] { "count(*)" }, selection, args, null, null, null);
    try {/*from   w  w  w  . j a v  a2 s  . com*/
        cr.moveToFirst();
        count = cr.getInt(0);
    } finally {
        cr.close();
    }
    return count;
}

From source file:com.odoo.core.orm.OModel.java

public int selectRowId(String selection, String[] args) {
    int row_id = INVALID_ROW_ID;
    SQLiteDatabase db = getReadableDatabase();
    Cursor cr = db.query(getTableName(), new String[] { OColumn.ROW_ID }, selection, args, null, null, null);
    try {/*from www.ja  va  2s .com*/
        if (cr.moveToFirst()) {
            row_id = cr.getInt(0);
        }
    } finally {
        cr.close();
    }
    return row_id;
}

From source file:com.test.onesignal.GenerateNotificationRunner.java

@Test
public void shouldGenerate2BasicGroupNotifications() throws Exception {
    // Make sure the notification got posted and the content is correct.
    Bundle bundle = getBaseNotifBundle();
    bundle.putString("grp", "test1");
    NotificationBundleProcessor_ProcessFromGCMIntentService(blankActivity, bundle, null);

    Map<Integer, PostedNotification> postedNotifs = ShadowRoboNotificationManager.notifications;
    Assert.assertEquals(2, postedNotifs.size());

    // Test summary notification
    Iterator<Map.Entry<Integer, PostedNotification>> postedNotifsIterator = postedNotifs.entrySet().iterator();
    PostedNotification postedNotification = postedNotifsIterator.next().getValue();

    Assert.assertEquals(notifMessage, postedNotification.getShadow().getContentText());
    Assert.assertEquals(Notification.FLAG_GROUP_SUMMARY,
            postedNotification.notif.flags & Notification.FLAG_GROUP_SUMMARY);

    // Test Android Wear notification
    postedNotification = postedNotifsIterator.next().getValue();
    Assert.assertEquals(notifMessage, postedNotification.getShadow().getContentText());
    Assert.assertEquals(0, postedNotification.notif.flags & Notification.FLAG_GROUP_SUMMARY);
    // Badge count should only be one as only one notification is visible in the notification area.
    Assert.assertEquals(1, ShadowBadgeCountUpdater.lastCount);

    // Should be 2 DB entries (summary and individual)
    SQLiteDatabase readableDb = OneSignalDbHelper.getInstance(blankActivity).getReadableDatabase();
    Cursor cursor = readableDb.query(NotificationTable.TABLE_NAME, null, null, null, null, null, null);
    Assert.assertEquals(2, cursor.getCount());
    cursor.close();/*from w ww  . j  a  va  2 s  .  c  o  m*/

    // Add another notification to the group.
    ShadowRoboNotificationManager.notifications.clear();
    bundle = new Bundle();
    bundle.putString("alert", "Notif test 2");
    bundle.putString("custom", "{\"i\": \"UUID2\"}");
    bundle.putString("grp", "test1");
    NotificationBundleProcessor_ProcessFromGCMIntentService(blankActivity, bundle, null);

    postedNotifs = ShadowRoboNotificationManager.notifications;
    Assert.assertEquals(2, postedNotifs.size());
    Assert.assertEquals(2, ShadowBadgeCountUpdater.lastCount);

    postedNotifsIterator = postedNotifs.entrySet().iterator();
    postedNotification = postedNotifsIterator.next().getValue();
    Assert.assertEquals("2 new messages", postedNotification.getShadow().getContentText());
    Assert.assertEquals(Notification.FLAG_GROUP_SUMMARY,
            postedNotification.notif.flags & Notification.FLAG_GROUP_SUMMARY);

    // Test Android Wear notification
    postedNotification = postedNotifsIterator.next().getValue();
    Assert.assertEquals("Notif test 2", postedNotification.getShadow().getContentText());
    Assert.assertEquals(0, postedNotification.notif.flags & Notification.FLAG_GROUP_SUMMARY);

    // Should be 3 DB entries (summary and 2 individual)
    readableDb = OneSignalDbHelper.getInstance(blankActivity).getReadableDatabase();
    cursor = readableDb.query(NotificationTable.TABLE_NAME, null, null, null, null, null, null);
    Assert.assertEquals(3, cursor.getCount());

    // Open summary notification
    postedNotifsIterator = postedNotifs.entrySet().iterator();
    postedNotification = postedNotifsIterator.next().getValue();
    Intent intent = createOpenIntent(postedNotification.id, bundle).putExtra("summary", "test1");
    NotificationOpenedProcessor_processFromContext(blankActivity, intent);
    Assert.assertEquals(0, ShadowBadgeCountUpdater.lastCount);
    // 2 open calls should fire.
    Assert.assertEquals(2, ShadowOneSignalRestClient.networkCallCount);
    ShadowRoboNotificationManager.notifications.clear();

    // Send 3rd notification
    bundle = new Bundle();
    bundle.putString("alert", "Notif test 3");
    bundle.putString("custom", "{\"i\": \"UUID3\"}");
    bundle.putString("grp", "test1");
    NotificationBundleProcessor_ProcessFromGCMIntentService(blankActivity, bundle, null);

    postedNotifsIterator = postedNotifs.entrySet().iterator();
    postedNotification = postedNotifsIterator.next().getValue();
    Assert.assertEquals("Notif test 3", postedNotification.getShadow().getContentText());
    Assert.assertEquals(Notification.FLAG_GROUP_SUMMARY,
            postedNotification.notif.flags & Notification.FLAG_GROUP_SUMMARY);
    Assert.assertEquals(1, ShadowBadgeCountUpdater.lastCount);
    cursor.close();
}

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();/*from  w w w. j  a va 2 s  .  c om*/

    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:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<>(15);
    final Set<Long> uploadedStats = new HashSet<>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor pendingUploadsCursor = null;
    try {//from   w w w .j  a v  a  2 s .  c  om
        pendingUploadsCursor = db.query("daily_stat_testing",
                new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g",
                        "free_mobile_femtocell", "sync" },
                "stat_timestamp>=? AND stat_timestamp<?",
                new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
        while (pendingUploadsCursor.moveToNext()) {
            final long d = pendingUploadsCursor.getLong(0);
            final int sync = pendingUploadsCursor.getInt(6);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = pendingUploadsCursor.getInt(1);
                s.freeMobile = pendingUploadsCursor.getInt(2);
                s.freeMobile3G = pendingUploadsCursor.getInt(3);
                s.freeMobile4G = pendingUploadsCursor.getInt(4);
                s.freeMobileFemtocell = pendingUploadsCursor.getInt(5);
                stats.put(d, s);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (pendingUploadsCursor != null)
                pendingUploadsCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("free_mobile_3g", s.freeMobile3G);
                cv.put("free_mobile_4g", s.freeMobile4G);
                cv.put("free_mobile_femtocell", s.freeMobileFemtocell);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat_testing", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat_testing", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
            json.put("timeOnFreeMobile3g", s.freeMobile3G);
            json.put("timeOnFreeMobile4g", s.freeMobile4G);
            json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncServiceTesting.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat_testing", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

From source file:com.odoo.core.orm.OModel.java

public List<ODataRow> selectManyToManyRecords(String[] projection, String column_name, int row_id) {
    OColumn column = getColumn(column_name);
    OModel rel_model = createInstance(column.getType());
    String table = getTableName() + "_" + rel_model.getTableName() + "_rel";
    String base_column = getTableName() + "_id";
    String rel_column = rel_model.getTableName() + "_id";

    // Getting relation table ids
    List<String> ids = new ArrayList<>();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cr = null;/*from w  w w .  j a v a 2s . c om*/
    try {
        cr = db.query(table, new String[] { rel_column }, base_column + "=?", new String[] { row_id + "" },
                null, null, null);
        if (cr.moveToFirst()) {
            do {
                ids.add(cr.getInt(0) + "");
            } while (cr.moveToNext());
        }
    } finally {
        if (cr != null) {
            cr.close();
        }
    }
    List<ODataRow> data = rel_model.select(projection,
            OColumn.ROW_ID + " IN (" + StringUtils.repeat(" ?, ", ids.size() - 1) + " ?)",
            ids.toArray(new String[ids.size()]));
    rel_model.close();
    return data;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public Cursor getMatchingRecipes(String match, String sortBy) {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        // We have to match like this because of Android bug 3153
        String fixed = "%" + match + "%";
        return db.query(RECIPES_TABLE, RECIPES_FIELDS, createLikePattern(), new String[] { fixed, fixed }, null,
                null, sortBy);//from   w w  w.  jav  a 2 s.  co m
    }
}

From source file:org.runnerup.export.SyncManager.java

public Set<String> feedSynchronizersSet(Context ctx) {
    Set<String> set = new HashSet<String>();
    String[] from = new String[] { "_id", DB.ACCOUNT.NAME, DB.ACCOUNT.ENABLED, DB.ACCOUNT.AUTH_CONFIG,
            DB.ACCOUNT.FLAGS };//from  w  w w  .  ja v a 2  s  .  co m

    SQLiteDatabase db = DBHelper.getReadableDatabase(ctx);
    Cursor c = db.query(DB.ACCOUNT.TABLE, from, null, null, null, null, null);
    if (c.moveToFirst()) {
        do {
            final ContentValues tmp = DBHelper.get(c);
            final Synchronizer synchronizer = add(tmp);
            final String name = tmp.getAsString(DB.ACCOUNT.NAME);
            final long flags = tmp.getAsLong(DB.ACCOUNT.FLAGS);
            if (isConfigured(name) && Bitfield.test(flags, DB.ACCOUNT.FLAG_FEED)
                    && synchronizer.checkSupport(Synchronizer.Feature.FEED)) {
                set.add(name);
            }
        } while (c.moveToNext());
    }
    c.close();
    DBHelper.closeDB(db);
    return set;
}

From source file:org.frc836.database.DBSyncService.java

private void sendPits() {
    // TODO could be abstracted further
    String[] pitProjection = PitStats.getNewPitStats().getProjection();
    synchronized (ScoutingDBHelper.lock) {

        SQLiteDatabase db = ScoutingDBHelper.getInstance().getReadableDatabase();

        Cursor c = db.query(PitStats.TABLE_NAME, pitProjection, PitStats.COLUMN_NAME_INVALID + "<>0", null,
                null, null, null);/*from   ww w  .  j a  v a  2 s  .  c om*/
        try {

            synchronized (outgoing) {

                if (c.moveToFirst())
                    do {
                        Map<String, String> args = new HashMap<String, String>();
                        args.put("password", password);
                        args.put("type", "pits");
                        args.put("version", version);
                        for (int i = 0; i < pitProjection.length; i++) {
                            args.put(pitProjection[i], c.getString(c.getColumnIndex(pitProjection[i])));
                        }
                        outgoing.add(args);
                    } while (c.moveToNext());
            }
        } finally {
            if (c != null)
                c.close();
            ScoutingDBHelper.getInstance().close();
        }
    }
}

From source file:org.frc836.database.DBSyncService.java

private void sendMatches() {
    // TODO could be abstracted further?

    // repurposed invalid flag for marking fields that need to be uploaded
    String[] matchProjection = MatchStatsStruct.getNewMatchStats().getProjection();

    synchronized (ScoutingDBHelper.lock) {

        SQLiteDatabase db = ScoutingDBHelper.getInstance().getReadableDatabase();

        Cursor c = db.query(MatchStatsStruct.TABLE_NAME, matchProjection,
                MatchStatsStruct.COLUMN_NAME_INVALID + "<>0", null, null, null, null);
        try {/*from   w w  w . j  a v a  2  s.c  om*/

            synchronized (outgoing) {

                if (c.moveToFirst())
                    do {
                        Map<String, String> args = new HashMap<String, String>();
                        args.put("password", password);
                        args.put("type", "match");
                        args.put("version", version);
                        for (int i = 0; i < matchProjection.length; i++) {
                            args.put(matchProjection[i], c.getString(c.getColumnIndex(matchProjection[i])));
                        }
                        outgoing.add(args);
                    } while (c.moveToNext());
            }
        } finally {
            if (c != null)
                c.close();
            ScoutingDBHelper.getInstance().close();
        }

    }
}