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.SubstanceActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Intent/*ww w .  j a va2s. c om*/
    final Intent intent = getIntent();

    final long substanceId = intent.getLongExtra("id", 0);

    // Open database
    SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext).getReadableDatabase();

    String[] queryColumns = { SlDataSQLiteHelper.SUBSTANCES_COLUMN_ATC_CODE,
            SlDataSQLiteHelper.SUBSTANCES_COLUMN_NAME };
    Cursor cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_SUBSTANCES, queryColumns,
            SlDataSQLiteHelper.SUBSTANCES_COLUMN_ID + " = " + substanceId, null, null, null, null);

    if (cursor.moveToFirst()) {
        // Substance
        substanceAtcCode = cursor
                .getString(cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.SUBSTANCES_COLUMN_ATC_CODE));
        substanceName = cursor
                .getString(cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.SUBSTANCES_COLUMN_NAME));

        // Layout
        setContentView(R.layout.activity_substance);

        // Toolbar
        final Toolbar toolbar = (Toolbar) findViewById(R.id.substance_toolbar);
        toolbar.setTitle(substanceName);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // ATC code
        TextView atcCodeTextView = (TextView) findViewById(R.id.substance_atc_code);
        atcCodeTextView.setText(substanceAtcCode);

        // List
        mListView = (ListView) findViewById(R.id.substance_list);
    }

    // Close database
    cursor.close();
    sqLiteDatabase.close();
}

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

@Override
public void handleResult(Result result) {
    mTools.showToast(getString(R.string.barcode_scanner_wait), 0);

    String barcode = result.getText();

    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            getString(R.string.project_website_uri) + "api/1/barcode/?search=" + barcode,
            new Response.Listener<JSONObject>() {
                @Override/*from w ww .  j a va  2s .  c om*/
                public void onResponse(JSONObject response) {
                    try {
                        String medicationName = response.getString("name");

                        if (medicationName.equals("")) {
                            mTools.showToast(getString(R.string.barcode_scanner_no_results), 1);

                            finish();
                        } else {
                            SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext)
                                    .getReadableDatabase();

                            String[] queryColumns = { SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID };
                            Cursor cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_MEDICATIONS,
                                    queryColumns,
                                    SlDataSQLiteHelper.MEDICATIONS_COLUMN_NAME + " LIKE "
                                            + mTools.sqe("%" + medicationName + "%") + " COLLATE NOCASE",
                                    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();

                            finish();
                        }
                    } catch (Exception e) {
                        mTools.showToast(getString(R.string.barcode_scanner_no_results), 1);

                        Log.e("BarcodeScannerActivity", Log.getStackTraceString(e));

                        finish();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("FelleskatalogenService", error.toString());
                }
            });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(jsonObjectRequest);
}

From source file:com.nextgis.maplib.map.VectorLayer.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    super.fromJSON(jsonObject);
    mGeometryType = jsonObject.getInt(JSON_GEOMETRY_TYPE_KEY);
    mIsInitialized = jsonObject.getBoolean(JSON_IS_INITIALIZED_KEY);
    if (jsonObject.has(JSON_RENDERERPROPS_KEY)) {
        setDefaultRenderer();// w ww.j av  a 2s. c  o m

        if (null != mRenderer && mRenderer instanceof IJSONStore) {
            IJSONStore jsonStore = (IJSONStore) mRenderer;
            jsonStore.fromJSON(jsonObject.getJSONObject(JSON_RENDERERPROPS_KEY));
        }
    }

    if (mIsInitialized) {
        mExtents = new GeoEnvelope();

        //load vector cache
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(false);
        String[] columns = new String[] { "_ID", "GEOM" };
        Cursor cursor = db.query(mPath.getName(), columns, null, null, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            mVectorCacheItems = new ArrayList<>();
            do {
                try {
                    GeoGeometry geoGeometry = GeoGeometry.fromBlob(cursor.getBlob(1));
                    int nId = cursor.getInt(0);
                    mExtents.merge(geoGeometry.getEnvelope());
                    mVectorCacheItems.add(new VectorCacheItem(geoGeometry, nId));
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } while (cursor.moveToNext());
        }
    }
}

From source file:com.onesignal.OneSignal.java

static boolean isDuplicateNotification(String id, Context context) {
    if (id == null || "".equals(id))
        return false;

    OneSignalDbHelper dbHelper = new OneSignalDbHelper(context);
    SQLiteDatabase readableDb = dbHelper.getReadableDatabase();

    String[] retColumn = { NotificationTable.COLUMN_NAME_NOTIFICATION_ID };
    String[] whereArgs = { id };/*  w  ww.ja  va2 s. c  o  m*/

    Cursor cursor = readableDb.query(NotificationTable.TABLE_NAME, retColumn,
            NotificationTable.COLUMN_NAME_NOTIFICATION_ID + " = ?", // Where String
            whereArgs, null, null, null);

    boolean exists = cursor.moveToFirst();
    cursor.close();
    readableDb.close();

    if (exists) {
        Log(LOG_LEVEL.DEBUG, "Duplicate GCM message received, skipping processing. " + id);
        return true;
    }

    return false;
}

From source file:com.fan3cn.fishrecorder.ContentFragment.java

/**
 * ??// www .  j a  va  2  s .  com
 * @param view
 */
private void handleShipEvent(final View view) {
    Button addButton = (Button) view.findViewById(R.id.button_add);
    addButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            EditText nameET = (EditText) view.findViewById(R.id.editText_ship_name);
            EditText nationET = (EditText) view.findViewById(R.id.editText_ship_nation);
            EditText registerET = (EditText) view.findViewById(R.id.editText_ship_register);
            EditText emailET = (EditText) view.findViewById(R.id.editText_ship_email);
            EditText ffaET = (EditText) view.findViewById(R.id.editText_ship_ffa);
            EditText wcpfcET = (EditText) view.findViewById(R.id.editText_ship_wcpfc);
            EditText radioET = (EditText) view.findViewById(R.id.editText_ship_radio);
            EditText licenseET = (EditText) view.findViewById(R.id.editText_ship_license);

            CheckBox ckBox = (CheckBox) view.findViewById(R.id.checkBox_is_default);

            int isDefault = ckBox.isChecked() ? 1 : 0;

            String name = nameET.getText().toString();
            String nation = nationET.getText().toString();
            String register = registerET.getText().toString();
            String email = emailET.getText().toString();
            String ffa = ffaET.getText().toString();
            String wcpfc = wcpfcET.getText().toString();
            String radio = radioET.getText().toString();
            String license = licenseET.getText().toString();

            if (name.isEmpty() || nation.isEmpty() || register.isEmpty() || email.isEmpty() || ffa.isEmpty()
                    || wcpfc.isEmpty() || radio.isEmpty() || license.isEmpty()) {
                new AlertDialog.Builder(getActivity()).setTitle("??").setPositiveButton("", null)
                        .setMessage("?").show();
                return;
            }

            SQLiteDatabase db = MainActivity.getDbHelper().getWritableDatabase();

            if (isDefault == 1) {
                Cursor cursor = db.query(Constants.table.get(menuId), null, "is_default=?",
                        new String[] { 1 + "" }, null, null, null);
                if (cursor.getCount() > 0) {
                    //?
                    ContentValues cv1 = new ContentValues();
                    cv1.put("is_default", 0);
                    db.update(Constants.table.get(menuId), cv1, "is_default=?", new String[] { 1 + "" });
                }
            }
            int companyId = 0;
            //?
            Cursor cursor = db.query("company", null, "is_default=?", new String[] { 1 + "" }, null, null,
                    null);
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    companyId = cursor.getInt(cursor.getColumnIndex("id"));
                    break;
                }
            }

            ContentValues cv = new ContentValues();
            cv.put("name", name);
            cv.put("company_id", companyId);
            cv.put("nation", nation);
            cv.put("resgiter_no", register);
            cv.put("email", email);
            cv.put("ffa_no", ffa);
            cv.put("wcpfc_no", wcpfc);
            cv.put("radio_tel", radio);
            cv.put("license", license);
            cv.put("is_default", isDefault);
            db.insert(Constants.table.get(menuId), null, cv);
            //??  
            db.close();

            Toast.makeText(getActivity(), "?!", Toast.LENGTH_SHORT).show();
        }
    });

    Button clearButton = (Button) view.findViewById(R.id.button_clear);

    clearButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText nameET = (EditText) view.findViewById(R.id.editText_ship_name);
            EditText nationET = (EditText) view.findViewById(R.id.editText_ship_nation);
            EditText registerET = (EditText) view.findViewById(R.id.editText_ship_register);
            EditText emailET = (EditText) view.findViewById(R.id.editText_ship_email);
            EditText ffaET = (EditText) view.findViewById(R.id.editText_ship_ffa);
            EditText wcpfcET = (EditText) view.findViewById(R.id.editText_ship_wcpfc);
            EditText radioET = (EditText) view.findViewById(R.id.editText_ship_radio);
            EditText licenseET = (EditText) view.findViewById(R.id.editText_ship_license);

            CheckBox ckBox = (CheckBox) view.findViewById(R.id.checkBox_is_default);

            nameET.setText("");
            nationET.setText("");
            registerET.setText("");
            emailET.setText("");
            ffaET.setText("");
            emailET.setText("");
            radioET.setText("");
            wcpfcET.setText("");
            licenseET.setText("");
            ckBox.setChecked(false);
        }
    });

}

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

private List<String> getSelectedCategories(boolean isMuzei) {
    List<String> categories = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String column = isMuzei ? KEY_MUZEI_SELECTED : 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  ava 2  s . com
    if (cursor.moveToFirst()) {
        do {
            categories.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return categories;
}

From source file:net.survivalpad.android.entity.History.java

@Override
public void findAll(SQLiteDatabase db, List<History> out) {
    String table = getTableName();
    String[] columns = getAllColumns();
    String selection = null;//from ww  w.j a  v a2 s  . co m
    String[] selectionArgs = null;
    String groupBy = null;
    String having = null;
    String orderBy = "updated_time DESC";

    Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
    while (cursor.moveToNext()) {
        History obj = getInstance();
        obj.read(cursor);
        out.add(obj);
    }

    for (History history : out) {
        history.getArticle().findById(history.getArticle().getId(), db);
        history.getAuthor().findById(history.getAuthor().getId(), db);
    }
}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.SqliteGroupAccessDbControllerTest.java

License:asdf

public void testInsert() throws Exception {
    Date currentDate = new Date();
    GroupAccess groupAccess = new GroupAccess(1, "fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.");
    groupAccess.setLastTokenRequest(currentDate);
    groupAccess.setLastUpdateFromServer(currentDate);
    groupAccess.setSynchronize(true);/*from www .  j a va 2s. c  o  m*/
    groupAccess.setInterrupted(false);

    assertEquals(IGroupAuthAccessDbController.INSERTION_CODE.CORRECT,
            mGroupAuthAccessDbController.insert(groupAccess));

    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor cursor = db.query(GroupAccess.TABLE_NAME, GroupAccess.COLUMN.ALL_COLUMNS,
            GroupAccess.COLUMN.GROUP_ID + " = ? ", new String[] { String.valueOf(1) }, null, null, null);
    int count = cursor.getCount();
    if (count == 0)
        cursor.close();

    assertTrue(cursor.moveToFirst());

    int groupId = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.GROUP_ID));
    boolean synchronize = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.SYNCHRONIZE)) == 1;
    boolean interrupted = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.INTERRUPTED)) == 1;
    Date lastTokenRequestDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_TOKEN_REQUEST)),
            new ParsePosition(0));
    Date lastUpdateDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER)),
            new ParsePosition(0));
    String token = cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.TOKEN));

    cursor.close();

    assertEquals(1, groupId);
    assertEquals(true, synchronize);
    assertEquals(false, interrupted);
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastTokenRequestDate));
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastUpdateDate));
    assertEquals("fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.", token);

}

From source file:cn.edu.wyu.documentviewer.RecentsProvider.java

/**
 * Purge all internal data whose authority matches the given
 * {@link Predicate}./*  w  ww  . j a v  a2  s.  c  o  m*/
 */
private void purgeByAuthority(Predicate<String> predicate) {
    final SQLiteDatabase db = mHelper.getWritableDatabase();
    final DocumentStack stack = new DocumentStack();

    Cursor cursor = db.query(TABLE_RECENT, null, null, null, null, null, null);
    try {
        while (cursor.moveToNext()) {
            try {
                final byte[] rawStack = cursor.getBlob(cursor.getColumnIndex(RecentColumns.STACK));
                DurableUtils.readFromArray(rawStack, stack);

                if (stack.root != null && predicate.apply(stack.root.authority)) {
                    final String key = getCursorString(cursor, RecentColumns.KEY);
                    db.delete(TABLE_RECENT, RecentColumns.KEY + "=?", new String[] { key });
                }
            } catch (IOException ignored) {
            }
        }
    } finally {
        //IoUtils.closeQuietly(cursor);
        IOUtils.closeQuietly(cursor);
    }

    cursor = db.query(TABLE_STATE, new String[] { StateColumns.AUTHORITY }, null, null, StateColumns.AUTHORITY,
            null, null);
    try {
        while (cursor.moveToNext()) {
            final String authority = getCursorString(cursor, StateColumns.AUTHORITY);
            if (predicate.apply(authority)) {
                db.delete(TABLE_STATE, StateColumns.AUTHORITY + "=?", new String[] { authority });
                Log.d(TAG, "Purged state for " + authority);
            }
        }
    } finally {
        //IoUtils.closeQuietly(cursor);
        IOUtils.closeQuietly(cursor);
    }

    cursor = db.query(TABLE_RESUME, null, null, null, null, null, null);
    try {
        while (cursor.moveToNext()) {
            try {
                final byte[] rawStack = cursor.getBlob(cursor.getColumnIndex(ResumeColumns.STACK));
                DurableUtils.readFromArray(rawStack, stack);

                if (stack.root != null && predicate.apply(stack.root.authority)) {
                    final String packageName = getCursorString(cursor, ResumeColumns.PACKAGE_NAME);
                    db.delete(TABLE_RESUME, ResumeColumns.PACKAGE_NAME + "=?", new String[] { packageName });
                }
            } catch (IOException ignored) {
            }
        }
    } finally {
        //IoUtils.closeQuietly(cursor);
        IOUtils.closeQuietly(cursor);
    }
}

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

/**
 * Querys the database and returns a cursor.
 * // w w w. j  av a  2  s .  c  om
 * @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 Cursor query(String table, String key, String value) throws DatabaseException {
    SQLiteDatabase db = this.getReadableDatabase();

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

    if (cursor != null && cursor.getCount() != 0) {
        cursor.moveToFirst();
    } else {
        throw new DatabaseException("The given key does not correspond to any IO : " + key);
    }
    db.close();

    return cursor;
}