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:net.olejon.mdapp.NotesEditActivity.java

private void getNote() {
    if (noteId != 0) {
        SQLiteDatabase sqLiteDatabase = new NotesSQLiteHelper(mContext).getReadableDatabase();

        String[] queryColumns = { NotesSQLiteHelper.COLUMN_TITLE, NotesSQLiteHelper.COLUMN_TEXT,
                NotesSQLiteHelper.COLUMN_PATIENT_ID, NotesSQLiteHelper.COLUMN_PATIENT_NAME,
                NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR, NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT,
                NotesSQLiteHelper.COLUMN_PATIENT_ROOM, NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS };
        Cursor cursor = sqLiteDatabase.query(NotesSQLiteHelper.TABLE, queryColumns,
                NotesSQLiteHelper.COLUMN_ID + " = " + noteId, null, null, null, null);

        if (cursor.moveToFirst()) {
            String title = cursor.getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_TITLE));
            String text = cursor.getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_TEXT));
            String patientId = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_ID));
            String patientName = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_NAME));
            String patientDoctor = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR));
            String patientDepartment = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT));
            String patientRoom = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_ROOM));
            String patientMedications = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS));

            mTitleEditText.setText(title);
            mTextEditText.setText(text);
            mPatientIdEditText.setText(patientId);
            mPatientNameEditText.setText(patientName);
            mPatientDoctorEditText.setText(patientDoctor);
            mPatientDepartmentEditText.setText(patientDepartment);
            mPatientRoomEditText.setText(patientRoom);

            if (patientMedications != null && !patientMedications.equals("")) {
                try {
                    mPatientMedicationsJsonArray = new JSONArray(patientMedications);

                    getMedications();//from  w  ww.  j  a v  a2 s.c o  m
                } catch (Exception e) {
                    Log.e("NotesEditActivity", Log.getStackTraceString(e));
                }
            }
        }

        cursor.close();
        sqLiteDatabase.close();
    }
}

From source file:project.cs.netinfservice.database.IODatabase.java

/**
 * Queries the database and returns a cursor.
 * /*from   w ww  . j  av  a2s  .c o  m*/
 * @param table
 *       The table in which we want to query
 * @param key
 *       The key
 * @param value
 *       The corresponding value
 * @return
 *       A cursor pointing to the first row of results
 * @throws DatabaseException
 *        Thrown, if no entry was found for the specified key value pair
 */
private synchronized Cursor query(String table, String key, String value) throws DatabaseException {
    SQLiteDatabase db = null;

    try {
        db = this.getReadableDatabase();
    } catch (SQLiteException e) {
        Log.e(TAG, "Querying database failed. Error during reading database.");
        throw new DatabaseException("Unexpected error while trying to read from database.");
    }

    // Makes the query for (key,value)
    Cursor cursor = db.query(table, null, key + "=?", new String[] { value }, null, null, null);

    // If there was any result, move the cursor to the first result
    if (cursor != null && cursor.getCount() != 0) {
        cursor.moveToFirst();
    } else {
        // Fails if it does not find anything
        db.close();
        throw new DatabaseException("The given key does not correspond to any IO : " + key);
    }

    db.close();

    // Return first object
    return cursor;
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }/*from  ww  w  .  j  a va2  s .  c  o  m*/

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    // ODK2: require FORM_MEDIA_PATH (different behavior -- ODK1 and
    // required FORM_FILE_PATH)
    if (!values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + " must be specified.");
    }

    // Normalize path...
    File mediaPath = ODKFileUtils.asAppFile(appName,
            values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));

    // require that the form directory actually exists
    if (!mediaPath.exists()) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                + " directory does not exist: " + mediaPath.getAbsolutePath());
    }

    patchUpValues(appName, values);

    if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
        values.put(FormsColumns.DISPLAY_NAME, mediaPath.getName());
    }

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.FORM_ID, FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH };
    String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, mediaPath) };
    String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
    Cursor c = null;

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null);
            if (c == null) {
                throw new SQLException("FAILED Insert into " + uri
                        + " -- unable to query for existing records: " + mediaPath.getAbsolutePath());
            }
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri
                        + " -- row already exists for form directory: " + mediaPath.getAbsolutePath());
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        try {
            long rowId = db.insert(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            if (rowId > 0) {
                Uri formUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        values.getAsString(FormsColumns.FORM_ID));
                getContext().getContentResolver().notifyChange(formUri, null);
                Uri idUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        Long.toString(rowId));
                getContext().getContentResolver().notifyChange(idUri, null);

                return formUri;
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
            }
        }
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:org.pixmob.freemobile.netstat.SyncService.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<DailyStat>(15);
    final Set<Long> uploadedStats = new HashSet<Long>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" },
            "stat_timestamp>=? AND stat_timestamp<?",
            new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
    try {//from   w  w  w . j  av a 2 s. c om
        while (c.moveToNext()) {
            final long d = c.getLong(0);
            final int sync = c.getInt(3);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = c.getInt(1);
                s.freeMobile = c.getInt(2);
                stats.put(d, s);
            }
        }
    } finally {
        c.close();
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncService.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

From source file:org.qeo.android.service.ApplicationSecurity.java

private boolean isAllowedReaderWriter(String rw, boolean read) {
    SQLiteDatabase db = mService.getDatabase();
    String[] columns = new String[] { TableManifestRW.C_UID };
    LOG.fine("isAllowedReaderWriter: " + rw + " -- " + mUid + " -- " + mPkgName);
    String selection = TableManifestRW.C_NAME + " = ? AND " + TableManifestRW.C_UID + " = ? AND "
            + TableManifestRW.C_PKG_NAME + " = ? AND "
            + (read ? TableManifestRW.C_READ : TableManifestRW.C_WRITE) + " = ?";
    String[] selectionArgs = new String[] { rw, Integer.toString(mUid), mPkgName, "1" };
    Cursor cursor = db.query(TableManifestRW.NAME, columns, selection, selectionArgs, null, null, null);
    boolean ok = cursor.getCount() == 1;
    cursor.close();/*from w  ww . j av  a2 s  .  co m*/
    return ok;
}

From source file:com.melchor629.musicote.MainActivity.java

/** Carga desde la base de datos */
private void cursordb(SQLiteDatabase db) {
    // Define a projection that specifies which columns from the database
    // you will actually use after this query.
    String[] projection = { DB_entry.COLUMN_CANCIONES_ID, DB_entry.COLUMN_CANCIONES_TITULO,
            DB_entry.COLUMN_CANCIONES_ARTISTA, DB_entry.COLUMN_CANCIONES_ALBUM,
            DB_entry.COLUMN_CANCIONES_DURACION, DB_entry.COLUMN_CANCIONES_ARCHIVO,
            DB_entry.COLUMN_CANCIONES_DOWNLOADED };

    // How you want the results sorted in the resulting Cursor
    String sortOrder = DB_entry.COLUMN_CANCIONES_ID + " ASC";

    Cursor c = db.query(DB_entry.TABLE_CANCIONES, // The table to query
            projection, // The columns to return
            null, // The columns for the WHERE clause
            null, // The values for the WHERE clause
            null, // don't group the rows
            null, // don't filter by row groups
            sortOrder // The sort order
    );/*from w  w w .  ja v  a2s.co m*/
    if (songList != null)
        songList.clear();
    else
        songList = new ArrayList<>();

    c.moveToFirst();
    try {
        do {
            // creating new HashMap
            LinkedTreeMap<String, String> map = new LinkedTreeMap<>();

            long id = c.getLong(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ID));
            String titulo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_TITULO));
            String artista = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARTISTA));
            String album = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ALBUM));
            String archivo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARCHIVO));
            String duracion = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DURACION));
            String downloaded = "false";//c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DOWNLOADED));

            // adding each child node to HashMap key => value
            map.put("id", "" + id);
            map.put("titulo", titulo);
            map.put("artista", artista);
            map.put("album", album);
            map.put("archivo", archivo);
            map.put("duracion", duracion);
            map.put("downloaded", downloaded.equalsIgnoreCase("true") ? "{fa-mobile}" : "{fa-cloud}"); //TODO

            songList.add(map);
        } while (c.moveToNext());
    } catch (CursorIndexOutOfBoundsException e) {
        db.execSQL(DB_entry.DELETE_CANCIONES);
        Log.e("DB", "Mala integridad de la BD");
    }
    c.close();
    sis();
}

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

public Cursor getAllRecipes(String sortBy) {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        return db.query(RECIPES_TABLE, RECIPES_FIELDS, null, null, null, null, sortBy);
    }//w w w  .  j ava2  s  .  c  o m
}

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

public Cursor getAllRecipes(String[] columns, String sortBy) {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        return db.query(RECIPES_TABLE, columns, null, null, null, null, sortBy);
    }/*from  w  w w.  jav a  2  s  .c om*/
}

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

public Cursor getAllTags() {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        return db.query(TAGS_TABLE, TAGS_FIELDS, null, null, TT_TAG, null, TT_TAG);
    }//  w  w w.j av  a 2 s.  c  o m
}

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

public Cursor getSingleRecipe(long rid) {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        return db.query(RECIPES_TABLE, RECIPES_FIELDS, RT_ID + " = ?", new String[] { Long.toString(rid) },
                null, null, null);//from   ww w .  j  ava2 s . c  om
    }
}