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, String limit) 

Source Link

Document

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

Usage

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

/**
 * /*from w  ww .java  2 s . c  om*/
 * @return
 */
public LociVisitWifi getLastWifiVisit() {
    final SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor cursor = db.query(Tables.VISITS, null, Visits.TYPE + "=" + Places.TYPE_WIFI, null, null, null,
            Visits._ID + " DESC", "1");
    ArrayList<LociVisitWifi> list = cursor2visitwifi(cursor);

    if (list != null && list.size() > 0)
        return list.get(0);
    else
        return null;
}

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

public MatchStatsStruct getMatchStats(String eventName, int match, int team, boolean practice) {
    synchronized (ScoutingDBHelper.lock) {

        try {//from  w  w w. ja v a 2 s  .c o m
            MatchStatsStruct stats = MatchStatsStruct.getNewMatchStats();

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

            String[] projection = stats.getProjection();
            String[] where = { String.valueOf(match), String.valueOf(getEventIDFromName(eventName, db)),
                    String.valueOf(team), practice ? "1" : "0" };

            Cursor c = db.query(MatchStatsStruct.TABLE_NAME, projection,
                    MatchStatsStruct.COLUMN_NAME_MATCH_ID + "=? AND " + MatchStatsStruct.COLUMN_NAME_EVENT_ID
                            + "=? AND " + MatchStatsStruct.COLUMN_NAME_TEAM_ID + "=? AND "
                            + MatchStatsStruct.COLUMN_NAME_PRACTICE_MATCH + "=?",
                    where, null, null, null, "0,1");

            stats.fromCursor(c, this, db);
            if (c != null)
                c.close();
            ScoutingDBHelper.getInstance().close();

            return stats;

        } catch (Exception e) {
            return null;
        }

    }
}

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

/**
 * @param time/*w w  w. ja va2 s.c o m*/
 * @param before
 * @return first location before time if before is true. Otherwise, after time. 
 *         returns null if no location is available.
 */
public LociLocation getFirstLocationBeforeOrAfterTime(long time, boolean before) {

    LociLocation loc = null;

    String[] columns = new String[] { Tracks._ID, Tracks.TIME, Tracks.LATITUDE, Tracks.LONGITUDE,
            Tracks.ALTITUDE, Tracks.SPEED, Tracks.BEARING, Tracks.ACCURACY };

    String selection = Tracks.TIME + "<=" + time;
    String order = " DESC";

    if (!before) {
        selection = Tracks.TIME + ">=" + time;
        order = " ASC";
    }

    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    Cursor cursor = db.query(Tables.TRACKS, columns, selection, null, null, null, Tracks.TIME + order, "" + 1);

    if (cursor.moveToFirst()) {
        loc = new LociLocation(LocationManager.GPS_PROVIDER);
        loc.setTime(cursor.getLong(cursor.getColumnIndex(Tracks.TIME)));
        loc.setLatitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LATITUDE)));
        loc.setLongitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LONGITUDE)));
        loc.setAltitude(cursor.getDouble(cursor.getColumnIndex(Tracks.ALTITUDE)));
        loc.setSpeed(cursor.getFloat(cursor.getColumnIndex(Tracks.SPEED)));
        loc.setBearing(cursor.getFloat(cursor.getColumnIndex(Tracks.BEARING)));
        loc.setAccuracy(cursor.getFloat(cursor.getColumnIndex(Tracks.ACCURACY)));
    }
    cursor.close();
    return loc;
}

From source file:android.melbournehistorymap.MapsActivity.java

private void updateMap() {

    //Now get the maps central location
    LatLng mapCenter = mMap.getCameraPosition().target;
    //clear markers
    mMap.clear();//  ww  w  .java 2s .c o m

    //if user tries to zoom to far out of the world, bring them back down to earth...
    if (mMap.getCameraPosition().zoom < ZOOM_RESTRICT_LEVEL) {
        CameraPosition cameraPosition = new CameraPosition.Builder().target(mapCenter) // Sets the center of the map to location user
                .zoom(ZOOM_RESTRICT_LEVEL) // Sets the zoom
                .bearing(0) // Sets the orientation of the camera to east
                .tilt(25) // Sets the tilt of the camera to 30 degrees
                .build(); // Creates a CameraPosition from the builder

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    //rebuild lat/lng variable to be used for Google Places API requests
    double lat = mapCenter.latitude;
    double lng = mapCenter.longitude;
    double zoom = mMap.getCameraPosition().zoom;

    LatLng leftBorder = mMap.getProjection().getVisibleRegion().farLeft;

    //Work out distance between current location and place location
    //Source Library: https://github.com/googlemaps/android-maps-utils

    double radius = SphericalUtil.computeDistanceBetween(mapCenter, leftBorder);

    //Now that we have the new long/latitude of the camera position include zoom level
    //Lets check the database to determine if the user has been here already
    //Set DB helper
    DBHelper myDBHelper = new DBHelper(MapsActivity.this, WikiAPI.DB_NAME, null, WikiAPI.VERSION);
    //Open DB as readable only.
    SQLiteDatabase db = myDBHelper.getWritableDatabase();
    //Prepare DB Search variables
    DecimalFormat dfLat = new DecimalFormat("#.##");
    DecimalFormat dfLng = new DecimalFormat("#.##");
    DecimalFormat dfZoom = new DecimalFormat("#");
    dfLat.setRoundingMode(RoundingMode.CEILING);
    dfLng.setRoundingMode(RoundingMode.CEILING);
    dfZoom.setRoundingMode(RoundingMode.CEILING);
    double dblLat = Double.parseDouble(dfLat.format(lat));
    double dblLng = Double.parseDouble(dfLng.format(lng));
    double dblZoom = Double.parseDouble(dfZoom.format(zoom));
    //Limit by 1 rows
    Cursor cursor = db.query(DBHelper.LOC_TABLE, null,
            "LAT LIKE '" + dblLat + "%' AND LNG LIKE '" + dblLng + "%' AND ZOOM = '" + dblZoom + "'", null,
            null, null, null, "1");

    int count = cursor.getCount();

    if (count == 0) {
        //user has not been to this location/zoom level  before
        //add the new location data, then trigger the google place webservice api
        ContentValues values = new ContentValues();

        values.put("lat", String.valueOf(dblLat));
        values.put("lng", String.valueOf(dblLng));
        values.put("zoom", String.valueOf(dblZoom));
        db.insert(DBHelper.LOC_TABLE, null, values);

        String url;
        url = updateURL(lat, lng, radius);
        List<List<String>> googlePlaces = null; //null on first reference, the list is updated within the method callstack
        db.close();

        GoogleAPI.callMapMethod(mMap, url, MapsActivity.this, googlePlaces, spinner);
    }
    if (count == 1) {
        //user has been here before
        //get place data from DB and not from the API
        //if place data returned hasn't been updated in 30 days - update data using getPlaceByID method
        Cursor placeCursor = db.query(DBHelper.TABLE_NAME, null, "PLACE_TYPES LIKE '%point_of_interest%'", null,
                null, null, null, null);

        List<List<String>> googlePlaces = new ArrayList<List<String>>();

        while (placeCursor.moveToNext()) {
            String place_ID = placeCursor.getString(placeCursor.getColumnIndex("PLACE_ID"));
            String placeName = placeCursor.getString(placeCursor.getColumnIndex("PLACE_NAME"));
            String placeLoc = placeCursor.getString(placeCursor.getColumnIndex("PLACE_LOCATION"));
            String placeLat = placeCursor.getString(placeCursor.getColumnIndex("LAT"));
            String placeLng = placeCursor.getString(placeCursor.getColumnIndex("LNG"));

            //if lat and long from database is in the search bounds, add to the list of data to be shown
            LatLngBounds SEARCH_BOUNDS = mMap.getProjection().getVisibleRegion().latLngBounds;
            LatLng search_loc = new LatLng(Double.parseDouble(placeLat), Double.parseDouble(placeLng));

            if (SEARCH_BOUNDS.contains(search_loc)) {
                //now what data do we want?
                //Initiate a place data array
                List<String> placeData = new ArrayList<String>();

                //add place data to its array
                placeData.add(placeName); //0
                placeData.add(place_ID); //1
                placeData.add(placeLoc); //2
                placeData.add(String.valueOf(placeLat)); //3
                placeData.add(String.valueOf(placeLng)); //4
                placeData.add(""); //5
                placeData.add(""); //6

                //send the place specific data to the google places array list
                googlePlaces.add(placeData);
            }
        }
        db.close();

        //TODO: Get this method off the main UI thread!
        GoogleAPI.filterPlaces(googlePlaces, mMap, this, spinner);
    }
}

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

/**
 * Returns visit basic information including visit_id, type, enter_time, and exit_time
 * @param placeId is place id/*  w w  w .  j av  a  2 s. co m*/
 * @param orderBy 
 * @param maxCount maximum number of rows to return. ignored when null.
 * @return
 */
public ArrayList<LociVisit> getBaseVisits(long placeId, String orderBy, String maxCount) {

    ArrayList<LociVisit> visits = new ArrayList<LociVisit>();

    final SQLiteDatabase db = mDbHelper.getReadableDatabase();
    String selection = (Visits.PLACE_ID + "=" + placeId);

    Cursor cursor;

    if (maxCount != null)
        cursor = db.query(Tables.VISITS, null, selection, null, null, null, orderBy, maxCount);
    else
        cursor = db.query(Tables.VISITS, null, selection, null, null, null, orderBy);

    if (cursor.moveToFirst()) {
        do {
            long visitId = cursor.getLong(cursor.getColumnIndex(Visits._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));

            visits.add(new LociVisit(visitId, placeId, type, enter, exit));

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

        } while (cursor.moveToNext());
    }

    cursor.close();
    return visits;
}

From source file:me.piebridge.bible.Bible.java

private String getVersionMetadata(String name, SQLiteDatabase metadata, String defaultValue) {
    String value = defaultValue;// ww w .  jav  a 2 s.  c  o  m
    Cursor cursor = metadata.query("metadata", new String[] { "value" }, "name = ? or name = ?",
            new String[] { name, name + "_" + Locale.getDefault().toString() }, null, null, "name desc", "1");
    while (cursor != null && cursor.moveToNext()) {
        value = cursor.getString(cursor.getColumnIndexOrThrow("value"));
        break;
    }
    if (cursor != null) {
        cursor.close();
    }
    return value;
}

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

/**
 * Select.//w  w w  .ja  va2s . c  o m
 * 
 * @param where
 *            the where
 * @param whereArgs
 *            the where args
 * @param groupBy
 *            the group by
 * @param having
 *            the having
 * @param orderBy
 *            the order by
 * @return the list
 */
public List<ODataRow> select(String where, Object[] whereArgs, String groupBy, String having, String orderBy) {
    List<ODataRow> records = new ArrayList<ODataRow>();
    SQLiteDatabase db = getReadableDatabase();
    String limit = null;
    if (mLimit > 0) {
        limit = mOffset + ", " + mLimit;
    }
    Cursor cr = db.query(getTableName(), new String[] { "*" }, getWhereClause(where),
            getWhereArgs(where, whereArgs), groupBy, having, orderBy, limit);
    if (cr.moveToFirst()) {
        do {
            ODataRow row = new ODataRow();
            for (OColumn col : getColumns()) {
                if (col.getRelationType() == null) {
                    row.put(col.getName(), createRecordRow(col, cr));
                } else {
                    switch (col.getRelationType()) {
                    case ManyToMany:
                        row.put(col.getName(),
                                new OM2MRecord(this, col, cr.getInt(cr.getColumnIndex(OColumn.ROW_ID))));
                        break;
                    case OneToMany:
                        row.put(col.getName(),
                                new OO2MRecord(this, col, cr.getInt(cr.getColumnIndex(OColumn.ROW_ID))));
                        break;
                    case ManyToOne:
                        row.put(col.getName(),
                                new OM2ORecord(this, col, cr.getInt(cr.getColumnIndex(col.getName()))));
                        break;
                    }
                }
            }
            /*
             * Adding functional column values to record values if not
             * syncing
             */
            if (!mSyncingData) {
                for (OColumn col : mFunctionalColumns) {
                    if (!col.canFunctionalStore()) {
                        row.put(col.getName(), getFunctionalMethodValue(col, row));
                    }
                }
            }
            if (row.getInt("id") == 0 || row.getString("id").equals("false"))
                row.put("id", 0);
            records.add(row);
        } while (cr.moveToNext());
    }
    cr.close();
    db.close();
    return records;
}

From source file:org.ttrssreader.controllers.DBHelper.java

public Article getArticle(int id) {
    Article ret = null;//ww  w . j  av a 2 s  . c om
    if (!isDBAvailable())
        return null;

    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);
    Cursor c = null;
    try {
        c = db.query(TABLE_ARTICLES, null, "_id=?", new String[] { id + "" }, null, null, null, null);
        if (c.moveToFirst())
            ret = handleArticleCursor(c);
    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }

    return ret;
}

From source file:org.ttrssreader.controllers.DBHelper.java

public Feed getFeed(int id) {
    Feed ret = new Feed();
    if (!isDBAvailable())
        return ret;

    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);/*from   w w  w . j av a  2s  .  c o m*/
    Cursor c = null;
    try {
        c = db.query(TABLE_FEEDS, null, "_id=?", new String[] { id + "" }, null, null, null, null);
        if (c.moveToFirst())
            ret = handleFeedCursor(c);
    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }

    return ret;
}

From source file:org.ttrssreader.controllers.DBHelper.java

public Category getCategory(int id) {
    Category ret = new Category();
    if (!isDBAvailable())
        return ret;

    SQLiteDatabase db = getOpenHelper().getReadableDatabase();
    readLock(true);//from  www  . j ava  2 s. com
    Cursor c = null;
    try {
        c = db.query(TABLE_CATEGORIES, null, "_id=?", new String[] { id + "" }, null, null, null, null);
        if (c.moveToFirst())
            ret = handleCategoryCursor(c);
    } finally {
        if (c != null && !c.isClosed())
            c.close();
        readLock(false);
    }

    return ret;
}