Java Code Examples for android.database.sqlite.SQLiteException

The following examples show how to use android.database.sqlite.SQLiteException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: barcodescanner-lib-aar   Source File: HistoryManager.java    License: MIT License 6 votes vote down vote up
public void trimHistory() {
  SQLiteOpenHelper helper = new DBHelper(activity);
  SQLiteDatabase db = null;
  Cursor cursor = null;
  try {
    db = helper.getWritableDatabase();      
    cursor = db.query(DBHelper.TABLE_NAME,
                      ID_COL_PROJECTION,
                      null, null, null, null,
                      DBHelper.TIMESTAMP_COL + " DESC");
    cursor.move(MAX_ITEMS);
    while (cursor.moveToNext()) {
      String id = cursor.getString(0);
      Log.i(TAG, "Deleting scan history ID " + id);
      db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + id, null);
    }
  } catch (SQLiteException sqle) {
    // We're seeing an error here when called in CaptureActivity.onCreate() in rare cases
    // and don't understand it. First theory is that it's transient so can be safely ignored.
    Log.w(TAG, sqle);
    // continue
  } finally {
    close(cursor, db);
  }
}
 
Example 2
Source Project: Instagram-Profile-Downloader   Source File: DatabaseHelper.java    License: MIT License 6 votes vote down vote up
public void insertIntoDb(String username, Bitmap image){
    SQLiteDatabase db = this.getWritableDatabase();

    if(hasObject(username, DB_TABLE))
        deleteRow(username, DB_TABLE);

    try {
        ContentValues contentValues = new ContentValues();
        contentValues.put(USERNAME, username);
        contentValues.put(IMAGE_THUMBNAIL, ZoomstaUtil.getBytes(image));
        db.insert(DB_TABLE, null, contentValues);
        db.close();

    } catch (SQLiteException e){
        e.printStackTrace();
    }

}
 
Example 3
protected static void deleteLayers(Activity activity)
{
    MainApplication app = (MainApplication) activity.getApplication();
    for (int i = app.getMap().getLayerCount() - 1; i >= 0; i--) {
        ILayer layer = app.getMap().getLayer(i);
        if (!layer.getPath().getName().equals(MainApplication.LAYER_OSM) && !layer.getPath()
                .getName()
                .equals(MainApplication.LAYER_A) && !layer.getPath()
                .getName()
                .equals(MainApplication.LAYER_B) && !layer.getPath()
                .getName()
                .equals(MainApplication.LAYER_C) && !layer.getPath()
                .getName()
                .equals(MainApplication.LAYER_TRACKS)) {
            layer.delete();
        }
    }

    try {
        ((MapContentProviderHelper) MapBase.getInstance()).getDatabase(false).execSQL("VACUUM");
    } catch (SQLiteException e) {
        e.printStackTrace();
    }
}
 
Example 4
@Override
public void fromJSON(JSONObject jsonObject)
        throws JSONException, SQLiteException
{
    super.fromJSON(jsonObject);

    mTracked = jsonObject.optBoolean(JSON_TRACKED_KEY);
    mCRS = jsonObject.optInt(GeoConstants.GEOJSON_CRS, GeoConstants.CRS_WEB_MERCATOR);
    if (jsonObject.has(JSON_NGW_VERSION_MAJOR_KEY)) {
        mNgwVersionMajor = jsonObject.getInt(JSON_NGW_VERSION_MAJOR_KEY);
    }
    if (jsonObject.has(JSON_NGW_VERSION_MINOR_KEY)) {
        mNgwVersionMinor = jsonObject.getInt(JSON_NGW_VERSION_MINOR_KEY);
    }

    setAccountName(jsonObject.optString(JSON_ACCOUNT_KEY));

    mRemoteId = jsonObject.optLong(Constants.JSON_ID_KEY);
    mSyncType = jsonObject.optInt(JSON_SYNC_TYPE_KEY, Constants.SYNC_NONE);
    mNGWLayerType = jsonObject.optInt(JSON_NGWLAYER_TYPE_KEY, Constants.LAYERTYPE_NGW_VECTOR);
    mServerWhere = jsonObject.optString(JSON_SERVERWHERE_KEY);
    mSyncDirection = jsonObject.optInt(JSON_SYNC_DIRECTION_KEY, DIRECTION_BOTH);
}
 
Example 5
Source Project: whassup   Source File: Whassup.java    License: Apache License 2.0 6 votes vote down vote up
private Cursor getCursorFromDB(final File dbFile, long since, int max) throws IOException {
    Log.d(TAG, "using DB "+dbFile);
    SQLiteDatabase db = getSqLiteDatabase(dbFile);
    String limit = null;
    String selection = null;
    String[] selectionArgs = null;
    if (since > 0) {
        selection = String.format("%s > ?", TIMESTAMP);
        selectionArgs = new String[]{String.valueOf(since)};
    }
    if (max > 0) {
        limit = String.valueOf(max);
    }
    final String orderBy = TIMESTAMP + " ASC";

    try {
        return db.query(WhatsAppMessage.TABLE, null, selection, selectionArgs, null, null, orderBy, limit);
    } catch (SQLiteException e) {
        Log.w(TAG, "error querying DB", e);
        throw new IOException("Error querying DB: "+e.getMessage());
    }
}
 
Example 6
Source Project: Storm   Source File: StormTest.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable DatabaseManager open() {

        final BuildConfig.ORM orm = getORM();

        final DatabaseManager manager = new DatabaseManager(
                getContext(),
                orm.getDbName(),
                orm.getDbVersion(),
                new Class[]{
                        StormObject.class
                }
        );

        try {
            manager.open();
        } catch (SQLiteException e) {
            Debug.e(e);
            return null;
        }

        return manager;
    }
 
Example 7
Source Project: DeviceConnect-Android   Source File: SQLiteProfile.java    License: MIT License 6 votes vote down vote up
/**
 * profilesテーブルの新規レコードで本データを追加しIDを取得する.
 * 
 * @param db データベース
 */
public void dbInsert(final SQLiteDatabase db) {
    ContentValues values = new ContentValues();
    values.put(PROFILE_NAME_FIELD, mProfileName);
    values.put(DESCRIPTION_FIELD, mDescription);
    long profileId = -1;
    try {
        profileId = db.insert(LocalOAuthOpenHelper.PROFILES_TABLE, null, values);
    } catch (SQLiteException e) {
        throw e;
    }
    if (profileId < 0) {
        throw new SQLiteException("SQLiteException - insert error.");
    }
    this.mId = profileId;
}
 
Example 8
private void startTrack() {
    // get track name date unique appendix
    String pattern = "yyyy-MM-dd--HH-mm-ss";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.getDefault());

    // insert DB row
    final long started = System.currentTimeMillis();
    String mTrackName = simpleDateFormat.format(started);
    mValues.clear();
    mValues.put(TrackLayer.FIELD_NAME, mTrackName);
    mValues.put(TrackLayer.FIELD_START, started);
    mValues.put(TrackLayer.FIELD_VISIBLE, true);
    try {
        Uri newTrack = getContentResolver().insert(mContentUriTracks, mValues);
        if (null != newTrack) {
            // save vars
            mTrackId = newTrack.getLastPathSegment();
            mSharedPreferencesTemp.edit().putString(TRACK_URI, newTrack.toString()).apply();
        }

        mIsRunning = true;
        addSplitter();
    } catch (SQLiteException ignored) {
    }
}
 
Example 9
Source Project: DeviceConnect-Android   Source File: SQLiteTokenManager.java    License: MIT License 6 votes vote down vote up
/**
 * クライアントIDとユーザー名が一致するトークンを取得する.
 * 
 * @param client クライアントID
 * @param username ユーザー名
 * @return トークン(該当なければnullを返す)
 * 
 */
public Token findToken(final Client client, final String username)  {
    if (mDb != null) {
        String selection = SQLiteToken.CLIENTID_FIELD + "=? and " 
                + SQLiteToken.USERS_USERID_FIELD + "=?";
        String[] selectionArgs = {
            client.getClientId(),
            String.valueOf(LocalOAuthOpenHelper.USERS_USER_ID)
        };
        SQLiteToken[] tokens = dbLoadTokens(mDb, selection, selectionArgs);
        if (tokens == null) {
            return null;
        } else if (tokens.length == 1) {
            return tokens[0];
        } else {
            throw new SQLiteException("アクセストークンに該当するトークンが2件以上存在しています。");
        }
    } else {
        throw new SQLiteException("DBがオープンされていません。");
    }
}
 
Example 10
Source Project: DeviceConnect-Android   Source File: LocalOAuth2Main.java    License: MIT License 6 votes vote down vote up
/**
 * (13)-2.アクセストークンを破棄して利用できないようにする(startAccessTokenListActivity()用.
 * 
 * @param tokenId トークンID
 */
public void destroyAccessToken(final long tokenId) {
    synchronized (mLockForDbAccess) {
        if (!mDb.isOpen()) {
            throw new RuntimeException("Database is not opened.");
        }

        try {
            mDb.beginTransaction();

            ((SQLiteTokenManager) mTokenManager).revokeToken(tokenId);

            mDb.setTransactionSuccessful();
        } catch (SQLiteException e) {
            throw new RuntimeException(e);
        } finally {
            mDb.endTransaction();
        }
    }
}
 
Example 11
Source Project: Twire   Source File: SubscriptionsDbHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
private ArrayList<Integer> getUsersNotToNotify(SQLiteDatabase db) throws SQLiteException {
    String query = "SELECT * FROM " + SubscriptionsDbHelper.TABLE_NAME + " WHERE " + SubscriptionsDbHelper.COLUMN_NOTIFY_WHEN_LIVE + "=" + 0 + ";";
    Cursor cursor = db.rawQuery(query, null);

    ArrayList<Integer> usersToNotify = new ArrayList<>();

    while (cursor.moveToNext()) {
        int idPosition = cursor.getColumnIndex(SubscriptionsDbHelper.COLUMN_ID);
        int userId = cursor.getInt(idPosition);

        usersToNotify.add(userId);
    }

    cursor.close();

    return usersToNotify;
}
 
Example 12
Source Project: sqlite-android   Source File: DatabaseGeneralTest.java    License: Apache License 2.0 6 votes vote down vote up
@MediumTest
@Test
public void testSchemaChange3() {
    mDatabase.execSQL("CREATE TABLE db1 (_id INTEGER PRIMARY KEY, data TEXT);");
    mDatabase.execSQL("INSERT INTO db1 (data) VALUES ('test');");
    mDatabase.execSQL("ALTER TABLE db1 ADD COLUMN blah int;");
    Cursor c = null;
    try {
        c = mDatabase.rawQuery("select blah from db1", null);
    } catch (SQLiteException e) {
        fail("unexpected exception: " + e.getMessage());
    } finally {
        if (c != null) {
            c.close();
        }
    }
}
 
Example 13
Source Project: clevertap-android-sdk   Source File: DBAdapter.java    License: MIT License 6 votes vote down vote up
synchronized long getLastUninstallTimestamp(){
    final String tName = Table.UNINSTALL_TS.getName();
    Cursor cursor = null;
    long timestamp = 0;

    try {
        final SQLiteDatabase db = dbHelper.getReadableDatabase();
        cursor = db.rawQuery("SELECT * FROM " + tName +
                " ORDER BY " + KEY_CREATED_AT + " DESC LIMIT 1",null);
        if(cursor!=null && cursor.moveToFirst()){
            timestamp = cursor.getLong(cursor.getColumnIndex(KEY_CREATED_AT));
        }
    }catch (final SQLiteException e) {
        getConfigLogger().verbose("Could not fetch records out of database " + tName + ".", e);
    } finally {
        dbHelper.close();
        if (cursor != null) {
            cursor.close();
        }
    }
    return timestamp;
}
 
Example 14
Source Project: pandora   Source File: DatabaseDriver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getTableNames(DatabaseDescriptor databaseDesc) throws SQLiteException {
    SQLiteDatabase database = openDatabase(databaseDesc);
    try {
        Cursor cursor = database.rawQuery("SELECT name FROM sqlite_master WHERE type IN (?/*, ?*/)",
                new String[]{"table"/*, "view"*/});
        try {
            List<String> tableNames = new ArrayList<>();
            while (cursor.moveToNext()) {
                tableNames.add(cursor.getString(0));
            }
            return tableNames;
        } finally {
            cursor.close();
        }
    } finally {
        database.close();
    }
}
 
Example 15
private Collection<String> getStackTrace(int logEntryId) throws SQLException {
    Collection<String> stackTrace = new ArrayList();
    SQLiteDatabase db = openDatabase();
    Cursor cursor = null;

    try {
        DefaultDBNameResolver dbNameResolver = getDbNameResolver();
        QueryBuilder qb = new QueryBuilder(dbNameResolver);
        cursor = mDatabase.rawQuery(qb.buildStackTraceQuery(logEntryId), new String[] {});
        while (cursor.moveToNext()) {
            stackTrace.add(cursor.getString(cursor.getColumnIndex(dbNameResolver.getColumnName(ColumnName.TRACE_LINE))));
        }
    } catch (SQLiteException e) {
        throw new SQLException("Cannot retrieve log entries", e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return stackTrace;
}
 
Example 16
@Override
public void putDownload(Download download) throws DatabaseIOException {
  ensureInitialized();
  ContentValues values = new ContentValues();
  values.put(COLUMN_ID, download.request.id);
  values.put(COLUMN_TYPE, download.request.type);
  values.put(COLUMN_URI, download.request.uri.toString());
  values.put(COLUMN_STREAM_KEYS, encodeStreamKeys(download.request.streamKeys));
  values.put(COLUMN_CUSTOM_CACHE_KEY, download.request.customCacheKey);
  values.put(COLUMN_DATA, download.request.data);
  values.put(COLUMN_STATE, download.state);
  values.put(COLUMN_START_TIME_MS, download.startTimeMs);
  values.put(COLUMN_UPDATE_TIME_MS, download.updateTimeMs);
  values.put(COLUMN_CONTENT_LENGTH, download.contentLength);
  values.put(COLUMN_STOP_REASON, download.stopReason);
  values.put(COLUMN_FAILURE_REASON, download.failureReason);
  values.put(COLUMN_PERCENT_DOWNLOADED, download.getPercentDownloaded());
  values.put(COLUMN_BYTES_DOWNLOADED, download.getBytesDownloaded());
  try {
    SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
    writableDatabase.replaceOrThrow(tableName, /* nullColumnHack= */ null, values);
  } catch (SQLiteException e) {
    throw new DatabaseIOException(e);
  }
}
 
Example 17
Source Project: clevertap-android-sdk   Source File: DBAdapter.java    License: MIT License 6 votes vote down vote up
/**
 * Deletes the inbox message for given messageId
 * @param messageId String messageId
 * @return boolean value based on success of operation
 */
@SuppressWarnings("UnusedReturnValue")
synchronized boolean deleteMessageForId(String messageId, String userId){
    if(messageId == null || userId == null) return false;

    final String tName = Table.INBOX_MESSAGES.getName();

    try {
        final SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(tName, _ID + " = ? AND " + USER_ID + " = ?", new String[]{messageId,userId});
        return true;
    } catch (final SQLiteException e) {
        getConfigLogger().verbose("Error removing stale records from " + tName, e);
        return false;
    } finally {
        dbHelper.close();
    }
}
 
Example 18
Source Project: letv   Source File: ChannelBaseFragment.java    License: Apache License 2.0 6 votes vote down vote up
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if (cursor != null) {
        Set<String> mBookedPrograms = new HashSet();
        while (cursor.moveToNext()) {
            try {
                int idx = cursor.getColumnIndexOrThrow(Field.MD5_ID);
                if (idx != -1) {
                    mBookedPrograms.add(cursor.getString(idx));
                }
            } catch (SQLiteException e) {
                e.printStackTrace();
                return;
            }
        }
        if ((getAdapter() instanceof ChannelDetailExpandableListAdapter) && getAdapter().getChannelLivehallView() != null) {
            getAdapter().getChannelLivehallView().setBookedPrograms(mBookedPrograms);
        }
    }
}
 
Example 19
Source Project: lbry-android   Source File: LoadTagsTask.java    License: MIT License 6 votes vote down vote up
protected List<Tag> doInBackground(Void... params) {
    List<Tag> tags = null;
    SQLiteDatabase db = null;
    try {
        if (context instanceof MainActivity) {
            db = ((MainActivity) context).getDbHelper().getReadableDatabase();
            if (db != null) {
                tags = DatabaseHelper.getTags(db);
            }
        }
    } catch (SQLiteException ex) {
        error = ex;
    }

    return tags;
}
 
Example 20
private ArrayList<Integer> getUsersNotToNotify(SQLiteDatabase db) throws SQLiteException {
	String query = "SELECT * FROM " + SubscriptionsDbHelper.TABLE_NAME + " WHERE " + SubscriptionsDbHelper.COLUMN_NOTIFY_WHEN_LIVE + "=" + 0 + ";";
	Cursor cursor = db.rawQuery(query, null);

	ArrayList<Integer> usersToNotify = new ArrayList<>();

	while(cursor.moveToNext()) {
		int idPosition = cursor.getColumnIndex(SubscriptionsDbHelper.COLUMN_ID);
		int userId = cursor.getInt(idPosition);

		usersToNotify.add(userId);
	}

	cursor.close();

	return usersToNotify;
}
 
Example 21
Source Project: DeviceConnect-Android   Source File: SQLiteClientManager.java    License: MIT License 6 votes vote down vote up
/**
 * サービスIDをキーにDB検索し該当するクライアントを返す.
 * @param serviceId サービスID
 * @return  not null: サービスIDが一致するクライアント / null: サービスIDが一致するクライアント無し
 */
public Client findByServiceId(final String serviceId) {
    if (mDb != null) {
        Bundle where = new Bundle();
        where.putString(SQLiteClient.DATA_TYPE_STRING + "," + SQLiteClient.DEVICEID_FIELD, serviceId);
        Client[] clients = dbLoadClients(mDb, where);
        if (clients == null || clients.length == 0) {
            return null;
        } else if (clients.length == 1) {
            return clients[0];
        } else {
            throw new SQLiteException("クライアントIDが2件以上のクライアントデータに設定されています。");
        }
        
    } else {
        throw new SQLiteException("DBがオープンされていません。");
    }
}
 
Example 22
@Override
public void onUpgrade(final SQLiteDatabase sqLiteDatabase,
                      final int oldv, final int newv) {
    if (oldv != newv) {

        switch(oldv) {
            case 20: {
                //Add the groupId field to the items:
                try {
                    sqLiteDatabase.execSQL("ALTER TABLE " + TABLE_NAME_ITEMS + " ADD COLUMN "
                            + ItemsDbColumns.GROUP_ID + " TEXT;");
                } catch( final SQLiteException ex) {
                    Log.error("onUpgrade: ALTER TABLE ADD COLUMN failed", ex);
                    //Fall through to the default case to recreate the tables completely.
                }
                break;
            }

            default: {
                dropTable(sqLiteDatabase, TABLE_NAME_ITEMS);
                dropTable(sqLiteDatabase, TABLE_NAME_FILES);
                dropTable(sqLiteDatabase, TABLE_NAME_CLASSIFICATION_ANSWERS);
                dropTable(sqLiteDatabase, TABLE_NAME_CLASSIFICATION_CHECKBOXES);

                createTable(sqLiteDatabase);
                break;
            }
        }
    }
}
 
Example 23
/**
 * 数据库表不存在异常
 */
private void tableException(SQLiteException sqLiteException) {
    if (sqLiteException != null && sqLiteException.getMessage() != null) {
        if (sqLiteException.getMessage().contains("no such table")) {
            dbReset();
        }
    }
}
 
Example 24
Source Project: LitePal   Source File: UpdateUsingUpdateMethodTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateWithStaticUpdateButWrongClass() {
	ContentValues values = new ContentValues();
	values.put("TEACHERNAME", "Toy");
	try {
           LitePal.update(Object.class, values, teacher.getId());
	} catch (SQLiteException e) {
	}
}
 
Example 25
Source Project: AndroidTrainingCode   Source File: DataProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Updates one or more rows in a table.
 * @see android.content.ContentProvider#update(Uri, ContentValues, String, String[])
 * @param uri The content URI for the table
 * @param values The values to use to update the row or rows. You only need to specify column
 * names for the columns you want to change. To clear the contents of a column, specify the
 * column name and NULL for its value.
 * @param selection An SQL WHERE clause (without the WHERE keyword) specifying the rows to
 * update. Use "?" to mark places that should be substituted by values in selectionArgs.
 * @param selectionArgs An array of values that are mapped in order to each "?" in selection.
 * If no "?" are used, set this to NULL.
 *
 * @return int The number of rows updated.
 */
@Override
public int update(Uri uri, ContentValues values, String selection,
        String[] selectionArgs) {

    // Decodes the content URI and choose which insert to use
    switch (sUriMatcher.match(uri)) {

        // A picture URL content URI
        case URL_DATE_QUERY:

            // Creats a new writeable database or retrieves a cached one
            SQLiteDatabase localSQLiteDatabase = mHelper.getWritableDatabase();

            // Updates the table
            int rows = localSQLiteDatabase.update(
                    DataProviderContract.DATE_TABLE_NAME,
                    values,
                    selection,
                    selectionArgs);

            // If the update succeeded, notify a change and return the number of updated rows.
            if (0 != rows) {
                getContext().getContentResolver().notifyChange(uri, null);
                return rows;
            } else {

                throw new SQLiteException("Update error:" + uri);
            }

        case IMAGE_URL_QUERY:

            throw new IllegalArgumentException("Update: Invalid URI: " + uri);
    }

    return -1;
}
 
Example 26
Source Project: MediaSDK   Source File: DefaultDownloadIndex.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void removeDownload(String id) throws DatabaseIOException {
  ensureInitialized();
  try {
    databaseProvider.getWritableDatabase().delete(tableName, WHERE_ID_EQUALS, new String[] {id});
  } catch (SQLiteException e) {
    throw new DatabaseIOException(e);
  }
}
 
Example 27
Source Project: NexusData   Source File: SQLiteDatabaseHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create and/or open a database.  This will be the same object returned by
 * {@link #getWritableDatabase} unless some problem, such as a full disk,
 * requires the database to be opened read-only.  In that case, a read-only
 * database object will be returned.  If the problem is fixed, a future call
 * to {@link #getWritableDatabase} may succeed, in which case the read-only
 * database object will be closed and the read/write object will be returned
 * in the future.
 *
 * <p class="caution">Like {@link #getWritableDatabase}, this method may
 * take a long time to return, so you should not call it from the
 * application main thread, including from
 * {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
 *
 * @throws SQLiteException if the database cannot be opened
 * @return a database object valid until {@link #getWritableDatabase}
 *     or {@link #close} is called.
 */
public synchronized SQLiteDatabase getReadableDatabase() {
    if (mDatabase != null && mDatabase.isOpen()) {
        return mDatabase;  // The database is already open for business
    }

    if (mIsInitializing) {
        throw new IllegalStateException("getReadableDatabase called recursively");
    }

    try {
        return getWritableDatabase();
    } catch (SQLiteException e) {
        if (mPath.getName() == null) throw e;  // Can't open a temp database read-only!
        LOG.warn("Couldn't open " + mPath.getName() + " for writing (will try read-only):", e);
    }

    SQLiteDatabase db = null;
    try {
        mIsInitializing = true;
        db = SQLiteDatabase.openDatabase(mPath.toString(), mFactory, SQLiteDatabase.OPEN_READONLY);
        if (db.getVersion() != mNewVersion) {
            throw new SQLiteException("Can't upgrade read-only database from version " +
                    db.getVersion() + " to " + mNewVersion + ": " + mPath);
        }

        onOpen(db);
        LOG.warn("Opened " + mPath.getName() + " in read-only mode");
        mDatabase = db;
        return mDatabase;
    } finally {
        mIsInitializing = false;
        if (db != null && db != mDatabase) db.close();
    }
}
 
Example 28
Source Project: clevertap-android-sdk   Source File: DBAdapter.java    License: MIT License 5 votes vote down vote up
/**
 * Adds a JSON string to the DB.
 *
 * @param obj   the JSON to record
 * @param table the table to insert into
 * @return the number of rows in the table, or DB_OUT_OF_MEMORY_ERROR/DB_UPDATE_ERROR
 */
synchronized int storeObject(JSONObject obj, Table table) {
    if (!this.belowMemThreshold()) {
        Logger.v("There is not enough space left on the device to store data, data discarded");
        return DB_OUT_OF_MEMORY_ERROR;
    }

    final String tableName = table.getName();

    Cursor cursor = null;
    int count = DB_UPDATE_ERROR;

    try {
        final SQLiteDatabase db = dbHelper.getWritableDatabase();

        final ContentValues cv = new ContentValues();
        cv.put(KEY_DATA, obj.toString());
        cv.put(KEY_CREATED_AT, System.currentTimeMillis());
        db.insert(tableName, null, cv);
        cursor = db.rawQuery("SELECT COUNT(*) FROM " + tableName, null);
        cursor.moveToFirst();
        count = cursor.getInt(0);
    } catch (final SQLiteException e) {
        getConfigLogger().verbose("Error adding data to table " + tableName + " Recreating DB");

        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
        dbHelper.deleteDatabase();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
        dbHelper.close();
    }
    return count;
}
 
Example 29
Source Project: OpenXiaomiScale   Source File: Database.java    License: Apache License 2.0 5 votes vote down vote up
public void insertElement (WeightDBElement element)
{
	Log.d("Database", "Insert element called!");

	SQLiteDatabase database = null;

	try
	{
		database = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);

		database.setForeignKeyConstraintsEnabled(true);

		database.execSQL(
				"INSERT INTO " + WEIGHT_TABLE_NAME + " VALUES (" +
						element.unixTime + "," +
						element.weight + "," +
						element.weightUnit + "," +
						element.userID + ")"
		);
	}
	catch (SQLiteException e)
	{
		// Unhandled exception!
		Log.d("Database", "Exception in inserting weight element in database");
		e.printStackTrace();
		System.exit(-1);
	}
	finally
	{
		if ( database != null )
			database.close();
	}
}
 
Example 30
Source Project: sqlite-android   Source File: SQLiteConnection.java    License: Apache License 2.0 5 votes vote down vote up
static SQLiteConnection open(SQLiteConnectionPool pool,
        SQLiteDatabaseConfiguration configuration,
        int connectionId, boolean primaryConnection) {
    SQLiteConnection connection = new SQLiteConnection(pool, configuration,
            connectionId, primaryConnection);
    try {
        connection.open();
        return connection;
    } catch (SQLiteException ex) {
        connection.dispose(false);
        throw ex;
    }
}