Example usage for android.database.sqlite SQLiteDatabase rawQuery

List of usage examples for android.database.sqlite SQLiteDatabase rawQuery

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase rawQuery.

Prototype

public Cursor rawQuery(String sql, String[] selectionArgs) 

Source Link

Document

Runs the provided SQL and returns a Cursor over the result set.

Usage

From source file:eu.operando.operandoapp.database.DatabaseHelper.java

public boolean isDomainBlocked(String domain) {
    /*String selectQuery = "SELECT * FROM " + TABLE_DOMAIN_FILTERS
        + " WHERE ((" + KEY_WILDCARD + " = 0 AND " + KEY_CONTENT + " LIKE '%" + domain + "') OR"
                + "(" + KEY_WILDCARD + " = 1 AND ? LIKE '%' || " + KEY_CONTENT + " || '%'))";*/
    String selectQuery = "SELECT * FROM " + TABLE_DOMAIN_FILTERS + " WHERE ? LIKE '%' || " + KEY_CONTENT
            + " || '%'";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = null;/*from w w  w  .j a va2  s.c  o m*/
    try {
        c = db.rawQuery(selectQuery, new String[] { domain });
    } catch (Exception e) {
        e.getMessage();
    }
    int count = c.getCount();
    c.close();
    return (count > 0);
}

From source file:net.smart_json_database.JSONDatabase.java

private void getTagsForJSONEntity(JSONEntity entity, SQLiteDatabase db) {
    ArrayList<String> names = new ArrayList<String>();
    String sql = "SELECT * FROM " + TABLE_REL_TAG_JSON_DATA + " WHERE to_id = ?";
    Cursor c = db.rawQuery(sql, new String[] { "" + entity.getUid() });
    if (c.getCount() > 0) {
        String name = "";
        c.moveToFirst();/*ww  w.  ja  v a 2s .  c o  m*/
        int col_from_id = c.getColumnIndex("from_id");
        do {
            name = invertedTags.get(new Integer(c.getInt(col_from_id)));
            if (name == null) {
                continue;
            }
            if (names.contains(name)) {
                continue;
            }
            names.add(name);
        } while (c.moveToNext());
    }
    c.close();
    if (names.size() > 0) {
        TagRelation relation = new TagRelation();
        relation.init(names);
        entity.setTags(relation);
    }
}

From source file:eu.operando.operandoapp.database.DatabaseHelper.java

public List<String> getStatistics() {
    SQLiteDatabase db = DatabaseHelper.this.getWritableDatabase();
    List<String> result = new ArrayList();
    Cursor c = db.rawQuery("SELECT * FROM " + TABLE_STATISTICS + " WHERE " + KEY_ID + " = 1", null);
    if (c.moveToFirst()) {
        for (int i = 1; i < c.getColumnCount(); i++) { //omit column 0
            result.add(filterName(c.getColumnName(i)) + ": " + c.getInt(i)
                    + (c.getInt(i) == 1 ? " time." : " times."));
        }//from  w w w  . j a va2 s.  c o m
    }
    return result;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public long getLastInsertRecipeId() {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.rawQuery("select max(_id) from " + RECIPES_TABLE, null);
        c.moveToFirst();/*from  www.j ava  2 s .c  o m*/
        long id = c.getLong(0);
        c.close();
        return id;
    }
}

From source file:com.concentricsky.android.khanacademy.app.ManageDownloadsActivity.java

private Cursor getDisplayOptionsCursor(SQLiteOpenHelper helper) {
    SQLiteDatabase db = helper.getReadableDatabase();

    String sql = "select distinct topic._id as _id, topic.title as title from topic, topicvideo, video where video.download_status>? and topicvideo.video_id=video.readable_id and topicvideo.topic_id=topic._id group by title";
    String[] selectionArgs = { String.valueOf(Video.DL_STATUS_NOT_STARTED) };
    Cursor mainCursor = db.rawQuery(sql, selectionArgs);

    sql = "select '-1' as _id, 'All Videos' as title";
    Cursor headerCursor = db.rawQuery(sql, null);

    MergeCursor cursor = new MergeCursor(new Cursor[] { headerCursor, mainCursor });
    return cursor;
}

From source file:it.bradipao.berengar.DbTool.java

public static int db2xml(SQLiteDatabase mDB, File xmlFile) {
    // vars//from   w  w  w  .j a v a2s.c  o m
    final String XML_DATABASE = "database";
    final String XML_DBNAME = "dbname";
    final String XML_TABLES = "tables";
    final String XML_TABLE = "table";
    final String XML_TABLENAME = "tablename";
    final String XML_TABLESQL = "tablesql";
    final String XML_COLSNAME = "colsname";
    final String XML_ROWS = "rows";
    final String XML_ROW = "r";
    final String XML_COL = "c";

    // tables list query and cursor
    int iTableNum = 0;
    FileWriter fw = null;
    BufferedWriter bw = null;
    XmlSerializer sr = Xml.newSerializer();

    String tblquery = "select * from sqlite_master";
    Cursor tblcur = mDB.rawQuery(tblquery, null);
    String rowquery = "";
    Cursor rowcur = null;

    // file writers
    try {
        fw = new FileWriter(xmlFile);
        bw = new BufferedWriter(fw);
        sr.setOutput(bw);
    } catch (FileNotFoundException e) {
        Log.e(LOGTAG, "error in db2gson file writers", e);
    } catch (IOException e) {
        Log.e(LOGTAG, "error in db2gson file writers", e);
    }
    // xml serializer

    try {
        // prepare xml document
        sr.startDocument("UTF-8", true);
        sr.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

        // start document
        sr.startTag("", XML_DATABASE);
        sr.startTag("", XML_DBNAME);
        sr.text(xmlFile.getName());
        sr.endTag("", XML_DBNAME);
        sr.startTag("", XML_TABLES);

        // iterate through tables
        String sTableName = "";
        String sTableSql = "";
        while (tblcur.moveToNext()) {
            sTableName = tblcur.getString(tblcur.getColumnIndex("name"));
            sTableSql = tblcur.getString(tblcur.getColumnIndex("sql"));
            if (GOLOG)
                Log.d(LOGTAG, "TABLE NAME : " + sTableName);
            // skip metadata, sequence, and uidx before exporting tables
            if (!sTableName.equals("android_metadata") && !sTableName.equals("sqlite_sequence")
                    && !sTableName.startsWith("uidx") && !sTableName.startsWith("idx_")
                    && !sTableName.startsWith("_idx")) {

                // table query and cursor
                iTableNum++;
                rowquery = "select * from " + sTableName;
                rowcur = mDB.rawQuery(rowquery, null);
                // exporting table
                sr.startTag("", XML_TABLE);
                sr.startTag("", XML_TABLENAME);
                sr.text(sTableName);
                sr.endTag("", XML_TABLENAME);
                if ((sTableSql != null) && (!sTableSql.isEmpty())) {
                    sr.startTag("", XML_TABLESQL);
                    sr.text(sTableSql);
                    sr.endTag("", XML_TABLESQL);
                }
                // iteratew through rows
                int i = -1;
                while (rowcur.moveToNext()) {
                    // at first element store column names
                    if (i == -1) {
                        sr.startTag("", XML_COLSNAME);
                        for (i = 0; i < rowcur.getColumnCount(); i++) {
                            sr.startTag("", XML_COL);
                            sr.text(rowcur.getColumnName(i));
                            sr.endTag("", XML_COL);
                        }
                        sr.endTag("", XML_COLSNAME);
                        sr.startTag("", XML_ROWS);
                    }
                    // get values
                    sr.startTag("", XML_ROW);
                    for (i = 0; i < rowcur.getColumnCount(); i++) {
                        sr.startTag("", XML_COL);
                        sr.text(rowcur.getString(i));
                        sr.endTag("", XML_COL);
                    }
                    sr.endTag("", XML_ROW);
                }
                // finishing table query
                rowcur.close();
                sr.endTag("", XML_ROWS);
                sr.endTag("", XML_TABLE);

            }
        }
        // finishing table query
        tblcur.close();
        sr.endTag("", XML_TABLES);
        sr.endTag("", XML_DATABASE);

        // finishing
        sr.endDocument();
        sr.flush();

    } catch (Exception e) {
        Log.e(LOGTAG, "error in db2xml", e);
    }

    return iTableNum;
}

From source file:net.smart_json_database.JSONDatabase.java

private void getHasManyRelationsForJSONEntity(JSONEntity entity, SQLiteDatabase db) {
    HashMap<String, HasMany> hasManyRelations = new HashMap<String, HasMany>();
    String sql = "SELECT * FROM " + TABLE_REL_JSON_DATA_JSON_DATA + " WHERE from_id = ?";

    Cursor c = db.rawQuery(sql, new String[] { "" + entity.getUid() });
    if (c.getCount() > 0) {
        String name = "";
        c.moveToFirst();//from  www .  j a  va 2 s.  c o  m
        int col_from_id = c.getColumnIndex("to_id");
        int col_rel_name = c.getColumnIndex("rel_name");
        do {
            name = c.getString(col_rel_name);
            if (hasManyRelations.containsKey(name)) {
                hasManyRelations.get(name).put(c.getInt(col_from_id));
            } else {
                hasManyRelations.put(name, new HasMany(name));
                hasManyRelations.get(name).put(c.getInt(col_from_id));
            }
        } while (c.moveToNext());
    }
    c.close();
    entity.setHasManyRelations(hasManyRelations);
}

From source file:net.smart_json_database.JSONDatabase.java

private void getBelongsToRelationsForJSONEntity(JSONEntity entity, SQLiteDatabase db) {
    HashMap<String, BelongsTo> belongsToRelations = new HashMap<String, BelongsTo>();
    String sql = "SELECT * FROM " + TABLE_REL_JSON_DATA_JSON_DATA + " WHERE to_id = ?";

    Cursor c = db.rawQuery(sql, new String[] { "" + entity.getUid() });
    if (c.getCount() > 0) {
        String name = "";
        c.moveToFirst();/* ww  w.j av  a 2 s. co  m*/
        int col_from_id = c.getColumnIndex("from_id");
        int col_rel_name = c.getColumnIndex("rel_name");
        do {
            name = c.getString(col_rel_name);
            if (belongsToRelations.containsKey(name)) {
                belongsToRelations.get(name).put(c.getInt(col_from_id));
            } else {
                belongsToRelations.put(name, new BelongsTo(name));
                belongsToRelations.get(name).put(c.getInt(col_from_id));
            }
        } while (c.moveToNext());
    }
    c.close();
    entity.setBelongsToRelations(belongsToRelations);

}

From source file:com.money.manager.ex.database.MmxOpenHelper.java

private void initBaseCurrency(SQLiteDatabase db) {
    // currencies
    CurrencyService currencyService = new CurrencyService(getContext());
    Currency systemCurrency = currencyService.getSystemDefaultCurrency();
    if (systemCurrency == null)
        return;/*from  www. j  a  v a  2  s.c o m*/

    InfoService infoService = new InfoService(getContext());

    // todo: try query generator.
    //        String sql = new Select()
    //                .select()
    //                .from(InfoRepositorySql.TABLE_NAME)
    //                .where(Info.INFONAME + "=?", InfoKeys.BASECURRENCYID)
    //                .toString();

    Cursor currencyCursor = db.rawQuery(
            "SELECT * FROM " + InfoRepositorySql.TABLE_NAME + " WHERE " + Info.INFONAME + "=?",
            new String[] { InfoKeys.BASECURRENCYID });
    if (currencyCursor == null)
        return;

    // Get id of the base currency record.
    int recordId = Constants.NOT_SET;
    boolean recordExists = currencyCursor.moveToFirst();
    if (recordExists) {
        recordId = currencyCursor.getInt(currencyCursor.getColumnIndex(Info.INFOID));
    }
    currencyCursor.close();

    // Use the system default currency.
    int currencyId = currencyService.loadCurrencyIdFromSymbolRaw(db, systemCurrency.getCurrencyCode());
    if (currencyId == Constants.NOT_SET) {
        // Use Euro by default.
        currencyId = 2;
    }

    UIHelper uiHelper = new UIHelper(getContext());

    // Insert/update base currency record into info table.
    if (!recordExists) {
        long newId = infoService.insertRaw(db, InfoKeys.BASECURRENCYID, currencyId);
        if (newId <= 0) {
            uiHelper.showToast("error inserting base currency on init");
        }
    } else {
        // Update the (by default empty) record to the default currency.
        long updatedRecords = infoService.updateRaw(db, recordId, InfoKeys.BASECURRENCYID, currencyId);
        if (updatedRecords <= 0) {
            uiHelper.showToast("error updating base currency on init");
        }
    }

    // Can't use provider here as the database is not ready.
    //            int currencyId = currencyService.loadCurrencyIdFromSymbol(systemCurrency.getCurrencyCode());
    //            String baseCurrencyId = infoService.getInfoValue(InfoService.BASECURRENCYID);
    //            if (!StringUtils.isEmpty(baseCurrencyId)) return;
    //            infoService.setInfoValue(InfoService.BASECURRENCYID, Integer.toString(currencyId));
}

From source file:eu.operando.operandoapp.database.DatabaseHelper.java

public DomainFilter getDomainFilter(long id) {
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT  * FROM " + TABLE_DOMAIN_FILTERS + " WHERE " + KEY_ID + " = " + id;

    Cursor c = db.rawQuery(selectQuery, null);

    if (c != null)
        c.moveToFirst();/*from   w  ww  .  j av a 2 s.co m*/

    DomainFilter domainFilter = new DomainFilter();
    domainFilter.setId(c.getInt(c.getColumnIndex(KEY_ID)));
    domainFilter.setContent((c.getString(c.getColumnIndex(KEY_CONTENT))));
    domainFilter.setSource((c.getString(c.getColumnIndex(KEY_SOURCE))));
    domainFilter.setModified(c.getString(c.getColumnIndex(KEY_MODIFIED)));
    domainFilter.setWildcard((c.getInt(c.getColumnIndex(KEY_WILDCARD))));

    return domainFilter;
}