Example usage for android.database.sqlite SQLiteDatabase close

List of usage examples for android.database.sqlite SQLiteDatabase close

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase close.

Prototype

public void close() 

Source Link

Document

Releases a reference to the object, closing the object if the last reference was released.

Usage

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

/**
 * Gets the creates the id.//from   w  w  w  .  j a v  a 2 s . c  o m
 * 
 * @return the creates the id
 */
private int getCreateId() {
    int newId = 0;
    SQLiteDatabase db = getReadableDatabase();
    Cursor cr = db.query("sqlite_sequence", new String[] { "name", "seq" }, "name = ?",
            new String[] { getTableName() }, null, null, null);
    if (cr.moveToFirst()) {
        newId = cr.getInt(cr.getColumnIndex("seq"));
    }
    cr.close();
    db.close();
    return newId;
}

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

/**
 * Count./*from   w w w  . j av a 2 s .c  o  m*/
 * 
 * @param where
 *            the where
 * @param whereArgs
 *            the where args
 * @return the int
 */
public int count(String where, Object[] whereArgs) {

    int count = 0;
    SQLiteDatabase db = getReadableDatabase();
    String whr = getWhereClause(where);
    String[] args = getWhereArgs(whr, whereArgs);
    Cursor cr = db.query(getTableName(), new String[] { "count(*) as total" }, whr, args, null, null, null);
    cr.moveToFirst();
    count = cr.getInt(0);
    cr.close();
    db.close();
    return count;
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

public ArrayList<SearchListItem> getFavoritesForString(String srchString) {
    ArrayList<SearchListItem> ret = new ArrayList<SearchListItem>();

    SQLiteDatabase db = getReadableDatabase();
    if (db == null)
        return null;

    String[] columns = { KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_SOURCE, KEY_SUBSOURCE, KEY_LAT, KEY_LONG,
            KEY_API_ID };//from  w ww  . j  a v a  2 s. co  m

    Cursor cursor = db.query(TABLE_FAVORITES, columns, KEY_NAME + " LIKE ? ",
            new String[] { "%" + srchString + "%" }, null, null, null, null);

    if (cursor != null && cursor.moveToFirst()) {
        while (cursor != null && !cursor.isAfterLast()) {
            int colId = cursor.getColumnIndex(KEY_ID);
            int colName = cursor.getColumnIndex(KEY_NAME);
            int colAddress = cursor.getColumnIndex(KEY_ADDRESS);
            int colSubSource = cursor.getColumnIndex(KEY_SUBSOURCE);
            int colLat = cursor.getColumnIndex(KEY_LAT);
            int colLong = cursor.getColumnIndex(KEY_LONG);
            int colApiId = cursor.getColumnIndex(KEY_API_ID);

            FavoritesData fd = new FavoritesData(cursor.getInt(colId), cursor.getString(colName),
                    cursor.getString(colAddress), cursor.getString(colSubSource), cursor.getDouble(colLat),
                    cursor.getDouble(colLong), cursor.getInt(colApiId));

            ret.add((SearchListItem) fd);
            cursor.moveToNext();
        }
    }

    if (cursor != null)
        cursor.close();

    db.close();

    return ret;
}

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

/**
 * Gets the name./*from w ww  .  j  a v a 2 s  .  c  om*/
 * 
 * @param model
 *            the model
 * @param row_id
 *            the row_id
 * @return the name
 */
public String getName(int row_id) {
    String name = "false";
    if (getColumn("name") != null) {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cr = db.query(getTableName(), new String[] { "name" }, OColumn.ROW_ID + " = ?",
                new String[] { row_id + "" }, null, null, null);
        if (cr.moveToFirst()) {
            name = cr.getString(cr.getColumnIndex("name"));
        }
        cr.close();
        db.close();
    }
    return name;
}

From source file:org.emergent.android.weave.syncadapter.SyncCache.java

/**
 * @param queryResult the resulte of querying the meta/global node
 * @return false if caches must be expired
 *//*from   ww  w .ja  va  2 s  . co m*/
public Date validateMetaGlobal(QueryResult<JSONObject> queryResult, String engineName) {
    long retval = 0;
    SQLiteDatabase db = null;
    try {
        String uriStr = queryResult.getUri().toASCIIString();
        JSONObject jsonObj = queryResult.getValue();
        Properties flattened = convertMetaGlobalToFlatProperties(jsonObj);
        String gVer = flattened.getProperty("storageVersion");
        String gSyncId = flattened.getProperty("syncID");
        String eVer = flattened.getProperty(engineName + ".version");
        String eSyncId = flattened.getProperty(engineName + ".syncID");
        db = m_helper.getWritableDatabase();
        retval = checkCacheDb(db, uriStr, engineName, gVer, gSyncId, eVer, eSyncId);
        if (retval > 0) {
            return new Date(retval);
        } else if (retval == MGD_MISMATCH) {
            clear();
        }

        ContentValues values = new ContentValues();
        values.put(MgColumns.NODE_URI, uriStr);
        values.put(MgColumns.ENGINE_NAME, engineName);
        values.put(MgColumns.LAST_MODIFIED, 0);
        values.put(MgColumns.GLOBAL_SYNCID, gSyncId);

        Integer gVerInt = null;
        try {
            gVerInt = Integer.valueOf(gVer);
        } catch (NumberFormatException ignored) {
        }
        values.put(MgColumns.GLOBAL_VERSION, gVerInt);

        values.put(MgColumns.ENGINE_SYNCID, eSyncId);

        Integer eVerInt = null;
        try {
            eVerInt = Integer.valueOf(eVer);
        } catch (NumberFormatException ignored) {
        }
        values.put(MgColumns.ENGINE_VERSION, eVerInt);
        long uriId = db.insert(META_GLOBAL_TABLE_NAME, null, values);

        return null;
    } finally {
        if (db != null)
            try {
                db.close();
            } catch (Exception ignored) {
            }
    }
}

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

/**
 * Select one to many rel ids.//from ww w .ja va 2 s  . c  om
 * 
 * @param base
 *            the base
 * @param rel
 *            the rel
 * @param base_id
 *            the base_id
 * @param ref_column
 *            the ref_column
 * @return the list
 */
public List<Integer> selecto2MRelIds(OModel base, OModel rel, int base_id, String ref_column) {
    List<Integer> ids = new ArrayList<Integer>();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cr = db.query(rel.getTableName(), new String[] { "id" }, ref_column + " = ?",
            new String[] { base_id + "" }, null, null, null);
    if (cr.moveToFirst()) {
        do {
            ids.add(cr.getInt(cr.getColumnIndex("id")));
        } while (cr.moveToNext());
    }
    cr.close();
    db.close();
    return ids;
}

From source file:com.openerp.orm.ORM.java

/**
 * Execute sql query as per user requirement.
 * /*from   ww  w . ja va2s .  c  o  m*/
 * @param model
 *            the model
 * @param columns
 *            the columns
 * @param where
 *            the where
 * @param args
 *            the args query arguments
 * @return the cursor of results
 */
public List<HashMap<String, Object>> executeSQL(String model, String[] columns, String[] where, String[] args) {
    SQLiteDatabase db = getWritableDatabase();
    StringBuffer sqlQuery = new StringBuffer();
    sqlQuery.append("SELECT ");
    sqlQuery.append(TextUtils.join(",", columns));
    sqlQuery.append(" FROM ");
    sqlQuery.append(modelToTable(model));
    sqlQuery.append(" WHERE ");
    sqlQuery.append(TextUtils.join(" ", where));

    List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

    Cursor cursor = db.rawQuery(sqlQuery.toString(), args);
    if (cursor.moveToFirst()) {
        do {
            HashMap<String, Object> row = new HashMap<String, Object>();
            for (String key : columns) {
                row.put(key, cursor.getString(cursor.getColumnIndex(key)));
            }
            data.add(row);
        } while (cursor.moveToNext());
    }
    db.close();
    cursor.close();
    return data;

}

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  . java  2s  . c  om

        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:android.melbournehistorymap.MapsActivity.java

private void updateMap() {

    //Now get the maps central location
    LatLng mapCenter = mMap.getCameraPosition().target;
    //clear markers
    mMap.clear();/*w w  w  . ja  va  2  s.c  om*/

    //if user tries to zoom to far out of the world, bring them back down to earth...
    if (mMap.getCameraPosition().zoom < ZOOM_RESTRICT_LEVEL) {
        CameraPosition cameraPosition = new CameraPosition.Builder().target(mapCenter) // Sets the center of the map to location user
                .zoom(ZOOM_RESTRICT_LEVEL) // Sets the zoom
                .bearing(0) // Sets the orientation of the camera to east
                .tilt(25) // Sets the tilt of the camera to 30 degrees
                .build(); // Creates a CameraPosition from the builder

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    //rebuild lat/lng variable to be used for Google Places API requests
    double lat = mapCenter.latitude;
    double lng = mapCenter.longitude;
    double zoom = mMap.getCameraPosition().zoom;

    LatLng leftBorder = mMap.getProjection().getVisibleRegion().farLeft;

    //Work out distance between current location and place location
    //Source Library: https://github.com/googlemaps/android-maps-utils

    double radius = SphericalUtil.computeDistanceBetween(mapCenter, leftBorder);

    //Now that we have the new long/latitude of the camera position include zoom level
    //Lets check the database to determine if the user has been here already
    //Set DB helper
    DBHelper myDBHelper = new DBHelper(MapsActivity.this, WikiAPI.DB_NAME, null, WikiAPI.VERSION);
    //Open DB as readable only.
    SQLiteDatabase db = myDBHelper.getWritableDatabase();
    //Prepare DB Search variables
    DecimalFormat dfLat = new DecimalFormat("#.##");
    DecimalFormat dfLng = new DecimalFormat("#.##");
    DecimalFormat dfZoom = new DecimalFormat("#");
    dfLat.setRoundingMode(RoundingMode.CEILING);
    dfLng.setRoundingMode(RoundingMode.CEILING);
    dfZoom.setRoundingMode(RoundingMode.CEILING);
    double dblLat = Double.parseDouble(dfLat.format(lat));
    double dblLng = Double.parseDouble(dfLng.format(lng));
    double dblZoom = Double.parseDouble(dfZoom.format(zoom));
    //Limit by 1 rows
    Cursor cursor = db.query(DBHelper.LOC_TABLE, null,
            "LAT LIKE '" + dblLat + "%' AND LNG LIKE '" + dblLng + "%' AND ZOOM = '" + dblZoom + "'", null,
            null, null, null, "1");

    int count = cursor.getCount();

    if (count == 0) {
        //user has not been to this location/zoom level  before
        //add the new location data, then trigger the google place webservice api
        ContentValues values = new ContentValues();

        values.put("lat", String.valueOf(dblLat));
        values.put("lng", String.valueOf(dblLng));
        values.put("zoom", String.valueOf(dblZoom));
        db.insert(DBHelper.LOC_TABLE, null, values);

        String url;
        url = updateURL(lat, lng, radius);
        List<List<String>> googlePlaces = null; //null on first reference, the list is updated within the method callstack
        db.close();

        GoogleAPI.callMapMethod(mMap, url, MapsActivity.this, googlePlaces, spinner);
    }
    if (count == 1) {
        //user has been here before
        //get place data from DB and not from the API
        //if place data returned hasn't been updated in 30 days - update data using getPlaceByID method
        Cursor placeCursor = db.query(DBHelper.TABLE_NAME, null, "PLACE_TYPES LIKE '%point_of_interest%'", null,
                null, null, null, null);

        List<List<String>> googlePlaces = new ArrayList<List<String>>();

        while (placeCursor.moveToNext()) {
            String place_ID = placeCursor.getString(placeCursor.getColumnIndex("PLACE_ID"));
            String placeName = placeCursor.getString(placeCursor.getColumnIndex("PLACE_NAME"));
            String placeLoc = placeCursor.getString(placeCursor.getColumnIndex("PLACE_LOCATION"));
            String placeLat = placeCursor.getString(placeCursor.getColumnIndex("LAT"));
            String placeLng = placeCursor.getString(placeCursor.getColumnIndex("LNG"));

            //if lat and long from database is in the search bounds, add to the list of data to be shown
            LatLngBounds SEARCH_BOUNDS = mMap.getProjection().getVisibleRegion().latLngBounds;
            LatLng search_loc = new LatLng(Double.parseDouble(placeLat), Double.parseDouble(placeLng));

            if (SEARCH_BOUNDS.contains(search_loc)) {
                //now what data do we want?
                //Initiate a place data array
                List<String> placeData = new ArrayList<String>();

                //add place data to its array
                placeData.add(placeName); //0
                placeData.add(place_ID); //1
                placeData.add(placeLoc); //2
                placeData.add(String.valueOf(placeLat)); //3
                placeData.add(String.valueOf(placeLng)); //4
                placeData.add(""); //5
                placeData.add(""); //6

                //send the place specific data to the google places array list
                googlePlaces.add(placeData);
            }
        }
        db.close();

        //TODO: Get this method off the main UI thread!
        GoogleAPI.filterPlaces(googlePlaces, mMap, this, spinner);
    }
}

From source file:org.opendatakit.sync.ProcessRowDataChanges.java

/**
 * Synchronize all synchronized tables with the cloud.
 * <p>// w w  w .ja v  a2s .c  o  m
 * This becomes more complicated with the ability to synchronize files. The
 * new order is as follows:
 * <ol>
 * <li>Synchronize app-level files. (i.e. those files under the appid
 * directory that are NOT then under the tables, instances, metadata, or
 * logging directories.) This is a multi-part process:
 * <ol>
 * <li>Get the app-level manifest, download any files that have changed
 * (differing hashes) or that do not exist.</li>
 * <li>Upload the files that you have that are not on the manifest. Note that
 * this could be suppressed if the user does not have appropriate permissions.
 * </li>
 * </ol>
 * </li>
 *
 * <li>Synchronize the static table files for those tables that are set to
 * sync. (i.e. those files under "appid/tables/tableid"). This follows the
 * same multi-part steps above (1a and 1b).</li>
 *
 * <li>Synchronize the table properties/metadata.</li>
 *
 * <li>Synchronize the table data. This includes the data in the db as well as
 * those files under "appid/instances/tableid". This file synchronization
 * follows the same multi-part steps above (1a and 1b).</li>
 *
 * <li>TODO: step four--the synchronization of instances files--should perhaps
 * also be allowed to be modular and permit things like ODK Submit to handle
 * data and files separately.</li>
 * </ol>
 * <p>
 * TODO: This should also somehow account for zipped files, exploding them or
 * what have you.
 * </p>
 * 
 * @param workingListOfTables
 *          -- the list of tables we should sync with the server. This will be
 *          a subset of the available local tables -- if there was any error
 *          during the sync'ing of the table-level files, or if the table
 *          schema does not match, the local table will be omitted from this
 *          list.
 */
public void synchronizeDataRowsAndAttachments(List<TableResource> workingListOfTables,
        boolean deferInstanceAttachments) {
    log.i(TAG, "entered synchronize()");

    SQLiteDatabase db = null;

    // we can assume that all the local table properties should
    // sync with the server.
    for (TableResource tableResource : workingListOfTables) {
        // Sync the local media files with the server if the table
        // existed locally before we attempted downloading it.

        String tableId = tableResource.getTableId();
        TableDefinitionEntry te;
        ArrayList<ColumnDefinition> orderedDefns;
        String displayName;
        try {
            db = sc.getDatabase();
            te = ODKDatabaseUtils.get().getTableDefinitionEntry(db, tableId);
            orderedDefns = TableUtil.get().getColumnDefinitions(db, sc.getAppName(), tableId);
            displayName = TableUtil.get().getLocalizedDisplayName(db, tableId);
        } finally {
            if (db != null) {
                db.close();
                db = null;
            }
        }

        synchronizeTableDataRowsAndAttachments(tableResource, te, orderedDefns, displayName,
                deferInstanceAttachments);
        sc.incMajorSyncStep();
    }
}