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:edu.cens.loci.provider.LociDbUtils.java

public ArrayList<LociPlace> getPlaces(String selection) {

    ArrayList<LociPlace> places = new ArrayList<LociPlace>();

    final SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String orderBy = Places.PLACE_NAME + " ASC";

    Cursor cursor = db.query(Tables.PLACES, null, selection, null, null, null, orderBy);

    if (cursor.moveToFirst()) {
        do {/*from   w  w w  .j  a v  a  2s .co  m*/
            LociPlace place = new LociPlace();
            place.placeId = cursor.getLong(cursor.getColumnIndex(Places._ID));
            place.name = cursor.getString(cursor.getColumnIndex(Places.PLACE_NAME));
            place.state = cursor.getInt(cursor.getColumnIndex(Places.PLACE_STATE));
            place.type = cursor.getInt(cursor.getColumnIndex(Places.PLACE_TYPE));
            place.entry = cursor.getInt(cursor.getColumnIndex(Places.ENTRY));
            place.entryTime = cursor.getLong(cursor.getColumnIndex(Places.ENTRY_TIME));
            place.registerTime = cursor.getLong(cursor.getColumnIndex(Places.REGISTER_TIME));

            place.wifis = getWifiFingerprint(place.placeId);
            place.areas = getGpsCircleArea(place.placeId);

            if (place.state == Places.STATE_DELETED)
                continue;

            places.add(place);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return places;
}

From source file:com.kyleszombathy.sms_scheduler.Home.java

/**Retrieves values from sql Database and store locally*/
private Cursor dbRetrieveContactData(SQLDbHelper mDbHelper, SQLiteDatabase db) {
    Cursor cursor = null;//from   w  ww .  j  a  v  a  2  s.  c o m

    String[] projection = { SQLContract.MessageEntry.NAME, SQLContract.MessageEntry.MESSAGE,
            SQLContract.MessageEntry.YEAR, SQLContract.MessageEntry.MONTH, SQLContract.MessageEntry.DAY,
            SQLContract.MessageEntry.HOUR, SQLContract.MessageEntry.MINUTE,
            SQLContract.MessageEntry.ALARM_NUMBER, SQLContract.MessageEntry.PHOTO_URI,
            SQLContract.MessageEntry.PHONE };

    // Sort the contact data by date/time, then by Name, then by Message Content
    String sortOrder = SQLContract.MessageEntry.DATETIME + " ASC, " + SQLContract.MessageEntry.NAME + " ASC, "
            + SQLContract.MessageEntry.MESSAGE + " ASC";
    String selection = SQLContract.MessageEntry.ARCHIVED + " LIKE ?";
    String[] selectionArgs = { String.valueOf(0) };

    try {
        cursor = db.query(SQLContract.MessageEntry.TABLE_NAME, // The table to query
                projection, // The columns to return
                selection, // The columns for the WHERE clause
                selectionArgs, // The values for the WHERE clause
                null, // don't group the rows
                null, // don't filter by row groups
                sortOrder // The sort order
        );
    } catch (Exception e) {
        Log.e(TAG, "dbRetrieveContactData: Retrieve encountered exception", e);
    }
    if (cursor != null) {
        Log.i(TAG,
                "dbRetrieveContactData: Retrieve successful. Found " + cursor.getCount() + " contact entries");
    }

    return cursor;
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

protected boolean Sync(String service, String scope, String params) {
    final Date start = new Date();
    boolean hasError = false;
    if (params == null)
        params = "";
    final SQLiteDatabase db = mDB.getWritableDatabase();
    final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>();

    final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params);
    final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params);
    final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob);
    String serverBlob = null;//from w  ww .  j  ava 2 s  . c  o  m
    Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?",
            new String[] { scopeServerBlob }, null, null, null);
    final String originalBlob;
    if (cur.moveToFirst()) {
        originalBlob = serverBlob = cur.getString(0);
    } else {
        originalBlob = null;
    }
    cur.close();
    db.beginTransaction();
    try {
        boolean nochanges = false;
        if (serverBlob != null) {
            nochanges = !contentHelper.hasDirtTable(db, scope);
        }
        boolean resolve = false;
        final Metadata meta = new Metadata();
        final HashMap<String, Object> vals = new HashMap<String, Object>();
        final ContentValues cv = new ContentValues(2);
        JsonFactory jsonFactory = new JsonFactory();
        JsonToken current = null;
        String name = null;
        boolean moreChanges = false;
        boolean forceMoreChanges = false;
        do {
            final int requestMethod;
            final String serviceRequestUrl;
            final ContentProducer contentProducer;

            if (serverBlob != null) {
                requestMethod = HTTP_POST;
                if (nochanges) {
                    serviceRequestUrl = download;
                } else {
                    serviceRequestUrl = upload;
                    forceMoreChanges = true;
                }
                contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges,
                        notifyTableInfo, contentHelper);
                nochanges = true;
            } else {
                requestMethod = HTTP_GET;
                serviceRequestUrl = download;
                contentProducer = null;

            }
            if (moreChanges) {
                db.beginTransaction();
            }

            Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer);
            if (result.getStatus() == HttpStatus.SC_OK) {
                final JsonParser jp = jsonFactory.createParser(result.getInputStream());

                jp.nextToken(); // skip ("START_OBJECT(d) expected");
                jp.nextToken(); // skip ("FIELD_NAME(d) expected");
                if (jp.nextToken() != JsonToken.START_OBJECT)
                    throw new Exception("START_OBJECT(d - object) expected");
                while (jp.nextToken() != JsonToken.END_OBJECT) {
                    name = jp.getCurrentName();
                    if (_.__sync.equals(name)) {
                        current = jp.nextToken();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            name = jp.getCurrentName();
                            current = jp.nextToken();
                            if (_.serverBlob.equals(name)) {
                                serverBlob = jp.getText();
                            } else if (_.moreChangesAvailable.equals(name)) {
                                moreChanges = jp.getBooleanValue() || forceMoreChanges;
                                forceMoreChanges = false;
                            } else if (_.resolveConflicts.equals(name)) {
                                resolve = jp.getBooleanValue();
                            }
                        }
                    } else if (_.results.equals(name)) {
                        if (jp.nextToken() != JsonToken.START_ARRAY)
                            throw new Exception("START_ARRAY(results) expected");
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            meta.isDeleted = false;
                            meta.tempId = null;
                            vals.clear();
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                name = jp.getCurrentName();
                                current = jp.nextToken();
                                if (current == JsonToken.VALUE_STRING) {
                                    vals.put(name, jp.getText());
                                } else if (current == JsonToken.VALUE_NUMBER_INT) {
                                    vals.put(name, jp.getLongValue());
                                } else if (current == JsonToken.VALUE_NUMBER_FLOAT) {
                                    vals.put(name, jp.getDoubleValue());
                                } else if (current == JsonToken.VALUE_FALSE) {
                                    vals.put(name, 0L);
                                } else if (current == JsonToken.VALUE_TRUE) {
                                    vals.put(name, 1L);
                                } else if (current == JsonToken.VALUE_NULL) {
                                    vals.put(name, null);
                                } else {
                                    if (current == JsonToken.START_OBJECT) {
                                        if (_.__metadata.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.uri.equals(name)) {
                                                    meta.uri = jp.getText();
                                                } else if (_.type.equals(name)) {
                                                    meta.type = jp.getText();
                                                } else if (_.isDeleted.equals(name)) {
                                                    meta.isDeleted = jp.getBooleanValue();
                                                } else if (_.tempId.equals(name)) {
                                                    meta.tempId = jp.getText();
                                                }
                                            }
                                        } else if (_.__syncConflict.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.isResolved.equals(name)) {
                                                } else if (_.conflictResolution.equals(name)) {
                                                } else if (_.conflictingChange.equals(name)) {
                                                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                        name = jp.getCurrentName();
                                                        current = jp.nextToken();
                                                        if (current == JsonToken.START_OBJECT) {
                                                            if (_.__metadata.equals(name)) {
                                                                while (jp.nextToken() != JsonToken.END_OBJECT) {

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // resolve conf

                                        } else if (_.__syncError.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                            }
                                        }
                                    }
                                }
                            }
                            TableInfo tab = contentHelper.getTableFromType(meta.type);
                            if (meta.isDeleted) {
                                tab.DeleteWithUri(meta.uri, db);
                            } else {
                                tab.SyncJSON(vals, meta, db);
                            }
                            if (!notifyTableInfo.contains(tab))
                                notifyTableInfo.add(tab);
                        }
                    }
                }
                jp.close();
                if (!hasError) {
                    cv.clear();
                    cv.put(BlobsTable.C_NAME, scopeServerBlob);
                    cv.put(BlobsTable.C_VALUE, serverBlob);
                    cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
                    cv.put(BlobsTable.C_STATE, 0);
                    db.replace(BlobsTable.NAME, null, cv);
                    db.setTransactionSuccessful();
                    db.endTransaction();
                    if (DEBUG) {
                        Log.d(TAG, "CP-Sync: commit changes");
                    }
                    final ContentResolver cr = getContext().getContentResolver();
                    for (TableInfo t : notifyTableInfo) {
                        final Uri nu = contentHelper.getDirUri(t.name, false);
                        cr.notifyChange(nu, null, false);
                        // false - do not force sync cause we are in sync
                        if (DEBUG) {
                            Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu);
                        }

                        for (String n : t.notifyUris) {
                            cr.notifyChange(Uri.parse(n), null, false);
                            if (DEBUG) {
                                Log.d(TAG, "+uri: " + n);
                            }
                        }
                    }
                    notifyTableInfo.clear();
                }
            } else {
                if (DEBUG) {
                    Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus());
                }
                hasError = true;
                break;
            }
        } while (moreChanges);
    } catch (final ConnectTimeoutException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ConnectTimeoutException", e);
        }
    } catch (final IOException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } catch (final ParseException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    } catch (final Exception e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    }
    if (hasError) {
        db.endTransaction();
        ContentValues cv = new ContentValues();
        cv.put(BlobsTable.C_NAME, scopeServerBlob);
        cv.put(BlobsTable.C_VALUE, originalBlob);
        cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
        cv.put(BlobsTable.C_STATE, -1);
        db.replace(BlobsTable.NAME, null, cv);
    }
    /*-if (!hasError) {
    final ContentValues cv = new ContentValues(2);
     cv.put(BlobsTable.C_NAME, scopeServerBlob);
     cv.put(BlobsTable.C_VALUE, serverBlob);
     db.replace(BlobsTable.NAME, null, cv);
     db.setTransactionSuccessful();
    }
    db.endTransaction();
    if (!hasError) {
     for (String t : notifyTableInfo) {
    getContext().getContentResolver().notifyChange(getDirUri(t),
          null);
     }
    }*/
    if (DEBUG) {
        Helpers.LogInfo(start);
    }
    return !hasError;
}

From source file:com.openerp.orm.ORM.java

/**
 * Checks for record.//from w  w w  .  j  a  v a 2  s .c o  m
 * 
 * @param db
 *            the db
 * @param id
 *            the id
 * @return true, if successful
 */
public boolean hasRecord(BaseDBHelper db, int id) {
    SQLiteDatabase dbHelper = getWritableDatabase();
    String where = " id = " + id + " AND oea_name = '" + user_name + "'";
    Cursor cursor = dbHelper.query(modelToTable(db.getModelName()), new String[] { "*" }, where, null, null,
            null, null);
    boolean flag = false;
    if (cursor.moveToFirst()) {
        flag = true;
    }
    cursor.close();
    dbHelper.close();
    return flag;
}

From source file:edu.cens.loci.provider.LociDbUtils.java

public ArrayList<LociVisit> getBaseVisits(long startTime, long endTime) {
    ArrayList<LociVisit> visits = new ArrayList<LociVisit>();

    final SQLiteDatabase db = mDbHelper.getReadableDatabase();
    String selection = (Visits.EXIT + ">=" + startTime + " AND " + Visits.ENTER + "<=" + endTime);

    Cursor cursor = db.query(Tables.VISITS, null, selection, null, null, null, null);

    if (cursor.moveToFirst()) {
        do {//w w w.  java  2s.  c  o m
            long visitId = cursor.getLong(cursor.getColumnIndex(Visits._ID));
            long placeId = cursor.getLong(cursor.getColumnIndex(Visits.PLACE_ID));
            int type = cursor.getInt(cursor.getColumnIndex(Visits.TYPE));
            long enter = cursor.getLong(cursor.getColumnIndex(Visits.ENTER));
            long exit = cursor.getLong(cursor.getColumnIndex(Visits.EXIT));

            //Log.d(TAG, String.format("visitId=%d placeId=%d type=%d enter=%d exit=%d", visitId, placeId, type, enter, exit));

            visits.add(new LociVisit(visitId, placeId, type, enter, exit));
        } while (cursor.moveToNext());
    }
    cursor.close();
    return visits;
}

From source file:edu.cens.loci.provider.LociDbUtils.java

public Cursor getPlaceData(String mimeType) {
    final SQLiteDatabase db = mDbHelper.getReadableDatabase();
    //checkDataTable();
    String selection = DataColumns.MIMETYPE_ID + "=" + mDbHelper.getMimeTypeId(mimeType);
    Cursor cursor = db.query(Tables.DATA, null, selection, null, null, null, null);
    return cursor;
}

From source file:edu.cens.loci.provider.LociDbUtils.java

public ArrayList<LociVisitWifi> getWifiVisits(long start, long end) {
    final SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String selection = (Visits.EXIT + ">=" + start + " AND " + Visits.ENTER + "<=" + end)
            + (" AND " + Visits.TYPE + "=" + Places.TYPE_WIFI);
    Cursor cursor = db.query(Tables.VISITS, null, selection, null, null, null, null);

    return cursor2visitwifi(cursor);
}

From source file:edu.cens.loci.provider.LociDbUtils.java

public Cursor getPlaceData(long placeId, String mimeType) {
    final SQLiteDatabase db = mDbHelper.getReadableDatabase();
    //checkDataTable();
    String selection = (Data.PLACE_ID + "=" + placeId) + " AND " + DataColumns.MIMETYPE_ID + "="
            + mDbHelper.getMimeTypeId(mimeType);
    Cursor cursor = db.query(Tables.DATA, null, selection, null, null, null, null);
    return cursor;
}

From source file:edu.cens.loci.provider.LociDbUtils.java

/**
 * Delete data row by row so that fixing of primaries etc work correctly.
 *///from w  w w  . ja  va 2  s  .c om
public int deleteData(String selection, String[] selectionArgs, boolean callerIsSyncAdapter) {
    int count = 0;
    final SQLiteDatabase db = mDbHelper.getReadableDatabase();
    // Note that the query will return data according to the access restrictions,
    // so we don't need to worry about deleting data we don't have permission to read.
    Cursor c = db.query(Tables.DATA, DataDeleteQuery.COLUMNS, selection, selectionArgs, null, null, null);
    try {
        while (c.moveToNext()) {
            long placeId = c.getLong(DataDeleteQuery.PLACE_ID);
            String mimeType = c.getString(DataDeleteQuery.MIMETYPE);
            DataRowHandler rowHandler = getDataRowHandler(mimeType);
            count += rowHandler.delete(db, c);
            if (!callerIsSyncAdapter) {
                setPlaceDirty(placeId);
            }
        }
    } finally {
        c.close();
    }

    return count;
}

From source file:com.openatk.fieldnotebook.MainActivity.java

private Field FindFieldByName(String name) {
    if (name != null) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        // Find current field
        Field theField = null;/*from w  w  w. j  a v  a  2 s .com*/
        String where = TableFields.COL_NAME + " = '" + name + "' AND " + TableFields.COL_DELETED + " = 0";
        Cursor cursor = database.query(TableFields.TABLE_NAME, TableFields.COLUMNS, where, null, null, null,
                null);
        if (cursor.moveToFirst()) {
            theField = Field.cursorToField(cursor);
            theField.setMap(map);
        }
        cursor.close();
        dbHelper.close();
        return theField;
    } else {
        return null;
    }
}