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.google.samples.apps.topeka.persistence.TopekaDatabaseHelper.java

/**
 * Gets all categories wrapped in a {@link Cursor} positioned at it's first element.
 * <p>There are <b>no quizzes</b> within the categories obtained from this cursor</p>
 *
 * @param context The context this is running in.
 * @return All categories stored in the database.
 *///  w ww. j a  va 2  s.  com
private static Cursor getCategoryCursor(Context context) {
    SQLiteDatabase readableDatabase = getReadableDatabase(context);
    Cursor data = readableDatabase.query(CategoryTable.NAME, CategoryTable.PROJECTION, null, null, null, null,
            null);
    data.moveToFirst();
    return data;
}

From source file:org.opendatakit.common.android.database.DataModelDatabaseHelper.java

/**
 * Accessor to retrieve the database tableId given a formId
 *
 * @param db// ww  w  .ja  v a2 s . c o  m
 * @param formId
 *          -- either the integer _ID or the textual form_id
 * @return
 */
public static IdInstanceNameStruct getIds(SQLiteDatabase db, String formId) {
    boolean isNumericId = StringUtils.isNumeric(formId);

    Cursor c = null;
    try {
        c = db.query(FORMS_TABLE_NAME,
                new String[] { FormsColumns._ID, FormsColumns.FORM_ID, FormsColumns.TABLE_ID,
                        FormsColumns.INSTANCE_NAME },
                (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?", new String[] { formId }, null,
                null, null);

        if (c.moveToFirst()) {
            int idxId = c.getColumnIndex(FormsColumns._ID);
            int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID);
            int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID);
            int idxInstanceName = c.getColumnIndex(FormsColumns.INSTANCE_NAME);

            return new IdInstanceNameStruct(c.getInt(idxId), c.getString(idxFormId), c.getString(idxTableId),
                    c.isNull(idxInstanceName) ? null : c.getString(idxInstanceName));
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return null;
}

From source file:com.google.samples.apps.topeka.persistence.TopekaDatabaseHelper.java

/**
 * Creates objects for quizzes according to a category id.
 *
 * @param categoryId The category to create quizzes for.
 * @param database The database containing the quizzes.
 * @return The found quizzes or an empty list if none were available.
 *//*ww  w  .  ja  v  a  2  s. c o m*/
private static List<Quiz> getQuizzes(final String categoryId, SQLiteDatabase database) {
    final List<Quiz> quizzes = new ArrayList<>();
    final Cursor cursor = database.query(QuizTable.NAME, QuizTable.PROJECTION,
            QuizTable.FK_CATEGORY + " LIKE ?", new String[] { categoryId }, null, null, null);
    cursor.moveToFirst();
    do {
        quizzes.add(createQuizDueToType(cursor));
    } while (cursor.moveToNext());
    cursor.close();
    return quizzes;
}

From source file:com.google.samples.apps.topeka.persistence.TopekaDatabaseHelper.java

/**
 * Looks for a category with a given id.
 *
 * @param context The context this is running in.
 * @param categoryId Id of the category to look for.
 * @return The found category./* w w  w  .jav a2  s .co  m*/
 */
public static Category getCategoryWith(Context context, String categoryId) {
    SQLiteDatabase readableDatabase = getReadableDatabase(context);
    String[] selectionArgs = { categoryId };
    Cursor data = readableDatabase.query(CategoryTable.NAME, CategoryTable.PROJECTION,
            CategoryTable.COLUMN_ID + "=?", selectionArgs, null, null, null);
    data.moveToFirst();
    return getCategory(data, readableDatabase);
}

From source file:com.jefftharris.passwdsafe.NotificationMgr.java

/** Get the id for a URI or null if not found */
private static Long getDbUriId(PasswdFileUri uri, SQLiteDatabase db) throws SQLException {
    Cursor cursor = db.query(DB_TABLE_URIS, new String[] { DB_COL_URIS_ID }, DB_MATCH_URIS_URI,
            new String[] { uri.getUri().toString() }, null, null, null);
    try {//from ww w .j  a v a  2s . c o m
        if (!cursor.moveToFirst()) {
            return null;
        }
        return cursor.getLong(0);
    } finally {
        cursor.close();
    }
}

From source file:org.opendatakit.common.android.database.DataModelDatabaseHelper.java

/**
 * Return a map of (elementKey -> ColumnDefinition)
 *
 * @param db/* w w  w  . j  av  a2 s  .co  m*/
 * @param tableId
 * @return
 * @throws JsonParseException
 * @throws JsonMappingException
 * @throws IOException
 */
public static Map<String, ColumnDefinition> getColumnDefinitions(SQLiteDatabase db, String tableId)
        throws JsonParseException, JsonMappingException, IOException {
    Map<String, ColumnDefinition> defn = new HashMap<String, ColumnDefinition>();

    Cursor c = null;
    try {
        c = db.query(COLUMN_DEFINITIONS_TABLE_NAME, null, ColumnDefinitionsColumns.TABLE_ID + "=?",
                new String[] { tableId }, null, null, null);

        if (c.moveToFirst()) {
            int idxEK = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_KEY);
            int idxEN = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_NAME);
            int idxET = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_TYPE);
            int idxIP = c.getColumnIndex(ColumnDefinitionsColumns.IS_UNIT_OF_RETENTION);
            int idxLIST = c.getColumnIndex(ColumnDefinitionsColumns.LIST_CHILD_ELEMENT_KEYS);
            HashMap<String, ColumnContainer> ref = new HashMap<String, ColumnContainer>();

            do {
                String elementKey = c.getString(idxEK);
                String elementName = c.getString(idxEN);
                String elementType = c.getString(idxET);
                boolean isUnitOfRetention = (c.getInt(idxIP) != 0);
                String childrenString = c.isNull(idxLIST) ? null : c.getString(idxLIST);
                ColumnContainer ctn = new ColumnContainer();
                ctn.defn = new ColumnDefinition(elementKey, elementName, elementType, isUnitOfRetention);

                if (childrenString != null) {
                    @SuppressWarnings("unchecked")
                    ArrayList<String> l = ODKFileUtils.mapper.readValue(childrenString, ArrayList.class);
                    ctn.children = l;
                }

                ref.put(elementKey, ctn);
            } while (c.moveToNext());

            // OK now connect all the children...

            for (ColumnContainer ctn : ref.values()) {
                if (ctn.children != null) {
                    for (String ek : ctn.children) {
                        ColumnContainer child = ref.get(ek);
                        if (child == null) {
                            throw new IllegalArgumentException("Unexpected missing child element: " + ek);
                        }
                        ctn.defn.addChild(child.defn);
                    }
                }
            }

            // and construct the list of entries...
            for (ColumnContainer ctn : ref.values()) {
                defn.put(ctn.defn.elementKey, ctn.defn);
            }
            return defn;
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return null;
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static void deleteAlarm(Context context, Lecture lecture) {
    AlarmsDBOpenHelper alarmDB = new AlarmsDBOpenHelper(context);
    SQLiteDatabase db = alarmDB.getWritableDatabase();
    Cursor cursor;//  w w  w.  jav a 2 s.c  o  m

    try {
        cursor = db.query(AlarmsTable.NAME, AlarmsDBOpenHelper.allcolumns, AlarmsTable.Columns.EVENT_ID + "=?",
                new String[] { lecture.lecture_id }, null, null, null);
    } catch (SQLiteException e) {
        e.printStackTrace();
        MyApp.LogDebug("delete alarm", "failure on alarm query");
        db.close();
        return;
    }

    if (cursor.getCount() == 0) {
        db.close();
        cursor.close();
        MyApp.LogDebug("delete_alarm", "alarm for " + lecture.lecture_id + " not found");
        return;
    }

    cursor.moveToFirst();

    Intent intent = new Intent(context, AlarmReceiver.class);

    String lecture_id = cursor.getString(cursor.getColumnIndex(AlarmsTable.Columns.EVENT_ID));
    intent.putExtra(BundleKeys.ALARM_LECTURE_ID, lecture_id);
    int day = cursor.getInt(cursor.getColumnIndex(AlarmsTable.Columns.DAY));
    intent.putExtra(BundleKeys.ALARM_DAY, day);
    String title = cursor.getString(cursor.getColumnIndex(AlarmsTable.Columns.EVENT_TITLE));
    intent.putExtra(BundleKeys.ALARM_TITLE, title);
    long startTime = cursor.getLong(cursor.getColumnIndex(AlarmsTable.Columns.TIME));
    intent.putExtra(BundleKeys.ALARM_START_TIME, startTime);

    // delete any previous alarms of this lecture
    db.delete(AlarmsTable.NAME, AlarmsTable.Columns.EVENT_ID + "=?", new String[] { lecture.lecture_id });
    db.close();

    intent.setAction("de.machtnix.fahrplan.ALARM");
    intent.setData(Uri.parse("alarm://" + lecture.lecture_id));

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingintent = PendingIntent.getBroadcast(context, Integer.parseInt(lecture.lecture_id),
            intent, 0);

    // Cancel any existing alarms for this lecture
    alarmManager.cancel(pendingintent);

    lecture.has_alarm = false;
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

static void loadDays(Context context) {
    MyApp.dateInfos = new DateInfos();
    LecturesDBOpenHelper lecturesDB = new LecturesDBOpenHelper(context);

    SQLiteDatabase lecturedb = lecturesDB.getReadableDatabase();
    Cursor cursor;/*w  ww  .ja  v a2  s  . c o  m*/

    try {
        cursor = lecturedb.query(LecturesTable.NAME, LecturesDBOpenHelper.allcolumns, null, null, null, null,
                null);
    } catch (SQLiteException e) {
        e.printStackTrace();
        lecturedb.close();
        lecturesDB.close();
        return;
    }

    if (cursor.getCount() == 0) {
        // evtl. Datenbankreset wg. DB Formatnderung -> neu laden
        cursor.close();
        lecturesDB.close();
        lecturedb.close();
        return;
    }

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        int day = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.DAY));
        String date = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.DATE));

        DateInfo dateItem = new DateInfo(day, date);
        if (!MyApp.dateInfos.contains(dateItem)) {
            MyApp.dateInfos.add(dateItem);
        }
        cursor.moveToNext();
    }
    cursor.close();

    for (DateInfo dateInfo : MyApp.dateInfos) {
        MyApp.LogDebug(LOG_TAG, "DateInfo: " + dateInfo);
    }
    lecturesDB.close();
    lecturedb.close();
}

From source file:com.codebutler.farebot.transit.SuicaTransitData.java

/**
 * ?????//from   w w  w  .j  av a2  s.c o m
 * <pre>http:// sourceforge.jp/projects/felicalib/wiki/suica???????</pre>
 * @param lineCode 
 * @param stationCode 
 * @return ????????0????1??????
 */
private static Station getBusStop(int regionCode, int lineCode, int stationCode) {
    int areaCode = (regionCode >> 6);

    try {
        SQLiteDatabase db = FareBotApplication.getInstance().getSuicaDBUtil().openDatabase();
        Cursor cursor = db.query(TABLE_IRUCA_STATIONCODE, COLUMNS_IRUCA_STATIONCODE,
                String.format("%s = ? AND %s = ?", COLUMN_LINECODE, COLUMN_STATIONCODE),
                new String[] { Integer.toHexString(lineCode), Integer.toHexString(stationCode) }, null, null,
                COLUMN_ID);

        if (!cursor.moveToFirst()) {
            return null;
        }

        // FIXME: Figure out a better way to deal with i18n.
        boolean isJa = Locale.getDefault().getLanguage().equals("ja");
        String companyName = cursor
                .getString(cursor.getColumnIndex(isJa ? COLUMN_COMPANYNAME : COLUMN_COMPANYNAME_EN));
        String stationName = cursor
                .getString(cursor.getColumnIndex(isJa ? COLUMN_STATIONNAME : COLUMN_STATIONNAME_EN));
        return new Station(companyName, null, stationName, null, null, null);

    } catch (Exception e) {
        Log.e("SuicaStationProvider", "getBusStop() error", e);
        return null;
    }
}

From source file:com.codebutler.farebot.transit.SuicaTransitData.java

/**
 * ?????????/* w w w  .ja  v a 2  s.c o m*/
 * <pre>http://sourceforge.jp/projects/felicalib/wiki/suica???????</pre>
 *
 * @param regionCode 
 * @param lineCode 
 * @param stationCode 
 * @return ????????0????1????2??????
 */
private static Station getRailStation(int regionCode, int lineCode, int stationCode) {
    int areaCode = (regionCode >> 6);

    try {
        SQLiteDatabase db = FareBotApplication.getInstance().getSuicaDBUtil().openDatabase();
        Cursor cursor = db.query(TABLE_STATIONCODE, COLUMNS_STATIONCODE,
                String.format("%s = ? AND %s = ? AND %s = ?", COLUMN_AREACODE, COLUMN_LINECODE,
                        COLUMN_STATIONCODE),
                new String[] { String.valueOf(areaCode & 0xFF), String.valueOf(lineCode & 0xFF),
                        String.valueOf(stationCode & 0xFF) },
                null, null, COLUMN_ID);

        if (!cursor.moveToFirst()) {
            Log.w("SuicaTransitData",
                    String.format("FAILED get rail company: r: 0x%s a: 0x%s l: 0x%s s: 0x%s",
                            Integer.toHexString(regionCode), Integer.toHexString(areaCode),
                            Integer.toHexString(lineCode), Integer.toHexString(stationCode)));

            return null;
        }

        // FIXME: Figure out a better way to deal with i18n.
        boolean isJa = Locale.getDefault().getLanguage().equals("ja");
        String companyName = cursor
                .getString(cursor.getColumnIndex(isJa ? COLUMN_COMPANYNAME : COLUMN_COMPANYNAME_EN));
        String lineName = cursor.getString(cursor.getColumnIndex(isJa ? COLUMN_LINENAME : COLUMN_LINENAME_EN));
        String stationName = cursor
                .getString(cursor.getColumnIndex(isJa ? COLUMN_STATIONNAME : COLUMN_STATIONNAME_EN));
        String latitude = cursor.getString(cursor.getColumnIndex(COLUMN_LATITUDE));
        String longitude = cursor.getString(cursor.getColumnIndex(COLUMN_LONGITUDE));
        return new Station(companyName, lineName, stationName, null, latitude, longitude);

    } catch (Exception e) {
        Log.e("SuicaStationProvider", "Error in getRailStation", e);
        return null;
    }
}