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:simonlang.coastdove.usagestatistics.ui.main.AppListLoader.java

@Override
public ArrayList<ApplicationInfo> loadInBackground() {
    AppUsageDbHelper dbHelper = new AppUsageDbHelper(getContext());
    SQLiteDatabase db = dbHelper.getReadableDatabase();

    String[] projection = { AppUsageContract.AppTable.COLUMN_NAME_PACKAGE };
    String groupBy = AppUsageContract.AppTable.COLUMN_NAME_PACKAGE;

    Cursor c = db.query(AppUsageContract.AppTable.TABLE_NAME, projection, null, null, groupBy, null, null);
    ArrayList<ApplicationInfo> data = new ArrayList<>(c.getCount());
    c.moveToFirst();//from w  ww  . j a  v  a2  s  .  c om
    while (!c.isAfterLast()) {
        String appPackageName = c.getString(0);
        if (appPackageName != null) {
            PackageManager packageManager = getContext().getPackageManager();
            try {
                ApplicationInfo appInfo = packageManager.getApplicationInfo(appPackageName, 0);
                data.add(appInfo);
            } catch (PackageManager.NameNotFoundException e) {
                Log.e("AppListLoader", "Unable to find app " + appPackageName + ": " + e.getMessage());
            }
        }
        c.moveToNext();
    }
    c.close();
    db.close();

    return data;
}

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

/**
 * Load all Lectures from the DB on the day specified
 *
 * @param context The Android Context//from  ww w.  j av  a 2s.com
 * @param day The day to load lectures for (0..), or -1 for all days
 * @return ArrayList of Lecture objects
 */
public static LectureList loadLecturesForDayIndex(Context context, int day) {
    MyApp.LogDebug(LOG_TAG, "load lectures of day " + day);

    SQLiteDatabase lecturedb = null;
    LecturesDBOpenHelper lecturesDB = new LecturesDBOpenHelper(context);
    lecturedb = lecturesDB.getReadableDatabase();

    HighlightDBOpenHelper highlightDB = new HighlightDBOpenHelper(context);
    SQLiteDatabase highlightdb = highlightDB.getReadableDatabase();

    LectureList lectures = new LectureList();
    Cursor cursor, hCursor;
    boolean allDays;

    if (day == ALL_DAYS) {
        allDays = true;
    } else {
        allDays = false;
    }

    try {
        cursor = lecturedb.query(LecturesTable.NAME, LecturesDBOpenHelper.allcolumns,
                allDays ? null : (LecturesTable.Columns.DAY + "=?"),
                allDays ? null : (new String[] { String.format("%d", day) }), null, null,
                LecturesTable.Columns.DATE_UTC);
    } catch (SQLiteException e) {
        e.printStackTrace();
        lecturedb.close();
        highlightdb.close();
        lecturesDB.close();
        return null;
    }
    try {
        hCursor = highlightdb.query(HighlightsTable.NAME, HighlightDBOpenHelper.allcolumns, null, null, null,
                null, null);
    } catch (SQLiteException e) {
        e.printStackTrace();
        lecturedb.close();
        highlightdb.close();
        lecturesDB.close();
        return null;
    }
    MyApp.LogDebug(LOG_TAG, "Got " + cursor.getCount() + " rows.");
    MyApp.LogDebug(LOG_TAG, "Got " + hCursor.getCount() + " highlight rows.");

    if (cursor.getCount() == 0) {
        cursor.close();
        lecturedb.close();
        highlightdb.close();
        lecturesDB.close();
        return null;
    }

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Lecture lecture = new Lecture(cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.EVENT_ID)));
        lecture.title = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.TITLE));
        lecture.subtitle = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.SUBTITLE));
        lecture.day = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.DAY));
        lecture.room = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.ROOM));
        lecture.startTime = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.START));
        lecture.duration = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.DURATION));
        lecture.speakers = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.SPEAKERS));
        lecture.track = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.TRACK));
        lecture.type = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.TYPE));
        lecture.lang = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.LANG));
        lecture.abstractt = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.ABSTRACT));
        lecture.description = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.DESCR));
        lecture.relStartTime = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.REL_START));
        lecture.date = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.DATE));
        lecture.links = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.LINKS));
        lecture.dateUTC = cursor.getLong(cursor.getColumnIndex(LecturesTable.Columns.DATE_UTC));
        lecture.room_index = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.ROOM_IDX));
        lecture.recordingLicense = cursor.getString(cursor.getColumnIndex(LecturesTable.Columns.REC_LICENSE));
        lecture.recordingOptOut = cursor.getInt(
                cursor.getColumnIndex(LecturesTable.Columns.REC_OPTOUT)) == LecturesTable.Values.REC_OPTOUT_OFF
                        ? Lecture.RECORDING_OPTOUT_OFF
                        : Lecture.RECORDING_OPTOUT_ON;
        lecture.changedTitle = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_TITLE)) != 0;
        lecture.changedSubtitle = cursor
                .getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_SUBTITLE)) != 0;
        lecture.changedRoom = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_ROOM)) != 0;
        lecture.changedDay = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_DAY)) != 0;
        lecture.changedSpeakers = cursor
                .getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_SPEAKERS)) != 0;
        lecture.changedRecordingOptOut = cursor
                .getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_RECORDING_OPTOUT)) != 0;
        lecture.changedLanguage = cursor
                .getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_LANGUAGE)) != 0;
        lecture.changedTrack = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_TRACK)) != 0;
        lecture.changedIsNew = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_IS_NEW)) != 0;
        lecture.changedTime = cursor.getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_TIME)) != 0;
        lecture.changedDuration = cursor
                .getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_DURATION)) != 0;
        lecture.changedIsCanceled = cursor
                .getInt(cursor.getColumnIndex(LecturesTable.Columns.CHANGED_IS_CANCELED)) != 0;

        lectures.add(lecture);
        cursor.moveToNext();
    }
    cursor.close();

    hCursor.moveToFirst();
    while (!hCursor.isAfterLast()) {
        String lecture_id = hCursor.getString(hCursor.getColumnIndex(HighlightsTable.Columns.EVENT_ID));
        int highlightState = hCursor.getInt(hCursor.getColumnIndex(HighlightsTable.Columns.HIGHLIGHT));
        MyApp.LogDebug(LOG_TAG, "lecture " + lecture_id + " is hightlighted:" + highlightState);

        for (Lecture lecture : lectures) {
            if (lecture.lecture_id.equals(lecture_id)) {
                lecture.highlight = (highlightState == HighlightsTable.Values.HIGHLIGHT_STATE_ON ? true
                        : false);
            }
        }
        hCursor.moveToNext();
    }
    hCursor.close();

    highlightdb.close();
    lecturedb.close();
    lecturesDB.close();
    return lectures;
}

From source file:com.example.android.touroflondon.data.TourDbHelper.java

/**
 * Returns a {@link Cursor} for all route point entries with the given projection.
 *
 * @param projection//from w  w  w  .  j a  v  a  2 s.  c  om
 * @return
 */
public Cursor getRoute(String[] projection) {
    SQLiteDatabase db = this.getReadableDatabase();

    // select all entries from route point table
    return db.query(TourContract.RouteEntry.TABLE_NAME, projection, null, null, null, null, null);
}

From source file:org.jsharkey.oilcan.ScriptDatabase.java

private void validateCache() {

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cur = db.query(TABLE_SCRIPTS, new String[] { FIELD_SCRIPT_DOMAINREGEX, FIELD_SCRIPT_CONTENT },
            FIELD_SCRIPT_ENABLED + " = 1", null, null, null, null);

    int COL_DOMAINREGEX = cur.getColumnIndex(FIELD_SCRIPT_DOMAINREGEX),
            COL_CONTENT = cur.getColumnIndex(FIELD_SCRIPT_CONTENT);

    cache.clear();/* w  w  w .  j a v a  2 s .c o m*/

    while (cur.moveToNext()) {
        String domainregex = cur.getString(COL_DOMAINREGEX), content = cur.getString(COL_CONTENT);
        cache.put(Pattern.compile(domainregex), content);

    }

    cur.close();

}

From source file:com.cuddlesoft.nori.database.APISettingsDatabase.java

/**
 * Get all {@link SearchClient.Settings} objects from the database.
 *
 * @return List of pairs mapping database IDs to {@link SearchClient.Settings} objects.
 *///from   ww w.  ja  v a  2  s .com
public List<Pair<Integer, SearchClient.Settings>> getAll() {
    // Query the database.
    SQLiteDatabase db = getReadableDatabase();
    Cursor c = db.query(TABLE_NAME, null, null, null, null, null, COLUMN_ID);

    // Convert database Cursor to List.
    final List<Pair<Integer, SearchClient.Settings>> settingsList = new ArrayList<>(c.getCount());
    while (c.moveToNext()) {
        settingsList.add(new Pair<>(c.getInt(c.getColumnIndex(COLUMN_ID)), cursorToSearchClientSettings(c)));
    }

    // Clean up native resources.
    c.close();
    db.close();

    return settingsList;
}

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

public boolean hasDirtData(SQLiteDatabase db) {
    Cursor c = db.query(name, null, _.isDirtyP, new String[] { "1" }, null, null, null);
    if (c.moveToFirst()) {
        c.close();//w  w w  .j  av a  2s  .  c  om
        return true;
    }
    c.close();
    return false;
}

From source file:com.onesignal.GenerateNotification.java

static void createSummaryNotification(Context inContext, boolean updateSummary, JSONObject gcmBundle) {
    if (updateSummary)
        setStatics(inContext);//from   w  ww  .  j a v  a  2  s .c o m

    String group = null;
    try {
        group = gcmBundle.getString("grp");
    } catch (Throwable t) {
    }

    Random random = new Random();
    PendingIntent summaryDeleteIntent = getNewActionPendingIntent(random.nextInt(),
            getNewBaseDeleteIntent(0).putExtra("summary", group));

    OneSignalDbHelper dbHelper = new OneSignalDbHelper(currentContext);
    SQLiteDatabase writableDb = dbHelper.getWritableDatabase();

    String[] retColumn = { NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID,
            NotificationTable.COLUMN_NAME_FULL_DATA, NotificationTable.COLUMN_NAME_IS_SUMMARY,
            NotificationTable.COLUMN_NAME_TITLE, NotificationTable.COLUMN_NAME_MESSAGE };

    String[] whereArgs = { group };

    Cursor cursor = writableDb.query(NotificationTable.TABLE_NAME, retColumn,
            NotificationTable.COLUMN_NAME_GROUP_ID + " = ? AND " + // Where String
                    NotificationTable.COLUMN_NAME_DISMISSED + " = 0 AND " + NotificationTable.COLUMN_NAME_OPENED
                    + " = 0",
            whereArgs, null, // group by
            null, // filter by row groups
            NotificationTable._ID + " DESC" // sort order, new to old
    );

    Notification summaryNotification;
    int summaryNotificationId = random.nextInt();

    String firstFullData = null;
    Collection<SpannableString> summeryList = null;

    if (cursor.moveToFirst()) {
        SpannableString spannableString;
        summeryList = new ArrayList<SpannableString>();

        do {
            if (cursor.getInt(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_IS_SUMMARY)) == 1)
                summaryNotificationId = cursor
                        .getInt(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID));
            else {
                String title = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_TITLE));
                if (title == null)
                    title = "";
                else
                    title += " ";

                // Html.fromHtml("<strong>" + line1Title + "</strong> " + gcmBundle.getString("alert"));

                String msg = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_MESSAGE));
                spannableString = new SpannableString(title + msg);
                if (title.length() > 0)
                    spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, title.length(),
                            0);
                summeryList.add(spannableString);

                if (firstFullData == null)
                    firstFullData = cursor
                            .getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_FULL_DATA));
            }
        } while (cursor.moveToNext());

        if (updateSummary) {
            try {
                gcmBundle = new JSONObject(firstFullData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    if (summeryList != null && (!updateSummary || summeryList.size() > 1)) {
        int notificationCount = summeryList.size() + (updateSummary ? 0 : 1);

        String summaryMessage = null;

        if (gcmBundle.has("grp_msg")) {
            try {
                summaryMessage = gcmBundle.getString("grp_msg").replace("$[notif_count]",
                        "" + notificationCount);
            } catch (Throwable t) {
            }
        }
        if (summaryMessage == null)
            summaryMessage = notificationCount + " new messages";

        JSONObject summaryDataBundle = new JSONObject();
        try {
            summaryDataBundle.put("alert", summaryMessage);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Intent summaryIntent = getNewBaseIntent(summaryNotificationId).putExtra("summary", group)
                .putExtra("onesignal_data", summaryDataBundle.toString());

        PendingIntent summaryContentIntent = getNewActionPendingIntent(random.nextInt(), summaryIntent);

        NotificationCompat.Builder summeryBuilder = getBaseNotificationCompatBuilder(gcmBundle, !updateSummary);

        summeryBuilder.setContentIntent(summaryContentIntent).setDeleteIntent(summaryDeleteIntent)
                .setContentTitle(currentContext.getPackageManager()
                        .getApplicationLabel(currentContext.getApplicationInfo()))
                .setContentText(summaryMessage).setNumber(notificationCount).setOnlyAlertOnce(updateSummary)
                .setGroup(group).setGroupSummary(true);

        if (!updateSummary)
            summeryBuilder.setTicker(summaryMessage);

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        String line1Title = null;

        // Add the latest notification to the summary
        if (!updateSummary) {
            try {
                line1Title = gcmBundle.getString("title");
            } catch (Throwable t) {
            }

            if (line1Title == null)
                line1Title = "";
            else
                line1Title += " ";

            String message = "";
            try {
                message = gcmBundle.getString("alert");
            } catch (Throwable t) {
            }

            SpannableString spannableString = new SpannableString(line1Title + message);
            if (line1Title.length() > 0)
                spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, line1Title.length(),
                        0);
            inboxStyle.addLine(spannableString);
        }

        for (SpannableString line : summeryList)
            inboxStyle.addLine(line);
        inboxStyle.setBigContentTitle(summaryMessage);
        summeryBuilder.setStyle(inboxStyle);

        summaryNotification = summeryBuilder.build();
    } else {
        // There currently isn't a visible notification from this group, save the group summary notification id and post it so it looks like a normal notification.
        ContentValues values = new ContentValues();
        values.put(NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID, summaryNotificationId);
        values.put(NotificationTable.COLUMN_NAME_GROUP_ID, group);
        values.put(NotificationTable.COLUMN_NAME_IS_SUMMARY, 1);

        writableDb.insert(NotificationTable.TABLE_NAME, null, values);

        NotificationCompat.Builder notifBuilder = getBaseNotificationCompatBuilder(gcmBundle, !updateSummary);

        PendingIntent summaryContentIntent = getNewActionPendingIntent(random.nextInt(),
                getNewBaseIntent(summaryNotificationId).putExtra("onesignal_data", gcmBundle.toString())
                        .putExtra("summary", group));

        addNotificationActionButtons(gcmBundle, notifBuilder, summaryNotificationId, group);
        notifBuilder.setContentIntent(summaryContentIntent).setDeleteIntent(summaryDeleteIntent)
                .setOnlyAlertOnce(updateSummary).setGroup(group).setGroupSummary(true);

        summaryNotification = notifBuilder.build();
    }

    NotificationManagerCompat.from(currentContext).notify(summaryNotificationId, summaryNotification);

    cursor.close();
    writableDb.close();
}

From source file:com.github.gw2app.events.Gw2ApiEvents.java

private HashMap<Integer, String> _getWorldNamesFromDB() {
    Log.d("Gw2", "Fetching world names from DB.");
    SQLiteDatabase db = this.dbhelper.getReadableDatabase();
    Cursor cursor = db.query(Gw2DB.WORLD_NAMES_TABLE, null, null, null, null, null, null);
    cursor.moveToFirst();// w  w w  . ja  va 2  s . c om
    HashMap<Integer, String> worldNames = new HashMap<Integer, String>();
    while (!cursor.isLast()) {
        Integer id = cursor.getInt(0);
        String name = cursor.getString(1);
        worldNames.put(id, name);
        cursor.moveToNext();
    }
    cursor.close();
    return worldNames;
}

From source file:com.github.gw2app.events.Gw2ApiEvents.java

private HashMap<Integer, String> _getMapNamesFromDB() {
    Log.d("Gw2", "Fetching map names from DB.");
    SQLiteDatabase db = this.dbhelper.getReadableDatabase();
    Cursor cursor = db.query(Gw2DB.MAP_NAMES_TABLE, null, null, null, null, null, null);
    cursor.moveToFirst();// w  ww  . jav  a  2  s  .c  o m
    HashMap<Integer, String> mapNames = new HashMap<Integer, String>();

    while (!cursor.isLast()) {
        Integer id = cursor.getInt(0);
        String name = cursor.getString(1);
        mapNames.put(id, name);
        cursor.moveToNext();
    }
    cursor.close();
    return mapNames;
}

From source file:edu.uillinois.wseemann.uicombatschedule.MainActivity.java

private String getDateInfo(Date date) {
    String strDate = null;//from ww  w .j av a2  s .  co m
    String info = null;

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);
    int year = cal.get(Calendar.YEAR);

    String stringDate = month + "/" + day + "/" + year;

    Database database = new Database(MainActivity.this);
    SQLiteDatabase db = database.getReadableDatabase();

    Cursor cursor = db.query(Database.DATES_TABLE_NAME, null, Database.DATE + " = ?",
            new String[] { stringDate }, null, null, null);

    if (cursor.moveToNext()) {
        strDate = cursor.getString(cursor.getColumnIndex(Database.DATE));
        info = cursor.getString(cursor.getColumnIndex(Database.INFO));
    }

    cursor.close();

    db.close();
    database.close();

    return info;
}