Example usage for android.database.sqlite SQLiteDatabase isOpen

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

Introduction

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

Prototype

public boolean isOpen() 

Source Link

Document

Returns true if the database is currently open.

Usage

From source file:com.emuneee.speeedreader.test.DatabaseUtilsTestCase.java

public void testDatabaseIsCreated() {
    SQLiteDatabase database;
    SQLiteHelper helper;/*ww w.jav a  2s.c o m*/

    helper = SQLiteHelper.getSQLiteHelper(mActivity);
    database = helper.getReadableDatabase();
    assertNotNull(database);
    assertEquals(true, database.isOpen());
    database.close();
}

From source file:com.futureplatforms.kirin.extensions.databases.DatabasesBackend.java

public void closeAll() {
    for (Map.Entry<String, SQLiteDatabase> entry : mDatabases.entrySet()) {
        SQLiteDatabase db = entry.getValue();
        if (db.isOpen()) {
            db.close();/*from   w w w  .  ja v a2  s  .  c  o  m*/
        }
    }

    // Should we really do this?
    mInFlightTransactions.clear();

    mDatabases.clear();

}

From source file:com.futureplatforms.kirin.extensions.databases.DatabasesBackend.java

@Override
public void db_openOrCreate_(String dbName, JSONObject config) {
    String txId = config.optString("txId");
    String onCreate = stringOrNull(config, "onCreateToken", null);
    String onUpdate = stringOrNull(config, "onUpdateToken", null);
    String onOpened = stringOrNull(config, "onOpenedToken", null);
    String onError = stringOrNull(config, "onErrorToken", null);
    String filename = config.optString("filename");
    int requestedVersion = config.optInt("version");

    SQLiteDatabase db = mDatabases.get(dbName);
    if (db == null || !db.isOpen()) {
        CursorFactory factory = null;/*w  w  w.  j a  v  a  2  s .  c o m*/
        OpenHelper helper = new OpenHelper(mContext, filename, factory, 1);
        db = helper.getWritableDatabase();
        mDatabases.put(dbName, db);
    }

    int existingVersion = getDatabaseVersion(dbName);
    if (existingVersion != requestedVersion) {
        DBTransaction tx = mInFlightTransactions.get(txId);
        assert tx == null;
        tx = new DBTransaction(dbName, txId, onOpened, onError, false, requestedVersion);
        mInFlightTransactions.put(txId, tx);
        if (existingVersion == -1) {
            // we need to call onCreate
            mKirinHelper.jsCallback(onCreate);
        } else {
            // we need to call onUpdate
            mKirinHelper.jsCallback(onUpdate, existingVersion, requestedVersion);
        }
        mKirinHelper.cleanupCallback(onCreate, onUpdate);

    } else {
        mKirinHelper.jsCallback(onOpened);
        mKirinHelper.cleanupCallback(onOpened, onError, onUpdate, onCreate);
    }
}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

public int getUnitUsageDbCount() {
    final SQLiteDatabase db = getReadableDatabase();
    final String[] proj = { UsageEntry._ID };
    if (!db.isOpen()) {
        return -1;
    }/*from  w  w  w .  j a va  2  s.  c o m*/
    final Cursor c = db.query(DB_USAGE_TABLE, proj, null, null, null, null, null);
    c.moveToFirst();
    final int count = c.getCount();
    c.close();
    db.close();
    return count;
}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 * Get issue picture from SQlite according to issue id
 * /*from  w  ww .  ja  va  2s  .  c  o  m*/
 * @param IssueID
 * @return
 */
public IssuePic getIssuePic(int IssueID) {
    SQLiteDatabase db = this.getReadableDatabase();
    IssuePic mIssuePic;

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cr = db.query(TABLE_IssuesPics, new String[] { KEY_IssueID, KEY_IssuePicData }, KEY_IssueID + "=?",
            new String[] { Integer.toString(IssueID) }, null, null, null, null);

    boolean ExistsRes = cr.moveToFirst();

    if (!ExistsRes) {
        mIssuePic = new IssuePic(-1, null);
    } else {

        mIssuePic = new IssuePic(cr.getInt(0), cr.getBlob(1));
    }
    cr.close();
    if (db.isOpen())
        db.close();

    return mIssuePic;
}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 *  Get Issue Thumb from SQLite table according to issue id.
 * /*from  ww w  . j a va 2 s . co  m*/
 * @param IssueID
 * @return
 */
public IssuePic getIssueThumb(int IssueID) {
    SQLiteDatabase db = this.getReadableDatabase();
    IssuePic mIssueThumb;

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cr = db.query(TABLE_IssuesThumbs, new String[] { KEY_IssueID, KEY_IssueThumbData },
            KEY_IssueID + "=?", new String[] { Integer.toString(IssueID) }, null, null, null, null);

    boolean ExistsRes = cr.moveToFirst();

    if (!ExistsRes) {
        mIssueThumb = new IssuePic(-1, null);
    } else {
        mIssueThumb = new IssuePic(cr.getInt(0), cr.getBlob(1));
    }
    cr.close();

    if (db.isOpen())
        db.close();

    return mIssueThumb;
}

From source file:com.geecko.QuickLyric.tasks.WriteToDatabaseTask.java

@Override
public Boolean doInBackground(Object... params) {
    lyricsArray = new Lyrics[params.length - 2];
    SQLiteDatabase database;
    if (params[0] instanceof Fragment) {
        fragment = (Fragment) params[0];
        mContext = fragment.getActivity();
        if (mContext == null || !(mContext instanceof MainActivity))
            cancel(true);/*w w  w  .j  ava  2  s. c  o  m*/
        database = DatabaseHelper.getInstance(mContext).getWritableDatabase();
    } else
        database = (SQLiteDatabase) params[0];
    item = (MenuItem) params[1];
    if (params[2] instanceof Lyrics[])
        lyricsArray = (Lyrics[]) params[2];
    else
        for (int i = 0; i < lyricsArray.length; i++) {
            lyricsArray[i] = (Lyrics) params[i + 2];
        }
    boolean result = true;
    String[] columns = DatabaseHelper.columns;
    if (database != null && database.isOpen()) {
        database.beginTransaction();
        try {
            for (Lyrics lyrics : lyricsArray) {
                Lyrics storedLyrics = DatabaseHelper.getInstance(mContext)
                        .get(new String[] { lyrics.getArtist(), lyrics.getTitle(), lyrics.getOriginalArtist(),
                                lyrics.getOriginalTrack() });
                if ((storedLyrics == null || (!storedLyrics.isLRC() && lyrics.isLRC()))
                        && !"Storage".equals(lyrics.getSource())) {
                    ContentValues values = new ContentValues(2);
                    values.put(columns[0], lyrics.getArtist());
                    values.put(columns[1], lyrics.getTitle());
                    values.put(columns[2], lyrics.getText());
                    values.put(columns[3], lyrics.getURL());
                    values.put(columns[4], lyrics.getSource());
                    if (lyrics.getCoverURL() != null && lyrics.getCoverURL().startsWith("http://"))
                        values.put(columns[5], lyrics.getCoverURL());
                    values.put(columns[6], lyrics.getOriginalArtist());
                    values.put(columns[7], lyrics.getOriginalTrack());
                    values.put(columns[8], lyrics.isLRC() ? 1 : 0);
                    values.put(columns[9], lyrics.getWriter());
                    values.put(columns[10], lyrics.getCopyright());
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    database.insert(DatabaseHelper.TABLE_NAME, null, values);
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = true;
                    result = true;
                } else if (mContext != null) { // if called from activity, not service
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = false;
                    result = false;
                }
                database.yieldIfContendedSafely();
            }
            database.setTransactionSuccessful();
        } finally {
            database.endTransaction();
        }
    }
    return result;
}

From source file:com.nadmm.airports.DownloadActivity.java

protected void cleanupExpiredData() {
    SQLiteDatabase catalogDb = mDbManager.getCatalogDb();

    Time now = new Time();
    now.setToNow();//  www. j av a 2s. c o  m
    String today = now.format3339(true);

    Cursor c = mDbManager.getAllFromCatalog();
    if (c.moveToFirst()) {
        do {
            // Check and delete all the expired databases
            String end = c.getString(c.getColumnIndex(Catalog.END_DATE));
            if (end.compareTo(today) < 0) {
                // This database has expired, remove it
                Integer _id = c.getInt(c.getColumnIndex(Catalog._ID));
                String dbName = c.getString(c.getColumnIndex(Catalog.DB_NAME));
                File file = new File(DatabaseManager.DATABASE_DIR, dbName);
                if (catalogDb.isOpen() && file.delete()) {
                    // Now delete the catalog entry for the file
                    catalogDb.delete(Catalog.TABLE_NAME, Catalog._ID + "=?",
                            new String[] { Integer.toString(_id) });
                }
            }
        } while (c.moveToNext());
    }
    c.close();
}

From source file:org.rapidandroid.activity.chart.ChartBroker.java

protected JSONGraphData getDateQuery(DateDisplayTypes displayType, Cursor cr, SQLiteDatabase db) {
    // TODO Auto-generated method stub
    int barCount = cr.getCount();

    if (barCount == 0) {
        db.close();/*from  ww w . j  a v  a2  s . c  o m*/
        cr.close();
    } else {
        Date[] xVals = new Date[barCount];
        int[] yVals = new int[barCount];
        cr.moveToFirst();
        int i = 0;
        do {
            xVals[i] = getDate(displayType, cr.getString(0));
            yVals[i] = cr.getInt(1);
            i++;
        } while (cr.moveToNext());

        try {
            // result.put("label", fieldToPlot.getName());
            // result.put("data", prepareData(xVals, yVals));
            // result.put("bars", getShowTrue());
            // result.put("xaxis", getXaxisOptions(xVals));
            // todo
            String legend = this.getLegendString(displayType);
            return new JSONGraphData(prepareDateHistogramData(displayType, xVals, yVals, legend),
                    loadOptionsForDateGraph(xVals, true, displayType));

        } catch (Exception ex) {

        } finally {
            if (!cr.isClosed()) {

                cr.close();
            }
            if (db.isOpen()) {
                db.close();
            }
        }
    }
    // either there was no data or something bad happened
    return new JSONGraphData(getEmptyData(), new JSONObject());
}

From source file:com.triarc.sync.SyncAdapter.java

public void updateLocalTypeData(JsonObject fromJson, SyncType type, SyncTypeCollection collection,
        final SyncResult syncResult) throws Exception {
    if (!hasTypeChanges(fromJson)) {
        Log.d(TAG, "No updates for type:" + type.getName());
        return;/*from w  w w  . j av  a2 s . c  o m*/
    }

    SQLiteDatabase db = openDatabase(collection);
    try {
        if (hasArrayValues("added", fromJson)) {
            JsonArray added = fromJson.get("added").getAsJsonArray();
            for (int index = 0; index < added.size(); index++) {
                JsonObject entity = added.get(index).getAsJsonObject();
                this.addOrUpdate(db, entity, type);
            }
        }
        if (hasArrayValues("updated", fromJson)) {
            JsonArray updated = fromJson.get("updated").getAsJsonArray();
            for (int index = 0; index < updated.size(); index++) {
                JsonObject entity = updated.get(index).getAsJsonObject();
                this.addOrUpdate(db, entity, type);
            }
        }
        if (hasArrayValues("deleted", fromJson)) {
            JsonArray deleted = fromJson.get("deleted").getAsJsonArray();
            for (int index = 0; index < deleted.size(); index++) {
                JsonElement jsonElement = deleted.get(index);
                String id = jsonElement.getAsString();
                String queryId = id;
                try {
                    int parseInt = Integer.parseInt(id);
                    jsonElement = new JsonPrimitive(parseInt);
                } catch (Exception e) {
                    queryId = "'" + id + "'";
                }
                this.deleteRow(db, queryId, type);
                deleted.set(index, jsonElement);
            }
        }
    } finally {
        if (db.isOpen()) {
            closeDb(collection.getName());
        }

    }

}