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:net.olejon.mdapp.AtcCodesActivity.java

private void getSubstance(String substanceName) {
    SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext).getReadableDatabase();

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

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

        Intent intent = new Intent(mContext, SubstanceActivity.class);
        intent.putExtra("id", id);
        startActivity(intent);/* w w w.  ja  v  a 2s.  c o m*/
    } else {
        cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_SUBSTANCES, queryColumns,
                SlDataSQLiteHelper.SUBSTANCES_COLUMN_NAME + " LIKE " + mTools.sqe("%" + substanceName + "%"),
                null, null, null, SlDataSQLiteHelper.SUBSTANCES_COLUMN_ID);

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

            Intent intent = new Intent(mContext, SubstanceActivity.class);
            intent.putExtra("id", id);
            startActivity(intent);
        } else {
            mTools.showToast(getString(R.string.atc_codes_could_not_find_substance), 1);
        }
    }

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

From source file:org.akop.crosswords.Storage.java

public long write(long folderId, long puzzleId, Crossword crossword) {
    long started = SystemClock.uptimeMillis();

    StorageHelper helper = getHelper();/*from   w w w.  j  a  v  a 2 s  .c o m*/
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues cv;

    try {
        cv = new ContentValues();
        cv.put(Puzzle.CLASS, crossword.getClass().getName());
        cv.put(Puzzle.SOURCE_URL, crossword.getSourceUrl());
        cv.put(Puzzle.TITLE, crossword.getTitle());
        cv.put(Puzzle.AUTHOR, crossword.getAuthor());
        cv.put(Puzzle.COPYRIGHT, crossword.getCopyright());
        cv.put(Puzzle.HASH, crossword.getHash());
        cv.put(Puzzle.SOURCE_ID, crossword.getSourceId());
        cv.put(Puzzle.FOLDER_ID, folderId);
        cv.put(Puzzle.OBJECT, mGson.toJson(crossword));
        cv.put(Puzzle.OBJECT_VERSION, 1);
        cv.put(Puzzle.LAST_UPDATED, System.currentTimeMillis());

        Long millis = null;
        if (crossword.getDate() != null) {
            millis = crossword.getDate().getMillis();
        }
        cv.put(Puzzle.DATE, millis);

        if (puzzleId != ID_NOT_FOUND) {
            db.update(Puzzle.TABLE, cv, Puzzle._ID + " = " + puzzleId, null);
        } else {
            puzzleId = db.insert(Puzzle.TABLE, null, cv);
        }
    } finally {
        db.close();
    }

    Crosswords.logv("Wrote crossword %s (%dms)", crossword.getHash(), SystemClock.uptimeMillis() - started);

    Intent outgoing = new Intent(ACTION_PUZZLE_CHANGE);
    outgoing.putExtra(INTENT_PUZZLE_ID, puzzleId);
    outgoing.putExtra(INTENT_PUZZLE_URL, crossword.getSourceUrl());

    sendLocalBroadcast(outgoing);

    return puzzleId;
}

From source file:ru.gkpromtech.exhibition.db.Table.java

public List<Pair<Entity[], T>> selectJoined(Join[] joins, String selection, String[] selectionArgs,
        String orderBy, String groupBy)
        throws InvalidClassException, IllegalAccessException, InstantiationException {

    List<Pair<Entity[], T>> result = new ArrayList<>();
    Table<? extends Entity>[] tables = new Table<?>[joins.length];

    StringBuilder query = new StringBuilder();
    for (int i = 0; i < joins.length; ++i) {
        tables[i] = ((DbHelper) mSqlHelper).getTableFor(joins[i].entity);
        for (String column : tables[i].mColumns) {
            query.append(",f").append(i).append(".").append(column);
        }//  w  w w.j  a  v a 2 s. c o m
    }
    for (String column : mColumns)
        query.append(",t.").append(column);
    query.replace(0, 1, "SELECT "); // first comma -> select

    query.append("\nFROM ").append(mTableName).append(" t");
    for (int i = 0; i < joins.length; ++i) {
        Join join = joins[i];
        query.append("\n");
        if (join.type != null)
            query.append(join.type).append(" ");
        query.append("JOIN ").append(tables[i].mTableName).append(" f").append(i).append(" ON ");
        if (join.customJoinOn != null) {
            query.append(join.customJoinOn);
        } else {
            query.append("f").append(i).append(".").append(join.entityRow).append(" = t.").append(join.row);
        }
    }

    if (selection != null)
        query.append("\nWHERE ").append(selection);
    if (groupBy != null)
        query.append("\nGROUP BY ").append(groupBy);
    if (orderBy != null)
        query.append("\nORDER BY ").append(orderBy);

    String queryString = query.toString();
    if (BuildConfig.DEBUG)
        Log.d("PP", queryString);

    SQLiteDatabase db = mSqlHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(queryString, selectionArgs);

    //noinspection TryFinallyCanBeTryWithResources
    try {
        while (cursor.moveToNext()) {
            int col = 0;
            Entity[] entities = new Entity[joins.length];
            for (int i = 0; i < joins.length; ++i) {
                Table<? extends Entity> table = tables[i];
                entities[i] = joins[i].entity.newInstance();
                for (int j = 0; j < table.mFields.length; ++j, ++col)
                    fillFieldValue(table.mType[j], table.mFields[j], entities[i], cursor, col);
            }

            T entity = mEntityClass.newInstance();
            for (int j = 0; j < mFields.length; ++j, ++col)
                fillFieldValue(mType[j], mFields[j], entity, cursor, col);
            result.add(new Pair<>(entities, entity));
        }
    } finally {
        cursor.close();
        db.close();
    }

    return result;
}

From source file:mmpud.project.daycountwidget.DayCountMainActivity.java

private void updateAdapter() {
    mAdapter.clear();//  ww w  .  ja  va  2s .com
    // query from database
    if (mDbHelper == null) {
        mDbHelper = new DayCountDbHelper(this);
    }
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    // get all available day count widget ids
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    ComponentName component = new ComponentName(this, DayCountWidgetProvider.class);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(component);
    for (int appWidgetId : appWidgetIds) {
        Cursor cursor = db.query(Contract.Widget.TABLE_NAME, null, Contract.Widget.WIDGET_ID + "=?",
                new String[] { String.valueOf(appWidgetId) }, null, null, null);
        long targetDateMillis;
        String title;
        String bodyStyle;
        int countBy;
        if (cursor.moveToFirst()) {
            targetDateMillis = cursor.getLong(cursor.getColumnIndexOrThrow(TARGET_DATE));
            title = cursor.getString(cursor.getColumnIndexOrThrow(EVENT_TITLE));
            bodyStyle = cursor.getString(cursor.getColumnIndexOrThrow(BODY_STYLE));
            countBy = cursor.getInt(cursor.getColumnIndexOrThrow(COUNT_BY));
        } else {
            targetDateMillis = LocalDate.now().atStartOfDay().atZone(ZoneOffset.UTC).toInstant().toEpochMilli();
            title = "";
            bodyStyle = String.valueOf(ContextCompat.getColor(this, R.color.body_black));
            countBy = COUNT_BY_DAY;
        }
        mAdapter.add(new DayCountWidget(appWidgetId, title, null, targetDateMillis, countBy, null, bodyStyle));
        cursor.close();
    }
    db.close();
}

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

/**
 * Checks for record./*  w w  w .  ja  v a 2  s .c o m*/
 * 
 * @param db
 *            the db
 * @param id
 *            the id
 * @return true, if successful
 */
public boolean hasRecord(BaseDBHelper db, int id) {
    SQLiteDatabase dbHelper = getWritableDatabase();
    String where = " id = " + id + " AND oea_name = '" + user_name + "'";
    Cursor cursor = dbHelper.query(modelToTable(db.getModelName()), new String[] { "*" }, where, null, null,
            null, null);
    boolean flag = false;
    if (cursor.moveToFirst()) {
        flag = true;
    }
    cursor.close();
    dbHelper.close();
    return flag;
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

private void handleResponse() {
    Log.i(this.getClass().getName(), "in handleResponse()");
    // close progress notification
    mNotificationManager.cancel(NOTIFICATION_ID);

    String notificationMessage = getString(R.string.upload_success);

    // notification intent with result
    final Intent notificationIntent = new Intent(getBaseContext(), ImageDetails.class);

    if (mImgurResponse == null) {
        notificationMessage = getString(R.string.connection_failed);
    } else if (mImgurResponse.get("error") != null) {
        notificationMessage = getString(R.string.unknown_error) + mImgurResponse.get("error");
    } else {/*from   w w  w .  jav  a2  s. c o  m*/
        // create thumbnail
        if (mImgurResponse.get("image_hash").length() > 0) {
            createThumbnail(imageLocation);
        }

        // store result in database
        final HistoryDatabase histData = new HistoryDatabase(getBaseContext());
        final SQLiteDatabase data = histData.getWritableDatabase();

        final HashMap<String, String> dataToSave = new HashMap<String, String>();
        dataToSave.put("delete_hash", mImgurResponse.get("delete_hash"));
        dataToSave.put("image_url", mImgurResponse.get("original"));
        final Uri imageUri = Uri
                .parse(getFilesDir() + "/" + mImgurResponse.get("image_hash") + THUMBNAIL_POSTFIX);
        dataToSave.put("local_thumbnail", imageUri.toString());
        dataToSave.put("upload_time", "" + System.currentTimeMillis());

        for (final Map.Entry<String, String> entry : dataToSave.entrySet()) {
            final ContentValues content = new ContentValues();
            content.put("hash", mImgurResponse.get("image_hash"));
            content.put("key", entry.getKey());
            content.put("value", entry.getValue());
            data.insert("imgur_history", null, content);
        }

        //set intent to go to image details
        notificationIntent.putExtra("hash", mImgurResponse.get("image_hash"));
        notificationIntent.putExtra("image_url", mImgurResponse.get("original"));
        notificationIntent.putExtra("delete_hash", mImgurResponse.get("delete_hash"));
        notificationIntent.putExtra("local_thumbnail", imageUri.toString());

        data.close();
        histData.close();

        // if the main activity is already open then refresh the gridview
        sendBroadcast(new Intent(BROADCAST_ACTION));
    }

    //assemble notification
    final Notification notification = new Notification(R.drawable.icon, notificationMessage,
            System.currentTimeMillis());
    notification.setLatestEventInfo(this, getString(R.string.app_name), notificationMessage, PendingIntent
            .getActivity(getBaseContext(), 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT));
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(NOTIFICATION_ID, notification);

}

From source file:app.clirnet.com.clirnetapp.activity.LoginActivity.java

private void addVitalsIntoInvstigation() {

    String addedVitalsSugarFlag = getInsertedInvestigationVitalsFlag();
    if (addedVitalsSugarFlag == null) {
        SQLiteDatabase db = null;
        try {//from w w w  . j a v  a  2  s  . c  o m
            db = sInstance.getWritableDatabase();
            db.execSQL(
                    "insert into table_investigation(patient_id,key_visit_id,sugar,sugar_fasting) select patient_id, key_visit_id , sugar, sugar_fasting from patient_history;");

            /*Updating flag to true so wont run 2nd time */ //20-05-2017

            setInsertedInvestigationVitalsFlag();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }
}

From source file:io.vit.vitio.Managers.ConnectDatabase.java

public Course getCourse(String classNmbr) {
    Course course = new Course();
    try {/*from  ww w.j av  a2s.com*/
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.query(TABLE_COURSES, COLUMNS, KEY_CLASNBR + "=?",
                new String[] { String.valueOf(classNmbr) }, null, null, null, null);

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

        course.setCLASS_NUMBER(cursor.getString(0));
        course.setCOURSE_TITLE(cursor.getString(1));
        course.setCOURSE_SLOT(cursor.getString(2));
        course.setCOURSE_TYPE(cursor.getString(3));
        course.setCOURSE_TYPE_SHORT(cursor.getString(4));
        course.setCOURSE_LTPC(cursor.getString(5));
        course.setCOURSE_CODE(cursor.getString(6));
        course.setCOURSE_MODE(cursor.getString(7));
        course.setCOURSE_OPTION(cursor.getString(8));
        course.setCOURSE_VENUE(cursor.getString(9));
        course.setCOURSE_FACULTY(cursor.getString(10));
        course.setCOURSE_REGISTRATIONSTATUS(cursor.getString(11));
        course.setCOURSE_BILL_DATE(cursor.getString(12));
        course.setCOURSE_BILL_NUMBER(cursor.getString(13));
        course.setCOURSE_PROJECT_TITLE(cursor.getString(14));
        course.setJson(new JSONObject(cursor.getString(15)));
        course.setCOURSE_ATTENDANCE(ParseCourses.getAttendance(new JSONObject(cursor.getString(16))));
        course.setCOURSE_TIMING(ParseCourses.getTimings(new JSONArray(cursor.getString(17))));
        course.setCOURSE_MARKS(ParseCourses.getCouseMarks(new JSONObject(cursor.getString(18))));

        cursor.close();
        db.close();

    } catch (Exception e) {
        e.printStackTrace();
        SQLiteDatabase _db = this.getWritableDatabase();
        if (_db != null && _db.isOpen()) {
            _db.close();
        }
    }

    return course;
}

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/* w w  w. j  a  va2  s . co m*/
                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.spoiledmilk.ibikecph.util.DB.java

public long saveSearchHistory(HistoryData hd, HistoryData from, Context context) {
    SQLiteDatabase db = this.getWritableDatabase();
    if (db == null)
        return -1;

    String[] columns = { KEY_ID, KEY_NAME };
    long id;// www.  j av a 2s  . c  om
    Cursor cursor = db.query(TABLE_SEARCH_HISTORY, columns, KEY_NAME + " = ?", new String[] { hd.getName() },
            null, null, null, null);
    if (cursor == null || cursor.isAfterLast()) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, hd.getName());
        values.put(KEY_ADDRESS, hd.getAdress());
        values.put(KEY_START_DATE, hd.getStartDate());
        values.put(KEY_END_DATE, hd.getEndDate());
        values.put(KEY_SOURCE, hd.getSource());
        values.put(KEY_SUBSOURCE, hd.getSubSource());
        values.put(KEY_LAT, Double.valueOf(hd.getLatitude()));
        values.put(KEY_LONG, Double.valueOf(hd.getLongitude()));
        id = db.insert(TABLE_SEARCH_HISTORY, null, values);
    } else {
        cursor.moveToFirst();
        id = cursor.getInt(cursor.getColumnIndex(KEY_ID));

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

    db.close();

    if (context != null && from != null)
        postHistoryItemToServer(hd, from, context);

    return id;
}