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.spoiledmilk.ibikecph.util.DB.java

public ArrayList<SearchListItem> getSearchHistoryForString(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_START_DATE, KEY_END_DATE, KEY_SOURCE, KEY_SUBSOURCE,
            KEY_LAT, KEY_LONG };//w w  w  .j  a v a 2s  .c  o  m

    Cursor cursor = db.query(TABLE_SEARCH_HISTORY, columns, KEY_NAME + " LIKE ? OR " + KEY_ADDRESS + " LIKE ?",
            new String[] { "%" + srchString + "%", "%" + 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 colStartDate = cursor.getColumnIndex(KEY_START_DATE);
            int colEndDate = cursor.getColumnIndex(KEY_END_DATE);
            int colSource = cursor.getColumnIndex(KEY_SOURCE);
            int colSubSource = cursor.getColumnIndex(KEY_SUBSOURCE);
            int colLat = cursor.getColumnIndex(KEY_LAT);
            int colLong = cursor.getColumnIndex(KEY_LONG);

            HistoryData hd = new HistoryData(cursor.getInt(colId), cursor.getString(colName),
                    cursor.getString(colAddress), cursor.getString(colStartDate), cursor.getString(colEndDate),
                    cursor.getString(colSource), cursor.getString(colSubSource), cursor.getDouble(colLat),
                    cursor.getDouble(colLong));
            if (hd.getName() != null && !hd.getName().trim().equals(""))
                ret.add(hd);
            cursor.moveToNext();
        }
    }

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

    db.close();

    return ret;
}

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

public ArrayList<SearchListItem> getSearchHistory() {

    ArrayList<SearchListItem> ret = new ArrayList<SearchListItem>();

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

    String[] columns = { KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_START_DATE, KEY_END_DATE, KEY_SOURCE, KEY_SUBSOURCE,
            KEY_LAT, KEY_LONG };/*  ww  w .  j a  v  a2  s .  c  om*/

    Cursor cursor = db.query(TABLE_SEARCH_HISTORY, columns, null, null, null, null, KEY_START_DATE + " DESC",
            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 colStartDate = cursor.getColumnIndex(KEY_START_DATE);
            int colEndDate = cursor.getColumnIndex(KEY_END_DATE);
            int colSource = cursor.getColumnIndex(KEY_SOURCE);
            int colSubSource = cursor.getColumnIndex(KEY_SUBSOURCE);
            int colLat = cursor.getColumnIndex(KEY_LAT);
            int colLong = cursor.getColumnIndex(KEY_LONG);

            HistoryData hd = new HistoryData(cursor.getInt(colId), cursor.getString(colName),
                    cursor.getString(colAddress), cursor.getString(colStartDate), cursor.getString(colEndDate),
                    cursor.getString(colSource), cursor.getString(colSubSource), cursor.getDouble(colLat),
                    cursor.getDouble(colLong));
            if (hd.getName() != null && !hd.getName().trim().equals("")) {
                ret.add(hd);
            }
            if (ret.size() > 10) {
                break;
            }
            cursor.moveToNext();
        }
    }

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

    db.close();

    return ret;
}

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

public void storeManyToManyRecord(String column_name, int row_id, List<Integer> relationIds, Command command)
        throws InvalidObjectException {
    OColumn column = getColumn(column_name);
    if (column != null) {
        OModel rel_model = createInstance(column.getType());
        String table = getTableName() + "_" + rel_model.getTableName() + "_rel";
        String base_column = getTableName() + "_id";
        String rel_column = rel_model.getTableName() + "_id";

        SQLiteDatabase db = getWritableDatabase();
        try {//from   ww w .  ja v a2  s.co m
            switch (command) {
            case Add:
                if (relationIds.size() > 0) {
                    for (int id : relationIds) {
                        ContentValues values = new ContentValues();
                        values.put(base_column, row_id);
                        values.put(rel_column, id);
                        values.put("_write_date", ODateUtils.getDate());
                        db.insert(table, null, values);
                    }
                }
                break;
            case Update:
                break;
            case Delete:
                // Deleting records to relation model
                if (relationIds.size() > 0) {
                    for (int id : relationIds) {
                        db.delete(table, base_column + " = ? AND  " + rel_column + " = ?",
                                new String[] { row_id + "", id + "" });
                    }
                }
                break;
            case Replace:
                // Removing old entries
                db.delete(table, base_column + " = ?", new String[] { row_id + "" });
                // Creating new entries
                storeManyToManyRecord(column_name, row_id, relationIds, Command.Add);
                break;
            }
        } finally {
            db.close();
            rel_model.close();
        }
    } else {
        throw new InvalidObjectException(
                "Column [" + column_name + "] not found in " + getModelName() + " model.");

    }
}

From source file:me.piebridge.bible.Bible.java

private boolean checkVersionMeta(File file, String version) {
    SQLiteDatabase metadata = null;
    try {//ww  w .java  2s  .com
        metadata = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null,
                SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        String dataversion = version.replace("demo", "");
        if (!versionFullnames.containsKey(version)) {
            versionFullnames.put(version, getVersionMetadata("fullname", metadata, dataversion));
        }
        if (!versionNames.containsKey(version)) {
            versionNames.put(version, getVersionMetadata("name", metadata, dataversion));
        }
        versionDates.put(version, getVersionMetadata("date", metadata, "0"));
        // setMetadata(metadata, dataversion, false);
        return true;
    } catch (Exception e) {
        try {
            file.delete();
        } catch (Exception f) {
        }
        return false;
    } finally {
        if (metadata != null) {
            metadata.close();
        }
    }
}

From source file:com.aero2.android.DefaultActivities.SmogMapActivity.java

public boolean addHeatMap(GoogleMap map) {
    Log.v(LOG_TAG, "Entered the addHeatMapFunction");
    AirAzureDbHelper airAzureDbHelper = new AirAzureDbHelper(getApplicationContext());
    final SQLiteDatabase db = airAzureDbHelper.getReadableDatabase();
    //Using the simple cursor loader class to query the cache on a background thread
    SimpleCursorLoader simpleCursorLoader = new SimpleCursorLoader(getApplicationContext()) {
        @Override/*  w  ww. j a  va  2 s. c  o  m*/
        public Cursor loadInBackground() {

            //All this work is done in the background thread

            String[] columns = new String[] { AirAzureContract.AirAzureEntry.COLUMN_AIR_INDEX,
                    AirAzureContract.AirAzureEntry.COLUMN_LAT, AirAzureContract.AirAzureEntry.COLUMN_LONG };
            Cursor mCursor;
            mCursor = db.query(AirAzureContract.AirAzureEntry.TABLE_NAME, columns, null, null, null, null,
                    null);
            return mCursor;

        }
    };

    //Getting a cursor containing the map data from the results cache
    Cursor cursor;
    cursor = simpleCursorLoader.loadInBackground();

    //******************************** Setting up the overlay on the Map Using the cursor *************************************
    //   STARTS HERE

    // Create the gradient.
    int[] colors = { Color.rgb(0, 255, 0), // green
            Color.rgb(255, 255, 0), // yellow
            Color.rgb(220, 0, 0) // red
    };

    float[] startPoints = { 0f, 0.5f, 1f };

    Gradient gradient = new Gradient(colors, startPoints);

    Log.v("CusorLength:", " cursor length is " + cursor.getCount());
    if (cursor.getCount() > 0) {
        //Make a Weighted heatmap of the Smog
        HeatmapTileProvider mProvider = new HeatmapTileProvider.Builder()
                .weightedData(getListForHeatMap(cursor)).gradient(gradient).opacity(0.3).radius(10).build();
        map.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
        db.close();
        cursor.close();
        return true;
    } else {
        db.close();
        cursor.close();
        return false;
    }
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public MessageArrayContent getLastMessage(String buddyId) {
    MessageArrayContent mac = null;//from   w w w  . j a  v  a  2  s.c o m
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    try {
        String[] columns = new String[] { MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL,
                MessageHistoryContract.MessageEntry._ID,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID };
        Cursor lastMessage = db.query(buddyId, columns, null, null, null, null,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP + " DESC", "1");
        lastMessage.moveToFirst();
        if (lastMessage.getCount() != 0 && lastMessage.moveToFirst()) {
            String type = lastMessage.getString(1);
            SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES, 0);
            String me = preferences.getString(Constants.USERNAME, "");
            boolean sent = me.equals(lastMessage.getString(0));

            if (TYPE_TEXT.equals(type)) {
                mac = new TextMessage(!sent, lastMessage.getString(2), lastMessage.getLong(4),
                        lastMessage.getString(3), lastMessage.getLong(6), lastMessage.getLong(7));
            } else if (TYPE_IMAGE.equals(type)) {
                JSONArray contentJSON = new JSONArray(lastMessage.getString(2));
                mac = new ImageMessage(!sent, contentJSON.getString(0), contentJSON.getString(1),
                        lastMessage.getString(5), lastMessage.getInt(6), lastMessage.getLong(4),
                        lastMessage.getString(3), lastMessage.getLong(6), lastMessage.getString(1),
                        lastMessage.getLong(7));
            }
        }
    } catch (Exception e) {

    } finally {
        db.close();
    }
    return mac;
}

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

private void getMedications() {
    try {// w w w.ja  va2s  . c om
        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:com.openerp.orm.ORM.java

/**
 * Count.//from  w w w .  j a v a 2  s  .  c  o m
 * 
 * Returns number of row in local database. Zero (0) if there are no any row
 * related to where clause.
 * 
 * @param dbHelper
 *            the database helper
 * @param where
 *            the where clause conditions
 * @param whereArgs
 *            the where args
 * @return the int (number of row in database)
 */
public int count(BaseDBHelper dbHelper, String[] where, String[] whereArgs) {
    SQLiteDatabase db = getWritableDatabase();
    StringBuffer sql = new StringBuffer();
    sql.append("SELECT count(*) as total FROM ");
    sql.append(modelToTable(dbHelper.getModelName()));
    sql.append(" WHERE ");
    if (where != null && where.length > 0) {

        for (String whr : where) {
            if (whr.contains(".")) {
                String[] datas = whr.split("\\.");
                String table = datas[0];
                String rel_id = table + "_id";
                String fetch_id = modelToTable(dbHelper.getModelName()) + "_id";
                String rel_table = modelToTable(dbHelper.getModelName()) + "_" + table + "_rel";
                String subQue = "id in (SELECT " + fetch_id + " FROM " + rel_table + " WHERE " + rel_id
                        + " = ?) ";
                sql.append(subQue);
                sql.append(" ");

            } else {
                sql.append(whr);
                sql.append(" ");
            }

        }
        sql.append(" and oea_name = '" + user_name + "'");
    } else {
        sql.append(" oea_name = '" + user_name + "'");
    }
    Cursor cursor = db.rawQuery(sql.toString(), whereArgs);
    cursor.moveToFirst();
    int count = cursor.getInt(0);
    db.close();
    cursor.close();
    return count;

}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public MessageArrayContent getMessage(String buddyId, long messageId) {
    int index = buddyId.indexOf('@');
    if (index >= 0) {
        buddyId = buddyId.substring(0, index);
    }/*  w ww.ja  va  2 s .com*/
    MessageArrayContent mac = null;
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    String[] columns = new String[] { MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP,
            MessageHistoryContract.MessageEntry._ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID };
    String sel = MessageHistoryContract.MessageEntry._ID + "=?";
    Cursor message = db.query(buddyId, columns, sel, new String[] { String.valueOf(messageId) }, null, null,
            null);

    message.moveToFirst();
    String from = message.getString(0);
    SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES, 0);
    String me = preferences.getString(Constants.USERNAME, "");
    String type = message.getString(1);
    String content = message.getString(2);
    String url = message.getString(3);
    int progress = 0;
    String status = message.getString(4);
    long time = message.getLong(5);
    long _ID = message.getLong(6);
    long othersId = message.getLong(7);
    switch (type) {
    case (MessageHistory.TYPE_TEXT):
        mac = new TextMessage(!me.equals(from), content, time, status, _ID, othersId);
        break;
    case (MessageHistory.TYPE_IMAGE):
        try {
            JSONArray contentJSON = new JSONArray(content);
            mac = new ImageMessage(!me.equals(from), //left
                    contentJSON.getString(0), //File
                    contentJSON.getString(1), //description
                    url, //url
                    progress, //progress
                    time, //timeStamp
                    status, //status
                    _ID, //_ID
                    buddyId, //buddyID
                    othersId); //othersId
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    }
    db.close();
    return mac;
}

From source file:com.snt.bt.recon.database.DBHandler.java

public <T> void updateSyncStatus(Class<T> cl, JSONObject obj)
        throws InstantiationException, IllegalAccessException, JSONException {
    T inst = cl.newInstance();/*  w w w .j a  va  2s  .  c om*/
    SQLiteDatabase database = this.getWritableDatabase();
    String updateQuery = "";

    if (inst instanceof Trip) {
        if (obj.get("status").toString().equals("yes"))
            database.delete(TABLE_TRIPS,
                    KEY_SESSION_ID + "=" + "'" + UUID.fromString(obj.get("session_id").toString()) + "'", null);
        else {
            updateQuery = "UPDATE " + TABLE_TRIPS + " set " + KEY_UPLOAD_STATUS + " = '"
                    + obj.get("status").toString() + "' where " + KEY_SESSION_ID + "=" + "'"
                    + UUID.fromString(obj.get("session_id").toString()) + "'";
            database.execSQL(updateQuery);
        }
    } else if (inst instanceof GPSLocation)
        if (obj.get("status").toString().equals("yes"))
            database.delete(TABLE_LOCATIONS,
                    KEY_LOCATION_ID + "=" + "'" + UUID.fromString(obj.get("location_id").toString()) + "'",
                    null);
        else {
            updateQuery = "UPDATE " + TABLE_LOCATIONS + " set " + KEY_UPLOAD_STATUS + " = '"
                    + obj.get("status").toString() + "' where " + KEY_LOCATION_ID + "=" + "'"
                    + UUID.fromString(obj.get("location_id").toString()) + "'";
            database.execSQL(updateQuery);
        }
    else if (inst instanceof BluetoothClassicEntry)
        if (obj.get("status").toString().equals("yes"))
            database.delete(TABLE_BC, "id=" + obj.getInt("id") + "", null);
        else {
            updateQuery = "UPDATE " + TABLE_BC + " set " + KEY_UPLOAD_STATUS + " = '"
                    + obj.get("status").toString() + "' where id=" + obj.getInt("id") + "";
            database.execSQL(updateQuery);
        }
    else if (inst instanceof BluetoothLowEnergyEntry)
        if (obj.get("status").toString().equals("yes"))
            database.delete(TABLE_BLE, "id=" + obj.getInt("id") + "", null);
        else {
            updateQuery = "UPDATE " + TABLE_BLE + " set " + KEY_UPLOAD_STATUS + " = '"
                    + obj.get("status").toString() + "' where id=" + obj.getInt("id") + "";
            database.execSQL(updateQuery);
        }

    //Log.d("DatabaseTest", updateQuery);
    database.close();
}