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:com.acrylicgoat.scrumnotes.MainActivity.java

private void saveNote() {
    ContentValues values = new ContentValues();

    String text = today.getText().toString() + " ";
    //Log.d("NoteEditorActivity", "note: " + text);
    int length = text.length();

    if (length == 0 || text.contains("To get started, select Tools") || text.equals("Yesterday: \n\nToday: ")) {
        //Toast.makeText(this, "Nothing to save.", Toast.LENGTH_SHORT).show();
        return;/*from  w  w w .j  av a 2s  .  c  o  m*/
    }

    values.put(Notes.NOTE, text);
    values.put(Notes.OWNER, currentOwner);

    //check if a note already exists for today
    DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    cursor = db.rawQuery(getTodaySQL(), null);
    if (cursor.getCount() > 0) {
        //Log.d("MainActivity", "saveNote(): doing update ");
        StringBuilder sb = new StringBuilder();
        sb.append("update notes set notes_note = '");
        sb.append(ScrumNotesUtil.escape(text));
        sb.append("' where notes_owner='");
        sb.append(currentOwner);
        sb.append("' and date(notes_date) = date('now','localtime')");
        dbHelper.getReadableDatabase().execSQL(sb.toString());
    } else {
        getContentResolver().insert(Notes.CONTENT_URI, values);
    }
    cursor.close();
    db.close();

}

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

private void initCategories(SQLiteDatabase database) {
    try {/*ww  w. j  a  v a  2s  .  co  m*/
        Cursor countCategories = database.rawQuery("SELECT * FROM CATEGORY_V1", null);
        if (countCategories == null || countCategories.getCount() > 0)
            return;

        int keyCategory = 0;
        String[] categories = new String[] { "1;1", "2;1", "3;1", "4;1", "5;1", "6;1", "7;1", "8;2", "9;2",
                "10;3", "11;3", "12;3", "13;4", "14;4", "15;4", "16;4", "17;5", "18;5", "19;5", "20;6", "21;6",
                "22;6", "23;7", "24;7", "25;7", "26;7", "27;7", "28;8", "29;8", "30;8", "31;8", "32;9", "33;9",
                "34;9", "35;10", "36;10", "37;10", "38;10", "39;13", "40;13", "41;13" };

        for (String item : categories) {
            int subCategoryId = Integer.parseInt(item.substring(0, item.indexOf(";")));
            int categoryId = Integer.parseInt(item.substring(item.indexOf(";") + 1));

            if (categoryId != keyCategory) {
                keyCategory = categoryId;
                int idStringCategory = mContext.getResources().getIdentifier(
                        "category_" + Integer.toString(categoryId), "string", mContext.getPackageName());

                if (idStringCategory > 0) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(Category.CATEGID, categoryId);
                    contentValues.put(Category.CATEGNAME, mContext.getString(idStringCategory));

                    // Update existing records, inserted via the db creation script.
                    int updated = database.update(CategoryRepository.tableName, contentValues,
                            Category.CATEGID + "=?", new String[] { Integer.toString(categoryId) });
                    if (updated <= 0) {
                        Timber.w("updating %s for category %s", contentValues.toString(),
                                Integer.toString(categoryId));
                    }
                }
            }

            int idStringSubcategory = mContext.getResources().getIdentifier(
                    "subcategory_" + Integer.toString(subCategoryId), "string", mContext.getPackageName());
            if (idStringSubcategory > 0) {
                ContentValues contentValues = new ContentValues();
                contentValues.put(Subcategory.SUBCATEGID, subCategoryId);
                contentValues.put(Subcategory.CATEGID, categoryId);
                contentValues.put(Subcategory.SUBCATEGNAME, mContext.getString(idStringSubcategory));

                int updated = database.update(SubcategoryRepository.tableName, contentValues,
                        Subcategory.SUBCATEGID + "=?", new String[] { Integer.toString(subCategoryId) });
                if (updated <= 0) {
                    Timber.w("update failed, %s for subcategory %s", contentValues.toString(),
                            Integer.toString(subCategoryId));
                }
            }
        }

        countCategories.close();
    } catch (Exception e) {
        Timber.e(e, "init database, categories");
    }
}

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

public int getMessageAmount(String buddyId) {
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    try {//w w w .  ja va 2 s.c o  m
        Cursor c = db.rawQuery("SELECT * FROM " + buddyId, null);
        int cnt = c.getCount();
        c.close();
        db.close();
        return cnt;
    } catch (Exception e) {
        return 0;
    }
}

From source file:bus_vn.gena.bus_vn.com.bus_vn.tabs.Tab_list_bus.java

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    if (type.equals("listBus")) {
        //?  intent ?    ? ?  
        Intent intent = new Intent(getActivity(), List_bus_stop.class);
        String numberBus = simpleAdapter.getItem(position).toString();
        numberBus = numberBus.substring(32, numberBus.length() - 1);
        numberBus = numberBus.replaceAll(" ", "");

        Context context = getActivity();
        DbOpenHelper dbOpenHelper = new DbOpenHelper(context);
        SQLiteDatabase db;
        db = dbOpenHelper.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.clear();//from  w  w w  .j a  v a  2  s  .  com
        String st = "";
        st = "SELECT bus_path_table.id FROM bus_path_table ";
        st = st + " WHERE bus_path_table.Name='" + numberBus + "'";
        st = st + " AND bus_path_table.Type_transport_id='" + typeTransport + "'";
        Cursor c = db.rawQuery(st, null);
        String busPathId = null;
        while (c.moveToNext()) {
            busPathId = c.getString(0);
        }
        intent.putExtra("busPathId", busPathId);
        //?  ? ?  
        startActivity(intent);
    } else {
        //?    ? 
        //?  intent ?    ? ?  
        Intent intent = new Intent(getActivity(), Scheme.class);
        String numberBus = simpleAdapter.getItem(position).toString();
        numberBus = numberBus.substring(32, numberBus.length() - 1);
        numberBus = numberBus.replaceAll(" ", "");
        intent.putExtra("numberBus", numberBus);
        intent.putExtra("typeTransport", typeTransport);
        startActivity(intent);
    }
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static void updateStarredThread(boolean starred, String clean_subject, int groupid, Context context) {
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbWrite = db.getWritableDatabase();

    clean_subject = clean_subject.replace("'", "''");

    String query;//from ww w .  j ava 2s  . c o m

    if (starred == false) {
        query = "DELETE FROM starred_threads WHERE subscribed_group_id=" + groupid + " AND clean_subject="
                + esc(clean_subject);
        dbWrite.execSQL(query);
    } else {
        // Check that it's not already on the table
        query = "SELECT _ID FROM starred_threads WHERE subscribed_group_id=" + groupid + " AND clean_subject="
                + esc(clean_subject);
        Cursor c = dbWrite.rawQuery(query, null);

        if (c.getCount() == 0) {
            ContentValues cv = new ContentValues();
            cv.put("subscribed_group_id", groupid);
            cv.put("clean_subject", clean_subject);
            dbWrite.insert("starred_threads", null, cv);
        }
        c.close();
    }
    dbWrite.close();
    db.close();
}

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

public static JSONObject db2json(SQLiteDatabase mDB, String sDbName) {
    // vars/*from   w  w w .  jav  a  2  s . c  o m*/
    JSONObject jsonDB = new JSONObject();
    JSONArray jsonNameTables = new JSONArray();
    JSONArray jsonTables = new JSONArray();

    // read tables
    String sqlquery = "select * from sqlite_master";
    Cursor cur = mDB.rawQuery(sqlquery, null);
    // iterate through tables
    int iTableNum = 0;
    String sTableName = "";
    String sTableSql = "";
    while (cur.moveToNext()) {
        sTableName = cur.getString(cur.getColumnIndex("name"));
        sTableSql = cur.getString(cur.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")) {
            // add new table
            iTableNum++;
            jsonNameTables.put(sTableName);
            // try exporting table
            jsonTables.put(table2json(mDB, sTableName, sTableSql));
        }
    }
    cur.close();

    // final json building
    try {
        // json db format
        jsonDB.put("jsondb_format", "1");
        // database name
        if ((sDbName != null) && (!sDbName.isEmpty()))
            jsonDB.put("db_name", sDbName);
        else
            jsonDB.put("db_name", "database.sqlite");
        // tables number and name
        jsonDB.put("tables_num", String.valueOf(iTableNum));
        jsonDB.put("tables_name", jsonNameTables);
        // tables
        jsonDB.put("tables", jsonTables);
    } catch (JSONException e) {
        Log.e(LOGTAG, "error in db2json", e);
    }

    // return String
    return jsonDB;
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static void logSentMessage(String msgId, String group, Context context) {
    int groupid = getGroupIdFromName(group, context);

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    /* Check first that the number of logged messages for this group is not greater than the 
    * limit impossed per group, because if it's greater we must delete number-limit older logs
    * until the table only has the limit. This is done this way because on the MessageList a set
    * is built with the post messages from that group, and then every loaded message's msgId is checked 
    * to see if it's in the set (to check for replies to our messages), so allowing it to grow too much
    * could make the MessageView slow/*from  w ww. j a  v a 2s.c  o m*/
    */

    Cursor c = dbwrite.rawQuery(
            "SELECT _id FROM sent_posts_log WHERE subscribed_group_id=" + groupid + " ORDER BY _id", null);
    int count = c.getCount();
    int toKill = count - UsenetConstants.SENT_POSTS_LOG_LIMIT_PER_GROUP;
    int kennyId;

    if (toKill > 0) {
        // Delete some more than needed so we don't have to do this on every post sent
        toKill += UsenetConstants.SENT_POST_KILL_ADITIONAL;
        c.moveToFirst();

        for (int i = 0; i < toKill; i++) {
            kennyId = c.getInt(0);
            dbwrite.execSQL("DELETE FROM sent_posts_log WHERE _id=" + kennyId);
            c.moveToNext();
        }
    }
    c.close();

    // Now we have room for sure, insert the log
    ContentValues cv = new ContentValues(2);
    cv.put("server_article_id", msgId);
    cv.put("subscribed_group_id", groupid);
    dbwrite.insert("sent_posts_log", null, cv);

    dbwrite.close();
    db.close();
}

From source file:com.barcamppenang2014.tabfragment.ProfileFragment.java

License:asdf

public String[] fillTextField() {
    String[] myInfo = new String[5];

    MyDatabase database = new MyDatabase(getActivity());
    SQLiteDatabase sqliteDatabase = database.getReadableDatabase();
    String sql = "SELECT * FROM USERPROFILE;";
    Cursor retrieved = sqliteDatabase.rawQuery(sql, null);

    // Log.d("yc","row of cursor in database is "+
    // Integer.toString(retrieved.getCount()));

    // If cursor is not null
    while (retrieved.moveToNext()) {

        myInfo[0] = retrieved.getString(retrieved.getColumnIndex("MYNAME"));
        myInfo[1] = retrieved.getString(retrieved.getColumnIndex("MYEMAIL"));
        myInfo[2] = retrieved.getString(retrieved.getColumnIndex("MYPHONE"));
        myInfo[3] = retrieved.getString(retrieved.getColumnIndex("MYPROFESSION"));
        myInfo[4] = retrieved.getString(retrieved.getColumnIndex("MYFBID"));
        // myInfo[5] =
        // retrieved.getString(retrieved.getColumnIndex("MYURI"));

    }//  w w  w  . j  ava 2 s .  c  o  m

    retrieved.close();
    database.close();
    sqliteDatabase.close();

    return myInfo;

}

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

public static JSONObject table2json(SQLiteDatabase mDB, String sTableName, String sTableSql) {
    // vars/*from   w w w  . j  av  a 2s .c o  m*/
    JSONObject jsonTable = new JSONObject();
    JSONArray jsonRows = new JSONArray();
    JSONArray jsonColsName = new JSONArray();
    JSONArray jsonCols = null;

    // read table
    String sqlquery = "select * from " + sTableName;
    Cursor cur = mDB.rawQuery(sqlquery, null);
    // iteratew through rows
    int i = -1;
    while (cur.moveToNext()) {
        // at first element store column names
        if (i == -1)
            for (i = 0; i < cur.getColumnCount(); i++) {
                jsonColsName.put(cur.getColumnName(i));
            }
        // get values
        jsonCols = new JSONArray();
        for (i = 0; i < cur.getColumnCount(); i++) {
            jsonCols.put(cur.getString(i));
        }
        // add values to rows array
        jsonRows.put(jsonCols);
    }

    // final json building
    try {
        // table name
        jsonTable.put("table_name", sTableName);
        // code for create table
        if ((sTableSql != null) && (!sTableSql.isEmpty()))
            jsonTable.put("table_sql", sTableSql);
        // columns name
        jsonTable.put("cols_name", jsonColsName);
        // rows
        jsonTable.put("rows", jsonRows);
    } catch (JSONException e) {
        Log.e(LOGTAG, "error in table2json", e);
    }

    // return String
    return jsonTable;
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static void expireReadMessages(Context context, boolean expireAll, long expireTime) {

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    // Get all the expired messages so we can delete bodies and attachments
    long currentTime = System.currentTimeMillis();
    String q = null;//from   w  ww  .  j a  v  a  2 s .  c  om

    if (expireAll) {
        q = "SELECT _id, subscribed_group_id, has_attachments, attachments_fnames " + "FROM headers "
                + "WHERE read=1 AND catched=1";
    } else {
        q = "SELECT _id, subscribed_group_id, has_attachments, attachments_fnames " + "FROM headers "
                + "WHERE read=1 AND catched=1 AND read_unixdate < " + currentTime + " - " + expireTime;
    }

    Cursor c = dbwrite.rawQuery(q, null);

    int count = c.getCount();
    c.moveToFirst();
    String groupname;

    for (int i = 0; i < count; i++) {

        groupname = getGroupNameFromId(c.getInt(1) /*subscribed_group_id*/, context);
        FSUtils.deleteCacheMessage(c.getInt(0)/* _id */, groupname);

        if (c.getInt(2)/*has_attach*/ == 1) {
            FSUtils.deleteAttachments(c.getString(3) /*attachments_fnames*/, groupname);
        }

        c.moveToNext();
    }

    if (expireAll)
        q = "DELETE FROM headers WHERE read=1";
    else
        q = "DELETE FROM headers WHERE read=1 AND read_unixdate < " + currentTime + " - " + expireTime;
    dbwrite.execSQL(q);
    c.close();
    dbwrite.close();
    db.close();
}