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:com.maxwen.wallpaper.board.databases.Database.java

public List<Object> getFavoriteWallpapersUnified() {
    List<Object> wallpapers = new ArrayList<>();
    List<String> selected = getSelectedCategories();
    List<String> selection = new ArrayList<>();
    if (selected.size() == 0)
        return wallpapers;
    Map<String, Category> categoryMap = getCategoryMap();

    StringBuilder CONDITION = new StringBuilder();
    for (String item : selected) {
        if (CONDITION.length() > 0) {
            CONDITION.append(" OR ").append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE ?");
        } else {//from   w  w  w  .j av  a  2 s  . co m
            CONDITION.append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE ?");
        }
        selection.add("%" + item.toLowerCase(Locale.getDefault()) + "%");
    }
    CONDITION.append(" AND " + KEY_FAVORITE + " = ?");
    selection.add("1");
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_WALLPAPERS, null, CONDITION.toString(),
            selection.toArray(new String[selection.size()]), null, null, KEY_CATEGORY);
    if (cursor.moveToFirst()) {
        String categoryName = cursor.getString(5);
        Category category = new Category(0, categoryName, categoryMap.get(categoryName).getThumbUrl(), false);
        wallpapers.add(category);
        int numWallpapers = 0;
        do {
            String newCategoryName = cursor.getString(5);
            if (!newCategoryName.equals(categoryName)) {
                category.setNumWallpapers(numWallpapers);
                numWallpapers = 0;
                categoryName = newCategoryName;
                category = new Category(0, newCategoryName, categoryMap.get(newCategoryName).getThumbUrl(),
                        false);
                wallpapers.add(category);
            }
            Wallpaper wallpaper = new Wallpaper(cursor.getInt(0), cursor.getString(1), cursor.getString(2),
                    cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getInt(6) == 1,
                    cursor.getLong(7));
            wallpapers.add(wallpaper);
            numWallpapers++;
        } while (cursor.moveToNext());
        category.setNumWallpapers(numWallpapers);
    }
    cursor.close();
    db.close();
    return wallpapers;
}

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

@Override
public int getAppVersion() {
    SQLiteDatabase db = mService.getDatabase();
    String[] columns = new String[] { TableManifestMeta.C_APP_VERSION };
    String selection = TableManifestMeta.C_ID + "=? AND " + TableManifestMeta.C_PKG_NAME + "=?";
    String[] selectionArgs = new String[] { Integer.toString(mUid), mPkgName };
    Cursor cursor = db.query(TableManifestMeta.NAME, columns, selection, selectionArgs, null, null, null);
    if (cursor.moveToFirst()) {
        int version = cursor.getInt(0);
        cursor.close();// w w w .  j  a v  a2s.  c o m
        return version;
    }
    return -1; // not yet known
}

From source file:com.sina.weibo.sdk.demo.sample.activity.TestFragment.java

public List<Status> getData() {
    SQLiteDatabase databaseHelper = Utils.getDatabaseHelper().getReadableDatabase();
    List<Status> mList = new ArrayList<>();
    Cursor cursor = databaseHelper.query("status", null, null, null, null, null, null);
    while (cursor.moveToNext()) {
        User mainUser = new User();
        Status status = new Status();
        status.user = mainUser;//from  w  w  w  . ja v a 2 s.  c o m

        status.user.name = cursor.getString(cursor.getColumnIndex("name"));
        status.user.gender = cursor.getString(cursor.getColumnIndex("gender"));
        status.user.location = cursor.getString(cursor.getColumnIndex("location"));
        status.user.followers_count = cursor.getInt(cursor.getColumnIndex("followers_count"));
        status.user.friends_count = cursor.getInt(cursor.getColumnIndex("friends_count"));
        status.user.statuses_count = cursor.getInt(cursor.getColumnIndex("statuses_count"));
        status.text = cursor.getString(cursor.getColumnIndex("main_content"));
        status.created_at = cursor.getString(cursor.getColumnIndex("created_at"));
        status.source = cursor.getString(cursor.getColumnIndex("source"));
        if (cursor.getInt(cursor.getColumnIndex("sub_status")) == 1) {
            Status retweeted = new Status();
            User subUser = new User();
            retweeted.user = subUser;
            status.retweeted_status = retweeted;
            status.retweeted_status.user.name = cursor.getString(cursor.getColumnIndex("sub_name"));
            status.retweeted_status.text = cursor.getString(cursor.getColumnIndex("sub_content"));
        }
        mList.add(status);
    }
    cursor.close();
    databaseHelper.close();
    return mList;
}

From source file:com.maxwen.wallpaper.board.databases.Database.java

private List<String> getSelectedCategories() {
    List<String> categories = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String column = KEY_SELECTED;
    Cursor cursor = db.query(TABLE_CATEGORIES, new String[] { KEY_NAME }, column + " = ?", new String[] { "1" },
            null, null, KEY_NAME);//from w w  w .  j  a  va  2  s  .  co m
    if (cursor.moveToFirst()) {
        do {
            categories.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return categories;
}

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

/**
 * Get the applicationversion of the application at the time the manifest was stored.
 *
 * @return The version number if known, -1 otherwise
 *//*from w w  w .j a  v  a2 s . c  om*/
public int getAppVersion() {
    SQLiteDatabase db = mService.getDatabase();
    String[] columns = new String[] { TableManifestMeta.C_APP_VERSION };
    String selection = TableManifestMeta.C_ID + "=? AND " + TableManifestMeta.C_PKG_NAME + "=?";
    String[] selectionArgs = new String[] { Integer.toString(mUid), mPkgName };
    Cursor cursor = db.query(TableManifestMeta.NAME, columns, selection, selectionArgs, null, null, null);
    if (cursor.moveToFirst()) {
        int version = cursor.getInt(0);
        cursor.close();
        return version;
    }
    return -1; // not yet known
}

From source file:com.jefftharris.passwdsafe.NotificationMgr.java

/** Update the notification expirations for a password file */
private void doUpdatePasswdFileData(long uriId, PasswdFileData fileData, SQLiteDatabase db)
        throws SQLException {
    PasswdSafeUtil.dbginfo(TAG, "Update %s, id: %d", fileData.getUri(), uriId);

    TreeMap<ExpiryEntry, Long> entries = new TreeMap<>();
    Cursor cursor = db.query(DB_TABLE_EXPIRYS,
            new String[] { DB_COL_EXPIRYS_ID, DB_COL_EXPIRYS_UUID, DB_COL_EXPIRYS_TITLE, DB_COL_EXPIRYS_GROUP,
                    DB_COL_EXPIRYS_EXPIRE },
            DB_MATCH_EXPIRYS_URI, new String[] { Long.toString(uriId) }, null, null, null);
    try {//  www  .  j  ava2 s  . com
        while (cursor.moveToNext()) {
            ExpiryEntry entry = new ExpiryEntry(cursor.getString(1), cursor.getString(2), cursor.getString(3),
                    cursor.getLong(4));
            entries.put(entry, cursor.getLong(0));
        }
    } finally {
        cursor.close();
    }

    boolean dbchanged = false;
    ContentValues values = null;
    for (PasswdRecord rec : fileData.getPasswdRecords()) {
        PasswdExpiration expiry = rec.getPasswdExpiry();
        if (expiry == null) {
            continue;
        }

        PwsRecord pwsrec = rec.getRecord();
        ExpiryEntry entry = new ExpiryEntry(rec.getUUID(), fileData.getTitle(pwsrec), fileData.getGroup(pwsrec),
                expiry.itsExpiration.getTime());
        if (entries.remove(entry) == null) {
            if (values == null) {
                values = new ContentValues();
                values.put(DB_COL_EXPIRYS_URI, uriId);
            }
            values.put(DB_COL_EXPIRYS_UUID, entry.itsUuid);
            values.put(DB_COL_EXPIRYS_TITLE, entry.itsTitle);
            values.put(DB_COL_EXPIRYS_GROUP, entry.itsGroup);
            values.put(DB_COL_EXPIRYS_EXPIRE, entry.itsExpiry);
            db.insertOrThrow(DB_TABLE_EXPIRYS, null, values);
            dbchanged = true;
        }
    }

    for (Long rmId : entries.values()) {
        db.delete(DB_TABLE_EXPIRYS, DB_MATCH_EXPIRYS_ID, new String[] { rmId.toString() });
        dbchanged = true;
    }

    if (dbchanged) {
        loadEntries(db);
    }
}

From source file:net.olejon.mdapp.NotesEditActivity.java

private void getMedications() {
    try {//  w ww.  j  a v  a 2  s . co  m
        int medicationsJsonArrayLength = mPatientMedicationsJsonArray.length();

        if (medicationsJsonArrayLength == 0) {
            mPatientMedicationsTextView.setVisibility(View.GONE);
        } else {
            mPatientMedicationsTextView.setVisibility(View.VISIBLE);

            final ArrayList<String> medicationsNamesArrayList = new ArrayList<>();
            final ArrayList<String> medicationsManufacturersArrayList = new ArrayList<>();

            final String[] medicationsNamesStringArrayList = new String[medicationsJsonArrayLength + 2];

            medicationsNamesStringArrayList[0] = getString(R.string.notes_edit_medications_dialog_interactions);
            medicationsNamesStringArrayList[1] = getString(R.string.notes_edit_medications_dialog_remove_all);

            for (int i = 0; i < medicationsJsonArrayLength; i++) {
                JSONObject medicationJsonObject = mPatientMedicationsJsonArray.getJSONObject(i);

                String name = medicationJsonObject.getString("name");
                String manufacturer = medicationJsonObject.getString("manufacturer");

                medicationsNamesArrayList.add(name);
                medicationsManufacturersArrayList.add(manufacturer);

                medicationsNamesStringArrayList[i + 2] = name;
            }

            String medicationsNames = "";

            for (int n = 0; n < medicationsNamesArrayList.size(); n++) {
                medicationsNames += medicationsNamesArrayList.get(n) + ", ";
            }

            medicationsNames = medicationsNames.replaceAll(", $", "");

            mPatientMedicationsTextView.setText(Html.fromHtml("<u>" + medicationsNames + "</u>"));

            mPatientMedicationsTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new MaterialDialog.Builder(mContext)
                            .title(getString(R.string.notes_edit_medications_dialog_title))
                            .items(medicationsNamesStringArrayList)
                            .itemsCallback(new MaterialDialog.ListCallback() {
                                @Override
                                public void onSelection(MaterialDialog materialDialog, View view, int i,
                                        CharSequence charSequence) {
                                    if (i == 0) {
                                        String medicationsInteractions = "";

                                        for (int n = 0; n < medicationsNamesArrayList.size(); n++) {
                                            medicationsInteractions += medicationsNamesArrayList.get(n)
                                                    .split(" ")[0] + " ";
                                        }

                                        medicationsInteractions = medicationsInteractions.trim();

                                        Intent intent = new Intent(mContext, InteractionsCardsActivity.class);
                                        intent.putExtra("search", medicationsInteractions);
                                        startActivity(intent);
                                    } else if (i == 1) {
                                        try {
                                            mPatientMedicationsJsonArray = new JSONArray("[]");

                                            getMedications();
                                        } catch (Exception e) {
                                            Log.e("NotesEditActivity", Log.getStackTraceString(e));
                                        }
                                    } else {
                                        int position = i - 2;

                                        String medicationName = medicationsNamesArrayList.get(position);
                                        String medicationManufacturer = medicationsManufacturersArrayList
                                                .get(position);

                                        SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext)
                                                .getReadableDatabase();

                                        String[] queryColumns = { SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID };
                                        Cursor cursor = sqLiteDatabase.query(
                                                SlDataSQLiteHelper.TABLE_MEDICATIONS, queryColumns,
                                                SlDataSQLiteHelper.MEDICATIONS_COLUMN_NAME + " = "
                                                        + mTools.sqe(medicationName) + " AND "
                                                        + SlDataSQLiteHelper.MEDICATIONS_COLUMN_MANUFACTURER
                                                        + " = " + mTools.sqe(medicationManufacturer),
                                                null, null, null, null);

                                        if (cursor.moveToFirst()) {
                                            long id = cursor.getLong(cursor.getColumnIndexOrThrow(
                                                    SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID));

                                            Intent intent = new Intent(mContext, MedicationActivity.class);

                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                                if (mTools.getDefaultSharedPreferencesBoolean(
                                                        "MEDICATION_MULTIPLE_DOCUMENTS"))
                                                    intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK
                                                            | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
                                            }

                                            intent.putExtra("id", id);
                                            startActivity(intent);
                                        }

                                        cursor.close();
                                        sqLiteDatabase.close();
                                    }
                                }
                            }).itemColorRes(R.color.dark_blue).show();
                }
            });
        }
    } catch (Exception e) {
        Log.e("NotesEditActivity", Log.getStackTraceString(e));
    }
}

From source file:org.opendatakit.survey.android.tasks.InstanceUploaderTask.java

@Override
protected InstanceUploadOutcome doInBackground(String... toUpload) {
    mOutcome = new InstanceUploadOutcome();
    mOutcome.mResults = new HashMap<String, String>();
    mOutcome.mAuthRequestingServer = null;

    String auth = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_AUTH);
    setAuth(auth);//from w  ww . j av a 2 s .  c o  m

    String urlString = null;

    /**
     * retrieve the URL string for the table, if defined... otherwise, use the
     * app property values to construct it.
     */
    {
        SQLiteDatabase db = null;

        Cursor c = null;
        try {
            db = DatabaseFactory.get().getDatabase(appContext, appName);
            c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null,
                    KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND "
                            + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY + "=?",
                    new String[] { uploadTableId, KeyValueStoreConstants.PARTITION_TABLE,
                            KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_SUBMISSION_URL },
                    null, null, null);
            if (c.getCount() == 1) {
                c.moveToFirst();
                int idxValue = c.getColumnIndex(KeyValueStoreColumns.VALUE);
                urlString = c.getString(idxValue);
            } else if (c.getCount() != 0) {
                throw new IllegalStateException(
                        "two or more entries for " + KeyValueStoreConstants.XML_SUBMISSION_URL);
            }
        } finally {
            c.close();
            db.releaseReference();
        }

        if (urlString == null) {
            urlString = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_SERVER_URL);
            String submissionUrl = PropertiesSingleton.getProperty(appName,
                    PreferencesActivity.KEY_SUBMISSION_URL);
            urlString = urlString + submissionUrl;
        }
    }

    // FormInfo fi = new FormInfo(appContext, appName,
    // ODKFileUtils.getuploadingForm.formDefFile);
    // get shared HttpContext so that authentication and cookies are
    // retained.
    HttpContext localContext = ClientConnectionManagerFactory.get(appName).getHttpContext();
    HttpClient httpclient = ClientConnectionManagerFactory.get(appName)
            .createHttpClient(WebUtils.CONNECTION_TIMEOUT);

    Map<URI, URI> uriRemap = new HashMap<URI, URI>();

    for (int i = 0; i < toUpload.length; ++i) {
        if (isCancelled()) {
            return mOutcome;
        }
        publishProgress(i + 1, toUpload.length);

        Uri toUpdate = Uri.withAppendedPath(InstanceProviderAPI.CONTENT_URI,
                appName + "/" + uploadTableId + "/" + StringEscapeUtils.escapeHtml4(toUpload[i]));
        Cursor c = null;
        try {
            c = appContext.getContentResolver().query(toUpdate, null, null, null, null);
            if (c.getCount() == 1 && c.moveToFirst()) {

                String id = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(InstanceColumns._ID));
                String dataTableInstanceId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                String lastOutcome = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(InstanceColumns.XML_PUBLISH_STATUS));
                String submissionInstanceId = ODKDataUtils.genUUID();
                // submissions always get a new legacy instance id UNLESS the last
                // submission failed,
                // in which case we retry the submission using the legacy instance id
                // associated with
                // that failure. This supports resumption of sends of forms with many
                // attachments.
                if (lastOutcome != null && lastOutcome.equals(InstanceColumns.STATUS_SUBMISSION_FAILED)) {
                    String lastId = ODKDatabaseUtils.get().getIndexAsString(c,
                            c.getColumnIndex(InstanceColumns.SUBMISSION_INSTANCE_ID));
                    if (lastId != null) {
                        submissionInstanceId = lastId;
                    }
                }
                c.close();

                FileSet instanceFiles;
                try {
                    instanceFiles = constructSubmissionFiles(dataTableInstanceId, submissionInstanceId);
                    // NOTE: /submission must not be translated! It is
                    // the well-known path on the server.

                    if (!uploadOneSubmission(urlString, toUpdate, id, submissionInstanceId, instanceFiles,
                            httpclient, localContext, uriRemap)) {
                        return mOutcome; // get credentials...
                    }
                } catch (JsonParseException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId
                            + " :: details: " + e.toString());
                } catch (JsonMappingException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId
                            + " :: details: " + e.toString());
                } catch (IOException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId
                            + " :: details: " + e.toString());
                }
            } else {
                mOutcome.mResults.put("unknown",
                        fail + "unable to retrieve instance information via: " + toUpdate.toString());
            }
        } finally {
            if (c != null && !c.isClosed()) {
                c.close();
            }
        }
    }

    return mOutcome;
}

From source file:net.olejon.mdapp.MedicationActivity.java

private void getManufacturer() {
    SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext).getReadableDatabase();

    String[] queryColumns = { SlDataSQLiteHelper.MANUFACTURERS_COLUMN_ID };
    Cursor cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_MANUFACTURERS, queryColumns,
            SlDataSQLiteHelper.MANUFACTURERS_COLUMN_NAME + " = " + mTools.sqe(medicationManufacturer), null,
            null, null, null);/* w  w w  .jav  a 2  s.com*/

    if (cursor.moveToFirst()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.MANUFACTURERS_COLUMN_ID));

        Intent intent = new Intent(mContext, ManufacturerActivity.class);
        intent.putExtra("id", id);
        startActivity(intent);
    }

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

From source file:com.triarc.sync.SyncAdapter.java

private void appendEntity(SyncType type, SQLiteDatabase openDatabase, JSONObject jsonObject, String id) {
    Cursor fullEntityCursor = null;
    try {// w  w  w  . j  ava  2s .c  o  m
        fullEntityCursor = openDatabase.query(type.getName(), null, "_id=" + id, null, null, null, null);

        if (fullEntityCursor.moveToNext()) {
            try {
                jsonObject.put("entity", readEntity(type, fullEntityCursor));
            } catch (Exception e) {
                syncResult.stats.numIoExceptions++;
                syncResult.databaseError = true;
                e.printStackTrace();
                sendLogs();
            }
        } else {
            Log.w(TAG, "should not happen, check appendEntity");
        }
    } finally {
        if (fullEntityCursor != null)
            fullEntityCursor.close();
    }
}