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:org.akop.crosswords.Storage.java

public Crossword.State getPuzzleState(long puzzleId) {
    long started = SystemClock.uptimeMillis();

    Crossword.State state = mStateCache.get((int) puzzleId);
    if (state == null) {
        StorageHelper helper = getHelper();
        SQLiteDatabase db = helper.getReadableDatabase();

        try {/* w w  w. j av  a2 s  .c  o  m*/
            Cursor cursor = db.query(PuzzleState.TABLE, new String[] { PuzzleState.CLASS, PuzzleState.OBJECT, },
                    PuzzleState.PUZZLE_ID + "=" + puzzleId, null, null, null, null);

            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        state = mGson.fromJson(cursor.getString(1), Crossword.State.class);
                        mStateCache.put((int) puzzleId, new Crossword.State(state));
                    }
                } finally {
                    cursor.close();
                }
            }
        } finally {
            db.close();
        }
    }

    if (state != null) {
        Crosswords.logv("Loaded state for %d (%dms)", puzzleId, SystemClock.uptimeMillis() - started);
    }

    return state;
}

From source file:com.project.android.dpla.mama_dpla.DataManager.java

/**
 * Complete variable mItems_ with tags by accessing local db
 * Called by getSearchResultsWithTags (String keyword, Context activityContext)
 * @param activityContext : context of the activity that calls this function
 *///from   ww  w .j a v a  2s. co  m
public void updateResultsWithTags(Context activityContext) {
    int items_len = mItems_.size();

    // Open database for read
    MAMADbHelper helper = new MAMADbHelper(activityContext);
    SQLiteDatabase db = helper.getReadableDatabase();

    // iterate mItems_ arraylist to fill each item
    for (int iter = 0; iter < items_len; iter++) {
        DPLAItem curr_item = mItems_.get(iter);
        String selection = MAMAContract.ItemEntry.COLUMN_NAME_ITEMATID + " = ?";
        String[] selectionArgs = { curr_item.getId() };
        Cursor cur = db.query(MAMAContract.ItemEntry.TABLE_NAME, MAMAContract.ItemEntry.ALL_COLUMS, selection,
                selectionArgs, null, null, null);
        if (cur.getCount() == 0) { // If there are no tags, set null
            curr_item.setTags(null);
        } else {
            cur.moveToFirst();
            curr_item.setTags(cur.getString(MAMAContract.ItemEntry.TAG_COLUMN_NUMBER));
            Log.d(TAG, curr_item.getTags());
        }
    }
}

From source file:org.akop.crosswords.Storage.java

public Crossword getPuzzle(long puzzleId) {
    long started = SystemClock.uptimeMillis();

    Crossword crossword = mPuzzleCache.get((int) puzzleId);
    if (crossword == null) {
        StorageHelper helper = getHelper();
        SQLiteDatabase db = helper.getReadableDatabase();

        try {/*from  w ww .  j ava2 s.co  m*/
            Cursor cursor = db.query(Puzzle.TABLE, new String[] { Puzzle.CLASS, Puzzle.OBJECT, },
                    Puzzle._ID + " = " + puzzleId, null, null, null, null);

            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        crossword = mGson.fromJson(cursor.getString(1), Crossword.class);
                        mPuzzleCache.put((int) puzzleId, crossword);
                    }
                } finally {
                    cursor.close();
                }
            }
        } finally {
            db.close();
        }
    }

    if (crossword != null) {
        Crosswords.logv("Loaded crossword %s (%dms)", crossword.getHash(),
                SystemClock.uptimeMillis() - started);
    }

    return crossword;
}

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * Return a Cursor object which contains all fields of an alert, for all
 * alerts in the database. It is perfectly possible that no alerts exist,
 * therefore an empty Cursor is returned.
 * /*from   ww  w  .j  a  v  a2s .  c  o m*/
 * @return A Cursor containing all alerts known in the database.
 */
public Cursor getAllAlerts() {
    final SQLiteDatabase db = getWritableDatabase();

    cleanupAlerts(db);
    return db.query(ALERTS_TABLE, null, null, null, null, null, null);
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public ChatEntry[] getChats() {
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor chats = db.query(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS,
            new String[] { MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID,
                    MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME },
            null, null, null, null, MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME);
    int chatCount = chats.getCount();
    ChatEntry[] resultChats = new ChatEntry[chatCount];
    int i = 0;//from  w  w w.  j av  a  2  s .co m
    chats.moveToFirst();
    if (chats.getCount() > 0)
        do {
            String buddyId = chats.getString(0);
            String name = chats.getString(1);
            MessageArrayContent mac = getLastMessage(buddyId);

            if (mac instanceof TextMessage) {
                TextMessage msg = (TextMessage) mac;

                String lastMessageDate;
                Date msgTime = new Date(msg.time);
                Calendar startOfDay = Calendar.getInstance();
                startOfDay.set(Calendar.HOUR_OF_DAY, 0);
                startOfDay.set(Calendar.MINUTE, 0);
                startOfDay.set(Calendar.SECOND, 0);
                startOfDay.set(Calendar.MILLISECOND, 0);
                long diff = startOfDay.getTimeInMillis() - msgTime.getTime();
                if (diff <= 0)
                    lastMessageDate = String.format(context.getResources().getString(R.string.time), msgTime);
                else if (diff > 1000 * 60 * 60 * 24)
                    lastMessageDate = String.format(context.getResources().getString(R.string.date), msgTime);
                else
                    lastMessageDate = context.getResources().getString(R.string.last_message_yesterday);

                resultChats[i] = new ChatEntry(buddyId, name, MessageHistory.TYPE_TEXT, msg.status,
                        lastMessageDate, ((msg.left) ? name + ": " : "") + msg.message, !msg.left);
            } else if (mac instanceof ImageMessage) {
                ImageMessage msg = (ImageMessage) mac;

                String lastMessageDate;
                Date msgTime = new Date(msg.time);
                Calendar startOfDay = Calendar.getInstance();
                startOfDay.set(Calendar.HOUR_OF_DAY, 0);
                startOfDay.set(Calendar.MINUTE, 0);
                startOfDay.set(Calendar.SECOND, 0);
                startOfDay.set(Calendar.MILLISECOND, 0);
                long diff = startOfDay.getTimeInMillis() - msgTime.getTime();
                if (diff <= 0)
                    lastMessageDate = String.format(context.getResources().getString(R.string.time), msgTime);
                else if (diff > 1000 * 60 * 60 * 24)
                    lastMessageDate = String.format(context.getResources().getString(R.string.date), msgTime);
                else
                    lastMessageDate = context.getResources().getString(R.string.last_message_yesterday);
                msg.description += "".equals(msg.description) ? context.getResources().getString(R.string.image)
                        : "";

                resultChats[i] = new ChatEntry(buddyId, name, MessageHistory.TYPE_IMAGE, msg.status,
                        lastMessageDate, msg.description, !msg.left);
            }
            i++;
        } while (chats.move(1));
    chats.close();
    db.close();
    return resultChats;
}

From source file:org.akop.crosswords.Storage.java

public long findByHash(String hash) {
    StorageHelper helper = getHelper();//from  w w  w.ja va2 s. c  o  m
    SQLiteDatabase db = helper.getReadableDatabase();
    long id = ID_NOT_FOUND;

    try {
        Cursor cursor = db.query(Puzzle.TABLE, new String[] { Puzzle._ID }, Puzzle.HASH + "=?",
                new String[] { hash }, null, null, null);

        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    id = cursor.getLong(0);
                }
            } finally {
                cursor.close();
            }
        }
    } finally {
        db.close();
    }

    return id;
}

From source file:org.akop.crosswords.Storage.java

public long findBySourceUrl(String sourceUrl) {
    StorageHelper helper = getHelper();/*w  w  w .  ja v a2 s. com*/
    SQLiteDatabase db = helper.getReadableDatabase();
    long id = ID_NOT_FOUND;

    try {
        Cursor cursor = db.query(Puzzle.TABLE, new String[] { Puzzle._ID }, Puzzle.SOURCE_URL + " = ?",
                new String[] { sourceUrl }, null, null, null);

        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    id = cursor.getLong(0);
                }
            } finally {
                cursor.close();
            }
        }
    } finally {
        db.close();
    }

    return id;
}

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * Check to see if an alert of a particular type exists at the given
 * stopCode. The type is either/*from  ww  w .  j  a  va2 s  . c  o m*/
 * {@link SettingsDatabase#ALERTS_TYPE_PROXIMITY} or
 * {@link SettingsDatabase#ALERTS_TYPE_TIME}
 * 
 * @param stopCode The stopCode to check against.
 * @param type The type of alert. See this method's description.
 * @return True if the alert exists, false if it doesn't.
 * @see SettingsDatabase#ALERTS_TYPE_PROXIMITY
 * @see SettingsDatabase#ALERTS_TYPE_TIME
 */
public boolean isActiveAlertOfType(final String stopCode, final int type) {
    if (stopCode == null || stopCode.length() == 0)
        return false;
    final SQLiteDatabase db = getWritableDatabase();
    cleanupAlerts(db);
    final Cursor c = db.query(ALERTS_TABLE, new String[] { ALERTS_STOPCODE },
            ALERTS_STOPCODE + " = ? AND " + ALERTS_TYPE + " = ?",
            new String[] { stopCode, String.valueOf(type) }, null, null, null);
    if (c.getCount() > 0) {
        c.close();
        return true;
    }

    c.close();
    return false;
}

From source file:simonlang.coastdove.usagestatistics.ui.app_details.SQLiteTableLoader.java

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

    String[] projection = { AppUsageContract.AppTable._ID, AppUsageContract.AppTable.COLUMN_NAME_TIMESTAMP,
            AppUsageContract.AppTable.COLUMN_NAME_PACKAGE, AppUsageContract.AppTable.COLUMN_NAME_DURATION };
    String selection = AppUsageContract.AppTable.COLUMN_NAME_PACKAGE + "=?";
    String[] selectionArgs = { this.appPackageName };
    String sortOrder = AppUsageContract.AppTable.COLUMN_NAME_TIMESTAMP + " ASC";

    Cursor c = db.query(AppUsageContract.AppTable.TABLE_NAME, projection, selection, selectionArgs, null, null,
            sortOrder);// ww  w . ja va2 s  . c  o  m

    // Extract all data from the cursor, so we can close the database
    ArrayList<AppUsageDataUIContainer> data = new ArrayList<>(c.getCount());
    c.moveToFirst();
    while (!c.isAfterLast()) {
        int timestampIndex = c.getColumnIndex(AppUsageContract.AppTable.COLUMN_NAME_TIMESTAMP);
        int idIndex = c.getColumnIndex(AppUsageContract.AppTable._ID);
        int durationIndex = c.getColumnIndex(AppUsageContract.AppTable.COLUMN_NAME_DURATION);
        long duration = c.getLong(durationIndex);
        String durationString = Misc.msToDurationString(duration);
        data.add(new AppUsageDataUIContainer(c.getInt(idIndex), c.getString(timestampIndex), durationString));

        c.moveToNext();
    }

    db.close();

    return data;
}

From source file:mmpud.project.daycountwidget.DayCountMainActivity.java

private void updateAdapter() {
    mAdapter.clear();/* w w  w  .  ja  va  2 s  .c  o  m*/
    // query from database
    if (mDbHelper == null) {
        mDbHelper = new DayCountDbHelper(this);
    }
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    // get all available day count widget ids
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    ComponentName component = new ComponentName(this, DayCountWidgetProvider.class);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(component);
    for (int appWidgetId : appWidgetIds) {
        Cursor cursor = db.query(Contract.Widget.TABLE_NAME, null, Contract.Widget.WIDGET_ID + "=?",
                new String[] { String.valueOf(appWidgetId) }, null, null, null);
        long targetDateMillis;
        String title;
        String bodyStyle;
        int countBy;
        if (cursor.moveToFirst()) {
            targetDateMillis = cursor.getLong(cursor.getColumnIndexOrThrow(TARGET_DATE));
            title = cursor.getString(cursor.getColumnIndexOrThrow(EVENT_TITLE));
            bodyStyle = cursor.getString(cursor.getColumnIndexOrThrow(BODY_STYLE));
            countBy = cursor.getInt(cursor.getColumnIndexOrThrow(COUNT_BY));
        } else {
            targetDateMillis = LocalDate.now().atStartOfDay().atZone(ZoneOffset.UTC).toInstant().toEpochMilli();
            title = "";
            bodyStyle = String.valueOf(ContextCompat.getColor(this, R.color.body_black));
            countBy = COUNT_BY_DAY;
        }
        mAdapter.add(new DayCountWidget(appWidgetId, title, null, targetDateMillis, countBy, null, bodyStyle));
        cursor.close();
    }
    db.close();
}