Example usage for android.database Cursor isClosed

List of usage examples for android.database Cursor isClosed

Introduction

In this page you can find the example usage for android.database Cursor isClosed.

Prototype

boolean isClosed();

Source Link

Document

return true if the cursor is closed

Usage

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Get the table definition entry for a tableId. This specifies the schema
 * ETag, the data-modification ETag, and the date-time of the last successful
 * sync of the table to the server./*from w  ww .  j a  v  a  2  s  .  com*/
 * 
 * @param db
 * @param tableId
 * @return
 */
public TableDefinitionEntry getTableDefinitionEntry(SQLiteDatabase db, String tableId) {

    TableDefinitionEntry e = null;
    Cursor c = null;
    try {
        StringBuilder b = new StringBuilder();
        ArrayList<String> selArgs = new ArrayList<String>();
        b.append(KeyValueStoreColumns.TABLE_ID).append("=?");
        selArgs.add(tableId);

        c = db.query(DatabaseConstants.TABLE_DEFS_TABLE_NAME, null, b.toString(),
                selArgs.toArray(new String[selArgs.size()]), null, null, null);
        if (c.moveToFirst()) {
            int idxSchemaETag = c.getColumnIndex(TableDefinitionsColumns.SCHEMA_ETAG);
            int idxLastDataETag = c.getColumnIndex(TableDefinitionsColumns.LAST_DATA_ETAG);
            int idxLastSyncTime = c.getColumnIndex(TableDefinitionsColumns.LAST_SYNC_TIME);

            if (c.getCount() != 1) {
                throw new IllegalStateException(
                        "Two or more TableDefinitionEntry records found for tableId " + tableId);
            }

            e = new TableDefinitionEntry(tableId);
            e.setSchemaETag(c.getString(idxSchemaETag));
            e.setLastDataETag(c.getString(idxLastDataETag));
            e.setLastSyncTime(c.getString(idxLastSyncTime));
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return e;
}

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

/**
 * Remove definitions from the Forms database that are no longer present on
 * disk./*from   www  .jav  a2 s .  com*/
 */
private final void removeStaleFormInfo(List<File> discoveredFormDefDirs) {
    Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY);

    String completionString = appContext.getString(R.string.searching_for_deleted_forms);
    publishProgress(completionString, null);

    WebLogger.getLogger(appName).i(t, "removeStaleFormInfo " + appName + " begin");
    ArrayList<Uri> badEntries = new ArrayList<Uri>();
    Cursor c = null;
    try {
        c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                null, null, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "removeStaleFormInfo " + appName + " null cursor returned from query.");
            return;
        }

        if (c.moveToFirst()) {
            do {
                String id = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID));
                Uri otherUri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id);

                String examString = appContext.getString(R.string.examining_form, id);
                publishProgress(examString, null);

                int appRelativeFormMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                if (appRelativeFormMediaPathIdx == -1) {
                    throw new IllegalStateException("Column " + FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                            + " missing from database table. Incompatible versions?");
                }
                String appRelativeFormMediaPath = ODKDatabaseUtils.get().getIndexAsString(c,
                        appRelativeFormMediaPathIdx);
                File f = ODKFileUtils.asAppFile(appName, appRelativeFormMediaPath);
                File formDefJson = new File(f, ODKFileUtils.FORMDEF_JSON_FILENAME);
                if (!f.exists() || !f.isDirectory() || !formDefJson.exists() || !formDefJson.isFile()) {
                    // the form definition does not exist
                    badEntries.add(otherUri);
                    continue;
                } else {
                    // ////////////////////////////////
                    // formdef.json exists. See if it is
                    // unchanged...
                    String json_md5 = ODKDatabaseUtils.get().getIndexAsString(c,
                            c.getColumnIndex(FormsColumns.JSON_MD5_HASH));
                    String fileMd5 = ODKFileUtils.getMd5Hash(appName, formDefJson);
                    if (json_md5.equals(fileMd5)) {
                        // it is unchanged -- no need to rescan it
                        discoveredFormDefDirs.remove(f);
                    }
                }
            } while (c.moveToNext());
        }
    } catch (Exception e) {
        WebLogger.getLogger(appName).e(t, "removeStaleFormInfo " + appName + " exception: " + e.toString());
        WebLogger.getLogger(appName).printStackTrace(e);
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    // delete the other entries (and directories)
    for (Uri badUri : badEntries) {
        WebLogger.getLogger(appName).i(t,
                "removeStaleFormInfo: " + appName + " deleting: " + badUri.toString());
        try {
            appContext.getContentResolver().delete(badUri, null, null);
        } catch (Exception e) {
            WebLogger.getLogger(appName).e(t, "removeStaleFormInfo " + appName + " exception: " + e.toString());
            WebLogger.getLogger(appName).printStackTrace(e);
            // and continue -- don't throw an error
        }
    }
    WebLogger.getLogger(appName).i(t, "removeStaleFormInfo " + appName + " end");
}

From source file:com.stfalcon.contentmanager.ContentManager.java

/**
 * Process result of camera intent//from  www.j  a  va2  s . c  o m
 */
private void onCameraIntentResult(int requestCode, int resultCode, Intent intent) {
    if (resultCode == Activity.RESULT_OK) {
        Cursor myCursor = null;
        Date dateOfPicture = null;
        try {
            // Create a Cursor to obtain the file Path for the large image
            String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
                    MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.ORIENTATION,
                    MediaStore.Images.ImageColumns.DATE_TAKEN };
            String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
            myCursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    largeFileProjection, null, null, largeFileSort);
            myCursor.moveToFirst();
            if (!myCursor.isAfterLast()) {
                // This will actually give you the file path location of the image.
                String largeImagePath = myCursor
                        .getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
                photoUri = Uri.fromFile(new File(largeImagePath));
                if (photoUri != null) {
                    dateOfPicture = new Date(myCursor.getLong(
                            myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATE_TAKEN)));
                    if (dateOfPicture != null && dateOfPicture.after(dateCameraIntentStarted)) {
                        rotateXDegrees = myCursor.getInt(
                                myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION));
                    } else {
                        photoUri = null;
                    }
                }
                if (myCursor.moveToNext() && !myCursor.isAfterLast()) {
                    String largeImagePath3rdLocation = myCursor
                            .getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
                    Date dateOfPicture3rdLocation = new Date(myCursor.getLong(
                            myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATE_TAKEN)));
                    if (dateOfPicture3rdLocation != null
                            && dateOfPicture3rdLocation.after(dateCameraIntentStarted)) {
                        photoUriIn3rdLocation = Uri.fromFile(new File(largeImagePath3rdLocation));
                    }
                }
            }
        } catch (Exception e) {
        } finally {
            if (myCursor != null && !myCursor.isClosed()) {
                myCursor.close();
            }
        }

        if (photoUri == null) {
            try {
                photoUri = intent.getData();
            } catch (Exception e) {
            }
        }

        if (photoUri == null) {
            photoUri = preDefinedCameraUri;
        }

        try {
            if (photoUri != null && new File(photoUri.getPath()).length() <= 0) {
                if (preDefinedCameraUri != null) {
                    Uri tempUri = photoUri;
                    photoUri = preDefinedCameraUri;
                    preDefinedCameraUri = tempUri;
                }
            }
        } catch (Exception e) {
        }

        photoUri = getFileUriFromContentUri(photoUri);
        preDefinedCameraUri = getFileUriFromContentUri(preDefinedCameraUri);
        try {
            if (photoUriIn3rdLocation != null) {
                if (photoUriIn3rdLocation.equals(photoUri)
                        || photoUriIn3rdLocation.equals(preDefinedCameraUri)) {
                    photoUriIn3rdLocation = null;
                } else {
                    photoUriIn3rdLocation = getFileUriFromContentUri(photoUriIn3rdLocation);
                }
            }
        } catch (Exception e) {
        }

        if (photoUri != null) {
            pickContentListener.onContentLoaded(photoUri, Content.IMAGE.toString());
        } else {
            pickContentListener.onError("");
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        pickContentListener.onCanceled();
    } else {
        pickContentListener.onCanceled();
    }
}

From source file:com.SecUpwN.AIMSICD.activities.MapViewerOsmDroid.java

/**
 *  Description:    Loads Signal Strength Database details to plot on the map,
 *                  only entries which have a location (lon, lat) are used.
 *
 *
 *//*  w  w  w  .j av a  2 s.  c om*/
private void loadEntries() {

    new AsyncTask<Void, Void, GeoPoint>() {
        @Override
        protected GeoPoint doInBackground(Void... voids) {
            final int SIGNAL_SIZE_RATIO = 15; // A scale factor to draw BTS Signal circles
            int signal;

            mCellTowerGridMarkerClusterer.getItems().clear();
            loadOpenCellIDMarkers();

            LinkedList<CellTowerMarker> items = new LinkedList<>();

            mDbHelper.open();
            Cursor c = null;
            try {
                // Grab cell data from CELL_TABLE (cellinfo) --> DBi_bts
                c = mDbHelper.getCellData();
            } catch (IllegalStateException ix) {
                Log.e(TAG, ix.getMessage(), ix);
            }
            if (c != null && c.moveToFirst()) {
                do {
                    // The indexing here is that of the Cursor and not the DB table itself
                    final int cellID = c.getInt(0); // CID
                    final int lac = c.getInt(1); // LAC
                    final int net = c.getInt(2); // RAT
                    final int mcc = c.getInt(6); // MCC
                    final int mnc = c.getInt(7); // MNC
                    final double dlat = Double.parseDouble(c.getString(3)); // Lat
                    final double dlng = Double.parseDouble(c.getString(4)); // Lon
                    if (dlat == 0.0 && dlng == 0.0) {
                        continue;
                    }
                    signal = c.getInt(5); // signal
                    // In case of missing or negative signal, set a default fake signal,
                    // so that we can still draw signal circles.  ?
                    if (signal <= 0) {
                        signal = 20;
                    }

                    if ((dlat != 0.0) || (dlng != 0.0)) {
                        loc = new GeoPoint(dlat, dlng);

                        CellTowerMarker ovm = new CellTowerMarker(mContext, mMap, "Cell ID: " + cellID, "", loc,
                                new MarkerData("" + cellID, "" + loc.getLatitude(), "" + loc.getLongitude(),
                                        "" + lac, "" + mcc, "" + mnc, "", false));
                        // The pin of our current position
                        ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_blue));
                        items.add(ovm);

                    }

                } while (c.moveToNext());
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Helpers.msgLong(MapViewerOsmDroid.this, getString(R.string.no_tracked_locations_found));
                    }
                });
            }

            GeoPoint ret = new GeoPoint(0, 0);
            if (mBound) {
                try {
                    int mcc = mAimsicdService.getCell().getMCC();
                    double[] d = mDbHelper.getDefaultLocation(mcc);
                    ret = new GeoPoint(d[0], d[1]);
                } catch (Exception e) {
                    Log.e("map", "Error getting default location!", e);
                }
            }
            if (c != null && !c.isClosed()) {
                c.close();
            }
            mDbHelper.close();

            // plot neighbouring cells
            while (mAimsicdService == null)
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
            List<Cell> nc = mAimsicdService.getCellTracker().updateNeighbouringCells();
            for (Cell cell : nc) {
                try {
                    loc = new GeoPoint(cell.getLat(), cell.getLon());
                    CellTowerMarker ovm = new CellTowerMarker(mContext, mMap,
                            getString(R.string.cell_id_label) + cell.getCID(), "", loc,
                            new MarkerData("" + cell.getCID(), "" + loc.getLatitude(), "" + loc.getLongitude(),
                                    "" + cell.getLAC(), "" + cell.getMCC(), "" + cell.getMNC(), "", false));

                    // The pin of other BTS
                    ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_orange));
                    items.add(ovm);
                } catch (Exception e) {
                    Log.e("map", "Error plotting neighbouring cells", e);
                }
            }

            mCellTowerGridMarkerClusterer.addAll(items);

            return ret;
        }

        /**
         *  TODO:  We need a manual way to add our own location in case:
         *          a) GPS is jammed or not working
         *          b) WiFi location is not used
         *          c) Default MCC is too far off
         *
         * @param defaultLoc
         */
        @Override
        protected void onPostExecute(GeoPoint defaultLoc) {
            if (loc != null && (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0)) {
                mMap.getController().setZoom(16);
                mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
            } else {
                if (mBound) {
                    // Try and find last known location and zoom there
                    GeoLocation lastLoc = mAimsicdService.lastKnownLocation();
                    if (lastLoc != null) {
                        loc = new GeoPoint(lastLoc.getLatitudeInDegrees(), lastLoc.getLongitudeInDegrees());

                        mMap.getController().setZoom(16);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    } else {
                        //Use MCC to move camera to an approximate location near Countries Capital
                        loc = defaultLoc;

                        mMap.getController().setZoom(12);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    }
                }
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.hichinaschool.flashcards.libanki.Sched.java

/** estimates remaining time for learning (based on last seven days) */
public int eta(int[] counts, boolean reload) {
    double revYesRate;
    double revTime;
    double lrnYesRate;
    double lrnTime;
    if (reload || mEtaCache[0] == -1) {
        Cursor cur = null;
        try {/*from   w w w  .j a v  a  2 s.  co  m*/
            cur = mCol.getDb().getDatabase().rawQuery(
                    "SELECT avg(CASE WHEN ease > 1 THEN 1.0 ELSE 0.0 END), avg(time) FROM revlog WHERE type = 1 AND id > "
                            + ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000),
                    null);
            if (!cur.moveToFirst()) {
                return -1;
            }
            revYesRate = cur.getDouble(0);
            revTime = cur.getDouble(1);
            cur = mCol.getDb().getDatabase().rawQuery(
                    "SELECT avg(CASE WHEN ease = 3 THEN 1.0 ELSE 0.0 END), avg(time) FROM revlog WHERE type != 1 AND id > "
                            + ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000),
                    null);
            if (!cur.moveToFirst()) {
                return -1;
            }
            lrnYesRate = cur.getDouble(0);
            lrnTime = cur.getDouble(1);
        } finally {
            if (cur != null && !cur.isClosed()) {
                cur.close();
            }
        }
        mEtaCache[0] = revYesRate;
        mEtaCache[1] = revTime;
        mEtaCache[2] = lrnYesRate;
        mEtaCache[3] = lrnTime;
    } else {
        revYesRate = mEtaCache[0];
        revTime = mEtaCache[1];
        lrnYesRate = mEtaCache[2];
        lrnTime = mEtaCache[3];
    }
    // rev cards
    double eta = revTime * counts[2];
    // lrn cards
    double factor = Math.min(1 / (1 - lrnYesRate), 10);
    double lrnAnswers = (counts[0] + counts[1] + counts[2] * (1 - revYesRate)) * factor;
    eta += lrnAnswers * lrnTime;
    return (int) (eta / 60000);
}

From source file:com.hichinaschool.flashcards.libanki.Sched.java

/**
 * Sibling spacing/*w  ww  .  j  a v  a 2  s. c o  m*/
 * ********************
 */

private void _burySiblings(Card card) {
    LinkedList<Long> toBury = new LinkedList<Long>();
    JSONObject nconf = _newConf(card);
    boolean buryNew = nconf.optBoolean("bury", true);
    JSONObject rconf = _revConf(card);
    boolean buryRev = rconf.optBoolean("bury", true);
    // loop through and remove from queues
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase()
                .rawQuery(String.format(Locale.US,
                        "select id, queue from cards where nid=%d and id!=%d "
                                + "and (queue=0 or (queue=2 and due<=%d))",
                        new Object[] { card.getNid(), card.getId(), mToday }), null);
        while (cur.moveToNext()) {
            long cid = cur.getLong(0);
            int queue = cur.getInt(1);
            if (queue == 2) {
                if (buryRev) {
                    toBury.add(cid);
                }
                // if bury disabled, we still discard to give same-day spacing
                mRevQueue.remove(cid);
            } else {
                // if bury is disabled, we still discard to give same-day spacing
                if (buryNew) {
                    toBury.add(cid);
                    mNewQueue.remove(cid);
                }
            }
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    // then bury
    mCol.getDb().execute("update cards set queue=-2,mod=?,usn=? where id in " + Utils.ids2str(toBury),
            new Object[] { Utils.now(), mCol.usn() });
}

From source file:com.aware.Aware.java

private void get_device_info() {
    Cursor awareContextDevice = awareContext.getContentResolver().query(Aware_Device.CONTENT_URI, null, null,
            null, null);//from   ww w  .j  a va 2 s  . co m
    if (awareContextDevice == null || !awareContextDevice.moveToFirst()) {
        ContentValues rowData = new ContentValues();
        rowData.put("timestamp", System.currentTimeMillis());
        rowData.put("device_id", Aware.getSetting(awareContext, Aware_Preferences.DEVICE_ID));
        rowData.put("board", Build.BOARD);
        rowData.put("brand", Build.BRAND);
        rowData.put("device", Build.DEVICE);
        rowData.put("build_id", Build.DISPLAY);
        rowData.put("hardware", Build.HARDWARE);
        rowData.put("manufacturer", Build.MANUFACTURER);
        rowData.put("model", Build.MODEL);
        rowData.put("product", Build.PRODUCT);
        rowData.put("serial", Build.SERIAL);
        rowData.put("release", Build.VERSION.RELEASE);
        rowData.put("release_type", Build.TYPE);
        rowData.put("sdk", Build.VERSION.SDK_INT);

        try {
            awareContext.getContentResolver().insert(Aware_Device.CONTENT_URI, rowData);

            Intent deviceData = new Intent(ACTION_AWARE_DEVICE_INFORMATION);
            sendBroadcast(deviceData);

            if (Aware.DEBUG)
                Log.d(TAG, "Device information:" + rowData.toString());

        } catch (SQLiteException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        } catch (SQLException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        }
    }
    if (awareContextDevice != null && !awareContextDevice.isClosed())
        awareContextDevice.close();
}

From source file:org.adaway.service.UpdateService.java

/**
 * Check for updates of hosts sources/*from   w  ww .j a va 2  s .  c  o m*/
 *
 * @return return code
 */
private int checkForUpdates() {
    Cursor enabledHostsSourcesCursor;
    long currentLastModifiedLocal;
    long currentLastModifiedOnline;
    boolean updateAvailable = false;

    int returnCode = StatusCodes.ENABLED; // default return code

    if (Utils.isAndroidOnline(mService)) {

        mNumberOfFailedDownloads = 0;
        mNumberOfDownloads = 0;

        // get cursor over all enabled hosts source
        enabledHostsSourcesCursor = ProviderHelper.getEnabledHostsSourcesCursor(mService);

        // iterate over all hosts sources in db with cursor
        if (enabledHostsSourcesCursor != null && enabledHostsSourcesCursor.moveToFirst()) {
            do {

                mNumberOfDownloads++;

                // get url and lastModified from db
                String currentUrl = enabledHostsSourcesCursor
                        .getString(enabledHostsSourcesCursor.getColumnIndex("url"));
                currentLastModifiedLocal = enabledHostsSourcesCursor
                        .getLong(enabledHostsSourcesCursor.getColumnIndex("last_modified_local"));

                try {
                    Log.v(Constants.TAG, "Checking hosts file: " + currentUrl);

                    /* build connection */
                    URL mURL = new URL(currentUrl);
                    URLConnection connection = mURL.openConnection();
                    connection.setConnectTimeout(15000);
                    connection.setReadTimeout(30000);

                    currentLastModifiedOnline = connection.getLastModified();

                    Log.d(Constants.TAG, "mConnectionLastModified: " + currentLastModifiedOnline + " ("
                            + DateUtils.longToDateString(mService, currentLastModifiedOnline) + ")");

                    Log.d(Constants.TAG, "mCurrentLastModified: " + currentLastModifiedLocal + " ("
                            + DateUtils.longToDateString(mService, currentLastModifiedLocal) + ")");

                    // check if file is available
                    connection.connect();
                    connection.getInputStream();

                    // check if update available for this hosts file
                    if (currentLastModifiedOnline > currentLastModifiedLocal) {
                        updateAvailable = true;
                    }

                    // save last modified online for later viewing in list
                    ProviderHelper.updateHostsSourceLastModifiedOnline(mService,
                            enabledHostsSourcesCursor
                                    .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)),
                            currentLastModifiedOnline);

                } catch (Exception e) {
                    Log.e(Constants.TAG, "Exception while downloading from " + currentUrl, e);

                    mNumberOfFailedDownloads++;

                    // set last_modified_online of failed download to 0 (not available)
                    ProviderHelper.updateHostsSourceLastModifiedOnline(mService, enabledHostsSourcesCursor
                            .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)), 0);
                }

            } while (enabledHostsSourcesCursor.moveToNext());
        }

        // close cursor in the end
        if (enabledHostsSourcesCursor != null && !enabledHostsSourcesCursor.isClosed()) {
            enabledHostsSourcesCursor.close();
        }

        // if all downloads failed return download_fail error
        if (mNumberOfDownloads == mNumberOfFailedDownloads && mNumberOfDownloads != 0) {
            returnCode = StatusCodes.DOWNLOAD_FAIL;
        }
    } else {
        // only report no connection when not in background
        if (!mBackgroundExecution) {
            returnCode = StatusCodes.NO_CONNECTION;
        } else {
            Log.e(Constants.TAG, "Should not happen! In background execution is no connection available!");
        }
    }

    // set return code if update is available
    if (updateAvailable) {
        returnCode = StatusCodes.UPDATE_AVAILABLE;
    }

    // check if hosts file is applied
    if (!ApplyUtils.isHostsFileCorrect(mService, Constants.ANDROID_SYSTEM_ETC_HOSTS)) {
        returnCode = StatusCodes.DISABLED;
    }

    return returnCode;
}

From source file:org.path.common.android.utilities.ODKDatabaseUtils.java

/**
 * Get a {@link UserTable} for this table based on the given where clause. All
 * columns from the table are returned.//from   w  w  w .  j av a 2 s. com
 * <p>
 * SELECT * FROM table WHERE whereClause GROUP BY groupBy[]s HAVING
 * havingClause ORDER BY orderbyElement orderByDirection
 * <p>
 * If any of the clause parts are omitted (null), then the appropriate
 * simplified SQL statement is constructed.
 * 
 * @param db
 * @param appName
 * @param tableId
 * @param columnDefns
 * @param whereClause
 *          the whereClause for the selection, beginning with "WHERE". Must
 *          include "?" instead of actual values, which are instead passed in
 *          the selectionArgs.
 * @param selectionArgs
 *          an array of string values for bind parameters
 * @param groupBy
 *          an array of elementKeys
 * @param having
 * @param orderByElementKey
 *          elementKey to order the results by
 * @param orderByDirection
 *          either "ASC" or "DESC"
 * @return
 */
public UserTable rawSqlQuery(SQLiteDatabase db, String appName, String tableId,
        ArrayList<ColumnDefinition> columnDefns, String whereClause, String[] selectionArgs, String[] groupBy,
        String having, String orderByElementKey, String orderByDirection) {
    Cursor c = null;
    try {
        StringBuilder s = new StringBuilder();
        s.append("SELECT * FROM \"").append(tableId).append("\" ");
        if (whereClause != null && whereClause.length() != 0) {
            s.append(" WHERE ").append(whereClause);
        }
        if (groupBy != null && groupBy.length != 0) {
            s.append(" GROUP BY ");
            boolean first = true;
            for (String elementKey : groupBy) {
                if (!first) {
                    s.append(", ");
                }
                first = false;
                s.append(elementKey);
            }
            if (having != null && having.length() != 0) {
                s.append(" HAVING ").append(having);
            }
        }
        if (orderByElementKey != null && orderByElementKey.length() != 0) {
            s.append(" ORDER BY ").append(orderByElementKey);
            if (orderByDirection != null && orderByDirection.length() != 0) {
                s.append(" ").append(orderByDirection);
            } else {
                s.append(" ASC");
            }
        }
        String sqlQuery = s.toString();
        c = db.rawQuery(sqlQuery, selectionArgs);
        UserTable table = new UserTable(c, appName, tableId, columnDefns, whereClause, selectionArgs, groupBy,
                having, orderByElementKey, orderByDirection);
        return table;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Get a {@link UserTable} for this table based on the given where clause. All
 * columns from the table are returned.//from  w  ww .ja v  a2  s  .  co  m
 * <p>
 * SELECT * FROM table WHERE whereClause GROUP BY groupBy[]s HAVING
 * havingClause ORDER BY orderbyElement orderByDirection
 * <p>
 * If any of the clause parts are omitted (null), then the appropriate
 * simplified SQL statement is constructed.
 * 
 * @param db
 * @param appName
 * @param tableId
 * @param columnDefns
 * @param whereClause
 *          the whereClause for the selection, beginning with "WHERE". Must
 *          include "?" instead of actual values, which are instead passed in
 *          the selectionArgs.
 * @param selectionArgs
 *          an array of string values for bind parameters
 * @param groupBy
 *          an array of elementKeys
 * @param having
 * @param orderByElementKey
 *          elementKey to order the results by
 * @param orderByDirection
 *          either "ASC" or "DESC"
 * @return
 */
public UserTable rawSqlQuery(SQLiteDatabase db, String appName, String tableId,
        ArrayList<ColumnDefinition> columnDefns, String whereClause, String[] selectionArgs, String[] groupBy,
        String having, String orderByElementKey, String orderByDirection) {
    Cursor c = null;
    try {
        StringBuilder s = new StringBuilder();
        s.append("SELECT * FROM \"").append(tableId).append("\" ");
        if (whereClause != null && whereClause.length() != 0) {
            s.append(" WHERE ").append(whereClause);
        }
        if (groupBy != null && groupBy.length != 0) {
            s.append(" GROUP BY ");
            boolean first = true;
            for (String elementKey : groupBy) {
                if (!first) {
                    s.append(", ");
                }
                first = false;
                s.append(elementKey);
            }
            if (having != null && having.length() != 0) {
                s.append(" HAVING ").append(having);
            }
        }
        if (orderByElementKey != null && orderByElementKey.length() != 0) {
            s.append(" ORDER BY ").append(orderByElementKey);
            if (orderByDirection != null && orderByDirection.length() != 0) {
                s.append(" ").append(orderByDirection);
            } else {
                s.append(" DESC");
            }
        }
        String sqlQuery = s.toString();
        c = db.rawQuery(sqlQuery, selectionArgs);
        UserTable table = new UserTable(c, appName, tableId, columnDefns, whereClause, selectionArgs, groupBy,
                having, orderByElementKey, orderByDirection);
        return table;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
}