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 ResponseFilter getResponseFilter(long id) {
    SQLiteDatabase db = this.getReadableDatabase();

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

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

    if (c != null)
        c.moveToFirst();//  w  w w .j a va  2s  .  c  o  m

    ResponseFilter responseFilter = new ResponseFilter();
    responseFilter.setId(c.getInt(c.getColumnIndex(KEY_ID)));
    responseFilter.setContent((c.getString(c.getColumnIndex(KEY_CONTENT))));
    responseFilter.setSource((c.getString(c.getColumnIndex(KEY_SOURCE))));
    responseFilter.setModified(c.getString(c.getColumnIndex(KEY_MODIFIED)));

    return responseFilter;
}

From source file:com.ideateam.plugin.DownloadDB.java

private void ReplaceDB() {

    Log.d(TAG, "..Get physical DB name and path. zipPath " + zipPath);

    String dbPath = zipPath.substring(0, zipPath.lastIndexOf("/")) + "/app_database/";
    SQLiteDatabase master_db = null;
    String field = "path";

    Log.d(TAG, dbPath + "Databases.db");
    File file = new File(dbPath + "Databases.db");

    if (!file.exists()) {

        Log.d(TAG, "Databases.db not found");
        field = "id";
        dbPath = zipPath.substring(0, zipPath.lastIndexOf("/")) + "/app_webview/databases/";
    }/*www.j  a va2s  . c om*/

    try {
        master_db = SQLiteDatabase.openDatabase(dbPath + "Databases.db", null, SQLiteDatabase.OPEN_READONLY);
    } catch (Exception e) {

    }

    if (master_db != null) {
        Cursor c = master_db.rawQuery("SELECT origin, " + field + " FROM Databases WHERE name='" + dbName + "'",
                null);
        c.moveToFirst();

        cordovaDBPath = dbPath + c.getString(0) + "/";
        cordovaDBName = c.getString(1);

        if (field == "id") {
            field += ".db";
        }

        c.close();
        master_db.close();

        Log.d(TAG, ": " + cordovaDBPath + cordovaDBName);

    }
}

From source file:com.odoo.core.orm.OModel.java

public List<ODataRow> query(String query, String[] args) {
    List<ODataRow> rows = new ArrayList<>();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cr = db.rawQuery(query, args);
    try {//from ww  w  .ja v  a 2s.c o m
        if (cr.moveToFirst()) {
            do {
                rows.add(OCursorUtils.toDatarow(cr));
            } while (cr.moveToNext());
        }
    } finally {
        cr.close();
    }
    return rows;

}

From source file:com.money.manager.ex.MmxContentProvider.java

private Cursor query_internal(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {/*from  w  w  w.ja va2  s  . c om*/
    Timber.d("Querying URI: %s", uri);

    // find object from uri
    Object sourceObject = getObjectFromUri(uri);

    initializeDependencies();

    SQLiteDatabase database = openHelper.get().getReadableDatabase();
    if (database == null) {
        Timber.e("Database could not be opened");
        return null;
    }

    Cursor cursor;

    // check type of instance data set
    if (Dataset.class.isInstance(sourceObject)) {
        Dataset dataset = ((Dataset) sourceObject);

        //            logQuery(dataset, projection, selection, selectionArgs, sortOrder);

        switch (dataset.getType()) {
        case QUERY:
            String query = prepareQuery(dataset.getSource(), projection, selection, sortOrder);
            cursor = database.rawQuery(query, selectionArgs);
            break;
        case SQL:
            cursor = database.rawQuery(selection, selectionArgs);
            break;
        case TABLE:
        case VIEW:
            SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
            queryBuilder.setTables(dataset.getSource());
            cursor = queryBuilder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
            break;
        default:
            throw new IllegalArgumentException("Type of dataset not defined");
        }
    } else {
        throw new IllegalArgumentException("Object sourceObject of mapContent is not instance of dataset");
    }

    // notify listeners waiting for the data is ready
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    if (!cursor.isClosed()) {
        Timber.d("Rows returned: %d", cursor.getCount());
    }

    return cursor;
}

From source file:net.gaast.giggity.Db.java

private void updateSchedule(SQLiteDatabase db, Seed.Schedule sched, int last_version) {
    if (sched.start.equals(sched.end)) {
        /* If it's one day only, avoid having start == end. Pretend it's from 6:00 'til 18:00 or something. */
        sched.start.setHours(6);//  www .  ja  va  2s .  c  o  m
        sched.end.setHours(18);
    } else {
        /* For different days, pretend the even't from noon to noon. In both cases, we'll have exact times
         * once we load the schedule for the first time. */
        sched.start.setHours(12);
        sched.end.setHours(12);
    }
    Cursor q = db.rawQuery("Select sch_id From schedule Where sch_url = ?", new String[] { sched.url });
    Log.d("cursor", "" + q.getCount());
    if (sched.version > last_version && q.getCount() == 0) {
        ContentValues row = new ContentValues();
        if (sched.id != null)
            row.put("sch_id_s", sched.id);
        else
            row.put("sch_id_s", Schedule.hashify(sched.url));
        row.put("sch_url", sched.url);
        row.put("sch_title", sched.title);
        row.put("sch_atime", sched.start.getTime() / 1000);
        row.put("sch_start", sched.start.getTime() / 1000);
        row.put("sch_end", sched.end.getTime() / 1000);
        row.put("sch_metadata", sched.metadata);
        db.insert("schedule", null, row);
    } else if (q.getCount() == 1) {
        q.moveToNext();
        if (oldDbVer < 8) {
            /* We're upgrading from < 8 so we have to backfill the start/end columns. */
            ContentValues row = new ContentValues();
            row.put("sch_start", sched.start.getTime() / 1000);
            row.put("sch_end", sched.end.getTime() / 1000);
            db.update("schedule", row, "sch_id = ?", new String[] { q.getString(0) });
        }

        /* Always refresh the metadata, seedfile is authoritative. */
        if (sched.metadata != "") {
            ContentValues row = new ContentValues();
            row.put("sch_metadata", sched.metadata);
            db.update("schedule", row, "sch_id = ?", new String[] { q.getString(0) });
        }
    }
    q.close();
}

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

public static int db2gson(SQLiteDatabase mDB, File jsonFile) {
    // vars/* www . j a v  a2s. c  o m*/
    int iTableNum = 0;
    FileWriter fw = null;
    BufferedWriter bw = null;
    JsonWriter jw = null;
    String sqlquery = "";
    Cursor cur = null;

    String mTable = null;
    String mTableSql = null;
    ArrayList<String> aTable = new ArrayList<String>();
    ArrayList<String> aTableSql = new ArrayList<String>();

    // file writers
    try {
        fw = new FileWriter(jsonFile);
        bw = new BufferedWriter(fw);
        jw = new JsonWriter(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);
    }

    // read tables list and extract name and createsql
    sqlquery = "select * from sqlite_master";
    cur = mDB.rawQuery(sqlquery, null);
    while (cur.moveToNext()) {
        mTable = cur.getString(cur.getColumnIndex("name"));
        mTableSql = cur.getString(cur.getColumnIndex("sql"));
        // add new table, and skip metadata, sequence, and uidx before exporting tables
        if (!mTable.equals("android_metadata") && !mTable.equals("sqlite_sequence")
                && !mTable.startsWith("uidx") && !mTable.startsWith("idx_") && !mTable.startsWith("_idx")) {
            iTableNum++;
            aTable.add(mTable);
            aTableSql.add(mTableSql);
            if (GOLOG)
                Log.d(LOGTAG, "TABLE NAME : " + mTable);
        }
    }
    cur.close();

    // start writing json
    try {
        // open root {
        jw.beginObject();
        // header elements
        jw.name("tables_num").value(Integer.toString(iTableNum));
        jw.name("jsondb_format").value("1");
        // tables name
        jw.name("tables_name");
        jw.beginArray();
        for (int i = 0; i < aTable.size(); i++)
            jw.value(aTable.get(i));
        jw.endArray();

        // open tables array
        jw.name("tables");
        jw.beginArray();
        // iterate through tables
        for (int i = 0; i < aTable.size(); i++) {
            // open table object
            jw.beginObject();
            // table name and table sql
            jw.name("table_name").value(aTable.get(i));
            jw.name("table_sql").value(aTableSql.get(i));
            // iteratew through rows
            sqlquery = "select * from " + aTable.get(i);
            cur = mDB.rawQuery(sqlquery, null);
            int k = -1;
            while (cur.moveToNext()) {
                if (k == -1) {
                    // column names generated at very first row
                    jw.name("cols_name");
                    jw.beginArray();
                    for (k = 0; k < cur.getColumnCount(); k++)
                        jw.value(cur.getColumnName(k));
                    jw.endArray();
                    // open rows array
                    jw.name("rows");
                    jw.beginArray();
                }
                // get columns values in row
                jw.beginArray();
                for (k = 0; k < cur.getColumnCount(); k++)
                    jw.value(cur.getString(k));
                jw.endArray();
            }
            // close rows array
            jw.endArray();
            // close table object
            jw.endObject();
        }
        // close tables array
        jw.endArray();

        // close root {
        jw.endObject();
        jw.close();
    } catch (IOException e) {
        Log.e(LOGTAG, "error in db2gson file writers", e);
    }

    // return number of tables
    return iTableNum;
}

From source file:com.fitforbusiness.nafc.dashboard.DashBoardFragment.java

private void setBusinessAlerts() {

    ArrayList<Map<String, String>> mapArrayList = new ArrayList<Map<String, String>>();
    SQLiteDatabase sqlDB = null;
    try {//from w  w  w.  j a  v a2  s  .co m
        sqlDB = DatabaseHelper.instance().getReadableDatabase();

        String query = "select julianday(pt_license_renewal_date)-julianday('now')  as pt_license, "
                + " julianday(first_aid_cert_renewal_date)-julianday('now')  as first_aid, "
                + " julianday(cpr_cert_renewal_date)-julianday('now')  as cpr_cert, "
                + " julianday(aed_cert_renewal_date)-julianday('now')  as aed_cert from trainer";

        Log.d("query is ", query);
        Cursor cursor = sqlDB.rawQuery(query, null);

        LinkedHashMap<String, String> row;
        if (cursor.moveToFirst()) {
            if (cursor.getFloat(cursor.getColumnIndex("pt_license")) < 90) {
                row = new LinkedHashMap<String, String>();
                if (cursor.getFloat(cursor.getColumnIndex("pt_license")) < 0) {
                    row.put("title", "PT License is overdue.");
                } else {
                    row.put("title", "PT License is due for renewal.");
                }

                row.put("no_of_days", (int) cursor.getFloat(cursor.getColumnIndex("pt_license")) + " day");
                mapArrayList.add(row);
            }
            if (cursor.getFloat(cursor.getColumnIndex("first_aid")) < 90) {
                row = new LinkedHashMap<String, String>();
                if (cursor.getFloat(cursor.getColumnIndex("first_aid")) < 0) {
                    row.put("title", "First Aid is overdue.");
                } else {
                    row.put("title", "First Aid is due for renewal.");
                }

                row.put("no_of_days", (int) cursor.getFloat(cursor.getColumnIndex("first_aid")) + " day");
                mapArrayList.add(row);
            }
            if (cursor.getFloat(cursor.getColumnIndex("cpr_cert")) < 90) {
                row = new LinkedHashMap<String, String>();
                if (cursor.getFloat(cursor.getColumnIndex("cpr_cert")) < 0) {
                    row.put("title", "CPR Certificate is overdue.");
                } else {
                    row.put("title", "CPR Certificate is due for renewal.");
                }

                row.put("no_of_days", (int) cursor.getFloat(cursor.getColumnIndex("cpr_cert")) + " day");
                mapArrayList.add(row);
            }
            if (cursor.getFloat(cursor.getColumnIndex("aed_cert")) < 90) {
                row = new LinkedHashMap<String, String>();
                if (cursor.getFloat(cursor.getColumnIndex("aed_cert")) < 0) {
                    row.put("title", "AED Certificate is overdue.");
                } else {
                    row.put("title", "AED Certificate is due for renewal.");
                }
                row.put("no_of_days", (int) cursor.getFloat(cursor.getColumnIndex("aed_cert")) + " day");
                mapArrayList.add(row);
            }

        }
        cursor.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
    adapter = new SimpleAdapter(getActivity(), mapArrayList, R.layout.custom_list_row_assesssment,
            new String[] { "title", "no_of_days" }, new int[] { R.id.tvFormName, R.id.tvNoOfFields });

}

From source file:org.rapidandroid.activity.chart.message.MessageDataBroker.java

private JSONGraphData loadMessageTrends() {
    SQLiteDatabase db = rawDB.getReadableDatabase();

    Date startDateToUse = mStartDate;
    // if (firstDateFromForm.after(mStartDate)) {
    // // first date in the form is more recent than the start date, so just
    // go with that.
    // startDateToUse = firstDateFromForm;
    // }//w ww.  j  a  v  a 2 s .  c  o  m
    DateDisplayTypes displayType = this.getDisplayType(startDateToUse, mEndDate);

    String selectionArg = getSelectionString(displayType);

    StringBuilder rawQuery = new StringBuilder();
    rawQuery.append("select time, count(*) from rapidandroid_message ");
    if (startDateToUse.compareTo(Constants.NULLDATE) != 0 && mEndDate.compareTo(Constants.NULLDATE) != 0) {
        rawQuery.append(" WHERE rapidandroid_message.time > '" + Message.SQLDateFormatter.format(startDateToUse)
                + "' AND rapidandroid_message.time < '" + Message.SQLDateFormatter.format(mEndDate) + "' ");
    }
    rawQuery.append(" group by ").append(selectionArg);
    rawQuery.append(" order by ").append(selectionArg).append(" ASC");

    // the X date value is column 0
    // the y value magnitude is column 1

    Cursor cr = db.rawQuery(rawQuery.toString(), null);
    return this.getDateQuery(displayType, cr, db);
}

From source file:net.smart_json_database.JSONDatabase.java

private ArrayList<JSONEntity> fetchByRawSQL(SQLiteDatabase db, String sql, String[] params, Order order) {

    ArrayList<JSONEntity> list = null;
    TreeMap<String, JSONEntity> map = null;
    if (order != null && order.sortDataField()) {
        map = new TreeMap<String, JSONEntity>();
    } else {/*w  w  w .  j  av a  2 s  . c  om*/
        list = new ArrayList<JSONEntity>();
    }

    if (order != null && order.sortDatabaseField()) {
        sql += order.sql();
    }

    Cursor c = db.rawQuery(sql, params);
    if (c.getCount() > 0) {

        c.moveToFirst();
        do {
            try {
                JSONEntity entity = JSONEntity.loadFromCursor(c);
                getTagsForJSONEntity(entity, db);
                getHasManyRelationsForJSONEntity(entity, db);
                getBelongsToRelationsForJSONEntity(entity, db);
                if (list != null) {
                    list.add(entity);
                } else {
                    map.put(entity.getString(order.collation()), entity);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
        } while (c.moveToNext());
    }
    c.close();
    if (map != null) {
        list = new ArrayList<JSONEntity>(map.values());
    }
    return list;
}

From source file:com.example.rartonne.appftur.HomeActivity.java

public void syncDwh() {
    String[] tables = { "pda_sec_id_data",
            //"batch_nr_checking",
            //"customer_incident",
            //"PROCESS_LOG",
            "\"SCAN_LOG\"", "ordernr_sites" };

    for (String table : tables) {
        try {/*from  w  w  w .java 2 s  .c  om*/
            String fields = "";
            String values = "";
            String urlPost = "http://admin.qr-ut.com/webservice/pdaws.php?action=syncDwh";
            List<NameValuePair> data = new ArrayList<>();
            String param = "";
            String updateScanlog = "";
            String updatePdaSecIdData = "";
            //on initalise la connexion  la base
            SQLiteDatabase bdd;
            DataBaseHelper myDbHelper = new DataBaseHelper(getApplicationContext());
            String format = "yyyy/MM/dd HH:mm:ss";
            SimpleDateFormat formater = new SimpleDateFormat(format);
            String date = formater.format(new Date());

            try {
                myDbHelper.createDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }

            myDbHelper.openDataBase();

            bdd = myDbHelper.getWritableDatabase();

            Cursor cursor;

            if (table == "\"SCAN_LOG\"") {
                cursor = bdd.rawQuery("SELECT * FROM " + table, null);
            } else if (table == "ordernr_sites") {
                cursor = bdd
                        .rawQuery(
                                "SELECT ordernr, status_code, modified_by, modified_on, installer_id FROM "
                                        + table + " WHERE modified_on > '" + GlobalClass.getLastUpdate() + "'",
                                null);
            } else {
                cursor = bdd.rawQuery("SELECT * FROM " + table + " WHERE createdon > " + "'"
                        + GlobalClass.getLastUpdate() + "'", null);
            }

            while (cursor.moveToNext()) {
                switch (table) {
                case "pda_sec_id_data":
                    fields = "type, value, createdon, modifiedon, gf_sec_id";
                    values = "'" + cursor.getString(1) + "', '" + cursor.getString(2) + "', '"
                            + cursor.getString(3) + "', '" + cursor.getString(4) + "', '" + cursor.getString(5)
                            + "'";
                    updatePdaSecIdData = "UPDATE pda_sec_id_data SET value = '" + cursor.getString(2)
                            + "', modifiedon = '" + cursor.getString(4) + "' WHERE gf_sec_id = '"
                            + cursor.getString(5) + "' AND type = '" + cursor.getString(1) + "';";
                    break;

                case "batch_nr_checking":
                    fields = "createdon, modifiedon, gps_lat, gps_long, createdby, modifiedby, status_code, isonline, checking_source, last_update_batch, last_synchro_blacklist, gf_sec_id, batch_nr_checking_id, batch_nr, article_id";
                    values = "";
                    break;

                case "customer_incident":
                    fields = "";
                    values = "";
                    break;

                case "PROCESS_LOG":
                    fields = "process_type, process_date, comment, object_name, status_code, interface_type, action";
                    values = "'" + cursor.getString(0) + "', '" + cursor.getString(1) + "', '"
                            + cursor.getString(2) + "', '" + cursor.getString(3) + "', " + cursor.getInt(4)
                            + ", '" + cursor.getString(5) + "', '" + cursor.getString(6) + "'";
                    break;

                case "\"SCAN_LOG\"":
                    fields = "gf_sec_id, gps_lat, gps_long, scan_date, user_id, status_code, art_id, customer_order_nr, welding_sketch_nr, serial_wm_nr, fusion_nr, source";
                    values = "'" + cursor.getString(0) + "', " + cursor.getDouble(1) + ", "
                            + cursor.getDouble(2) + ", '" + cursor.getString(3) + "', " + cursor.getInt(4)
                            + ", " + cursor.getInt(5) + ", '" + cursor.getString(6) + "', '"
                            + cursor.getString(7) + "', '" + cursor.getString(8) + "', '" + cursor.getString(9)
                            + "', " + cursor.getInt(10) + ", '" + cursor.getString(11) + "'";
                    updateScanlog += "UPDATE \"SCAN_LOG\" SET gps_lat = " + cursor.getDouble(1)
                            + ", gps_long = " + cursor.getDouble(2) + ", scan_date = '" + cursor.getString(3)
                            + "'" + ", user_id = " + cursor.getInt(4) + ", status_code = " + cursor.getInt(5)
                            + ", art_id = '" + cursor.getString(6) + "', customer_order_nr = '"
                            + cursor.getString(7) + "'" + ", welding_sketch_nr = '" + cursor.getString(8)
                            + "', serial_wm_nr = '" + cursor.getString(9) + "', fusion_nr = "
                            + cursor.getInt(10) + " WHERE gf_sec_id = '" + cursor.getString(0)
                            + "' AND source = 'PDA';";
                    break;

                case "ordernr_sites":
                    fields = "ordernr, status_code, modified_by, modified_on, installer_id";
                    values = "'" + cursor.getString(0) + "', " + cursor.getInt(1) + ", " + cursor.getInt(2)
                            + ", '" + cursor.getString(3) + "', " + cursor.getInt(4);
                    break;
                }
                param += "INSERT INTO " + table + " (" + fields + ") VALUES (" + values + ");";
                //break;
            }

            param += updatePdaSecIdData;
            param += updateScanlog;
            param += "UPDATE pda_settings SET last_update = '" + GlobalClass.getLastUpdate()
                    + "' WHERE pda_id = '" + GlobalClass.getSerialNumber() + "'";
            data.add(new BasicNameValuePair("data", param));

            //on envoie les INSERT
            new HttpAsyncTaskPost(this, data).execute(urlPost);

            cursor.close();

            bdd.close();

            GlobalClass.setLastUpdate(date);
            startActivity(new Intent(this, HomeActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}