Java Code Examples for android.database.SQLException

The following are top voted examples for showing how to use android.database.SQLException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Udhari   File: TxProvider.java   Source Code and License 7 votes vote down vote up
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = mCardsDBHelper.getWritableDatabase();

    Uri returnUri = null;
    int match = sUriMatcher.match(uri);
    switch (match) {
        case TRANSACTIONS: // Since insert and query all has same url
            long transactionId = db.insert(DatabaseContract.TABLE_TRANSACTIONS, null, values);
            if (transactionId > 0) {
                returnUri = ContentUris.withAppendedId(DatabaseContract.CONTENT_URI, transactionId);
                getContext().getContentResolver().notifyChange(uri, null);
            } else {
                throw new SQLException("Can't create ID");
            }
            break;
        default:
            throw new UnsupportedOperationException("This URI is not supported");
    }
    return returnUri;
}
 
Example 2
Project: q-mail   File: EmailProviderTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = SQLException.class) //Handle this better?
public void query_forMessagesWithAccountAndRequiredFieldsWithNoOrderBy_throwsSQLiteException() {
    Account account = Preferences.getPreferences(getContext()).newAccount();
    account.getUuid();

    Cursor cursor = getProvider().query(
            Uri.parse("content://" + EmailProvider.AUTHORITY + "/account/" + account.getUuid() + "/messages"),
            new String[] {
                    EmailProvider.MessageColumns.ID,
                    EmailProvider.MessageColumns.FOLDER_ID,
                    EmailProvider.ThreadColumns.ROOT
            },
            "",
            new String[] {},
            "");

    assertNotNull(cursor);
    assertTrue(cursor.isAfterLast());
}
 
Example 3
Project: sqlbrite-sqlcipher   File: BriteDatabaseTest.java   Source Code and License 6 votes vote down vote up
@Test public void executeInsertThrowsAndDoesNotTrigger() {
  SQLiteStatement statement = real.compileStatement("INSERT INTO " + TABLE_EMPLOYEE + " ("
      + NAME + ", " + USERNAME + ") "
      + "VALUES ('Alice Allison', 'alice')");

  db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES)
      .skip(1) // Skip initial
      .subscribe(o);

  try {
    db.executeInsert(TABLE_EMPLOYEE, statement);
    fail();
  } catch (SQLException ignored) {
  }
  o.assertNoMoreEvents();
}
 
Example 4
Project: GitHub   File: ParserConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Should try to use the legacy parser by default, which is be unable to handle the SQL script.
 */
public void testLegacyMigration() {

    try {
        Configuration configuration = new Configuration.Builder(getContext())
                .setDatabaseName("migration.db")
                .setDatabaseVersion(2)
                .create();

        DatabaseHelper helper = new DatabaseHelper(configuration);
        SQLiteDatabase db = helper.getWritableDatabase();
        helper.onUpgrade(db, 1, 2);

        fail("Should not be able to parse the SQL script.");

    } catch (SQLException e) {
        final String message = e.getMessage();

        assertNotNull(message);
        assertTrue(message.contains("syntax error"));
        assertTrue(message.contains("near \"MockMigration\""));
    }
}
 
Example 5
Project: LucaHome-AndroidApplication   File: DatabaseMenuList.java   Source Code and License 6 votes vote down vote up
public boolean Update(@NonNull LucaMenu updateEntry) throws SQLException {
    ContentValues contentValues = new ContentValues();

    contentValues.put(KEY_ROW_ID, updateEntry.GetId());
    contentValues.put(KEY_WEEKDAY, updateEntry.GetWeekday().GetEnglishDay());
    contentValues.put(KEY_DAY, String.valueOf(updateEntry.GetDate().DayOfMonth()));
    contentValues.put(KEY_MONTH, String.valueOf(updateEntry.GetDate().Month()));
    contentValues.put(KEY_YEAR, String.valueOf(updateEntry.GetDate().Year()));
    contentValues.put(KEY_TITLE, updateEntry.GetTitle());
    contentValues.put(KEY_DESCRIPTION, updateEntry.GetDescription());
    contentValues.put(KEY_IS_ON_SERVER, String.valueOf(updateEntry.GetIsOnServer()));
    contentValues.put(KEY_SERVER_ACTION, updateEntry.GetServerDbAction().toString());

    _database.update(DATABASE_TABLE, contentValues, KEY_ROW_ID + "=" + updateEntry.GetId(), null);

    return true;
}
 
Example 6
Project: PlusGram   File: userDBAdapter.java   Source Code and License 6 votes vote down vote up
public user getItm(int uid) throws SQLException {
    Cursor cursor = this.db.query(true, DATABASE_MAINTABLE, this.yek_SH_flashkart, "uid == '" + uid + "' ", null, null, null, null, null);
    user nam = new user();
    if (cursor != null) {
        cursor.moveToFirst();
        nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
        nam.setUid(cursor.getInt(cursor.getColumnIndex(KEY_UID)));
        nam.setFname(cursor.getString(cursor.getColumnIndex(KEY_FNAME)));
        nam.setLname(cursor.getString(cursor.getColumnIndex(KEY_LNAME)));
        nam.setUsername(cursor.getString(cursor.getColumnIndex(KEY_USERNAME)));
        nam.setPic(cursor.getString(cursor.getColumnIndex(KEY_PIC)));
        nam.setStatus(cursor.getString(cursor.getColumnIndex(KEY_STATUS)));
        nam.setPhone(cursor.getString(cursor.getColumnIndex(KEY_PHONE)));
        nam.setUptime(cursor.getString(cursor.getColumnIndex(KEY_UPTIME)));
        nam.setIsupdate(cursor.getInt(cursor.getColumnIndex(KEY_ISUPDATE)));
        nam.setIsspecific(cursor.getInt(cursor.getColumnIndex(KEY_ISSPECEFIC)));
        nam.setPicup(cursor.getInt(cursor.getColumnIndex(KEY_PICUP)));
        nam.setStatusup(cursor.getInt(cursor.getColumnIndex(KEY_STATUSUP)));
        nam.setPhoneup(cursor.getInt(cursor.getColumnIndex(KEY_PHONEUP)));
        nam.setIsonetime(cursor.getInt(cursor.getColumnIndex(KEY_ISONETIME)));

    }
    assert cursor != null;
    cursor.close();
    return nam;
}
 
Example 7
Project: maklib   File: ContentHandler.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
    SQLiteDatabase db = sqlHelper.getReadableDatabase();
    int uriRequest = uriMatcher.match(uri);
    Uri insertUri;
    long insertid;

    if (uriRequest == ContentContract.TASK){
        insertid = db.insert(ContentContract.TABLE, null, contentValues);
        if (insertid > 0){
            insertUri = ContentUris.withAppendedId(ContentContract.CONTENT_URI, insertid);
        } else {
            throw new SQLException("Failed to insert row into " + uri.getPath());
        }
    } else {
        throw new UnsupportedOperationException("unknown uri");
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return insertUri;
}
 
Example 8
Project: PlusGram   File: hideDBAdapter.java   Source Code and License 6 votes vote down vote up
public hideObjc getItm(int ID) throws SQLException {
    Cursor cursor = this.db.query(true, DATABASE_MAINTABLE, this.yek_SH_flashkart, "dialog_id == '" + ID + "' AND isHidden = 1", null, null, null, null, null);
    hideObjc nam = new hideObjc();
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
        nam.setDialog_id(cursor.getInt(cursor.getColumnIndex(KEY_DIALOG_ID)));
        nam.setHideCode(cursor.getInt(cursor.getColumnIndex(KEY_HIDE_CODE)));
        nam.setIsChannel(cursor.getInt(cursor.getColumnIndex(KEY_IS_CHANNEL)));
        nam.setIsGroup(cursor.getInt(cursor.getColumnIndex(KEY_IS_GROUP)));
        nam.setIsHidden(cursor.getInt(cursor.getColumnIndex(KEY_IS_HIDDEN)));

    }
    assert cursor != null;
    cursor.close();
    return nam;
}
 
Example 9
Project: YuiHatano   File: ShadowSQLiteDatabase.java   Source Code and License 6 votes vote down vote up
private void beginTransaction(SQLiteTransactionListener transactionListener, boolean exclusive) {
    acquireReference();
    try {
        //            getThreadSession().beginTransaction(
        //                    exclusive ? ShadowSQLiteSession.TRANSACTION_MODE_EXCLUSIVE :
        //                            ShadowSQLiteSession.TRANSACTION_MODE_IMMEDIATE,
        //                    transactionListener,
        //                    getThreadDefaultConnectionFlags(false /*readOnly*/), null);
        isTransaction = true;
        mConnection.setAutoCommit(false);
    } catch (java.sql.SQLException e) {
        e.printStackTrace();
    } finally {
        releaseReference();
    }
}
 
Example 10
Project: BakingApp   File: RecipesProvider.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
    int match = sUriMatcher.match(uri);
    Uri returnUri;
    switch (match) {
        case RECIPES:
            Recipe recipe = buildRecipeFromContentValues(contentValues);
            long recipeId = recipeDao.insertRecipe(recipe);
            if (recipeId > 0){
                returnUri = ContentUris.withAppendedId(RecipesContract.RecipeEntry.CONTENT_URI, recipeId);
            } else {
                throw new SQLException("Failed to insert row into " + uri);
            }
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    mContext.getContentResolver().notifyChange(uri, null);
    return returnUri;
}
 
Example 11
Project: mobile-grammar   File: AddReminderToGroupActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onClick(View view) {
    try {
        // update this group to database ....
        ArticlesDataSource mDbHelper = new ArticlesDataSource(getApplicationContext());
        mDbHelper.createDatabase();
        mDbHelper.open();
        long updatedId = mDbHelper.updateGroup(groupName, listOfIdsLessons, getIdGroupToBeUpdated());
        if (updatedId != -1) {
            //Toast.makeText(getApplicationContext(), R.string.group_has_been_saved, Toast.LENGTH_SHORT).show();
            // ... and go to activity to show it
            Intent intent = new Intent(getApplicationContext(), AllArticlesListViewActivity.class);
            intent.putExtra("group_id", getIdGroupToBeUpdated());
            intent.putExtra("group_name", groupName);
            intent.putExtra("status_what_show", ActivityArticlesStatusToShow.SHOW_ALL_GROUPS);
            startActivity(intent);
        } else {
            // throw exception
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 12
Project: mobile-grammar   File: ArticlesDataSource.java   Source Code and License 6 votes vote down vote up
/**
 * We have to options to find articles:
 * 1. Find all articles - in this case we have ids as null
 * 2. Find articles inside group - in this case we must to pass ids of group. In activity we have getIdsOfGroup() to do this.
 *
 * @param articleName name of article
 * @param ids sequence of ids of article where we need to search
 * @return Cursor
 */
public Cursor findArticles(String articleName, String ids) {
    try {
        String sql;
        if (ids == null) {
            sql = "select  _id as _id, unit_number as title, html as html from articles \n" +
                    "where unit_number like '%" + articleName + "%' order by _id ";
        } else {
            sql = "select  _id as _id, unit_number as title, html as html from articles \n" +
                    "where unit_number like '%" + articleName + "%' and _id in (" + ids + ") order by _id ";
        }

        Cursor mCur = mDb.rawQuery(sql, null);

        if (mCur != null) {
            mCur.moveToNext();
        }
        return mCur;
    } catch (SQLException mSQLException) {
        throw mSQLException;
    }
}
 
Example 13
Project: LucaHome-AndroidApplication   File: DatabaseShoppingList.java   Source Code and License 6 votes vote down vote up
public boolean Update(@NonNull ShoppingEntry updateEntry) throws SQLException {
    ContentValues contentValues = new ContentValues();

    contentValues.put(KEY_ROW_ID, updateEntry.GetId());
    contentValues.put(KEY_NAME, updateEntry.GetName());
    contentValues.put(KEY_GROUP, updateEntry.GetGroup().toString());
    contentValues.put(KEY_QUANTITY, updateEntry.GetQuantity());
    contentValues.put(KEY_UNIT, updateEntry.GetUnit());
    contentValues.put(KEY_BOUGHT, (updateEntry.GetBought() ? "1" : "0"));
    contentValues.put(KEY_IS_ON_SERVER, String.valueOf(updateEntry.GetIsOnServer()));
    contentValues.put(KEY_SERVER_ACTION, updateEntry.GetServerDbAction().toString());

    _database.update(DATABASE_TABLE, contentValues, KEY_ROW_ID + "=" + updateEntry.GetId(), null);

    return true;
}
 
Example 14
Project: androidtools   File: PTSqliteHelper.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    try {
        String sql = "CREATE TABLE " + TABLE_NAME
                + "(" + COLUMN_ID +
                " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_LEVEL +
                " INTEGER, " +
                COLUMN_CONTENT +
                " VARCHAR, " +
                COLUMN_DATE +
                " INTEGER);";
        sqLiteDatabase.execSQL(sql);
    } catch (SQLException ex) {
        Log.d("PTSqliteHelper", ex.getMessage());
        return;
    }
}
 
Example 15
Project: AndiCar   File: DB.java   Source Code and License 6 votes vote down vote up
private void upgradeDbTo310(SQLiteDatabase db, int oldVersion) throws SQLException {
    String updSql;
    if (!columnExists(db, TABLE_NAME_REFUEL, COL_NAME_REFUEL__AMOUNT)) {
        updSql = "ALTER TABLE " + TABLE_NAME_REFUEL + " ADD " + COL_NAME_REFUEL__AMOUNT + " NUMERIC NULL ";
        db.execSQL(updSql);
        updSql = "UPDATE " + TABLE_NAME_REFUEL + " SET " + COL_NAME_REFUEL__AMOUNT + " = " + COL_NAME_REFUEL__QUANTITYENTERED + " * "
                + COL_NAME_REFUEL__PRICE;
        db.execSQL(updSql);
    }
    if (!columnExists(db, TABLE_NAME_REFUEL, COL_NAME_REFUEL__AMOUNTENTERED)) {
        updSql = "ALTER TABLE " + TABLE_NAME_REFUEL + " ADD " + COL_NAME_REFUEL__AMOUNTENTERED + " NUMERIC NULL ";
        db.execSQL(updSql);
        updSql = "UPDATE " + TABLE_NAME_REFUEL + " SET " + COL_NAME_REFUEL__AMOUNTENTERED + " = " + COL_NAME_REFUEL__QUANTITYENTERED + " * "
                + COL_NAME_REFUEL__PRICEENTERED;
        db.execSQL(updSql);
    }

    upgradeDbTo330(db, oldVersion);
}
 
Example 16
Project: NoticeDog   File: InboxPersistence.java   Source Code and License 6 votes vote down vote up
public boolean deleteConversation(Conversation conversation) {
    boolean success;
    try {
        this.database.beginTransaction();
        if (this.database.delete(InboxSQLiteHelper.TABLE_MESSAGES, "_sender_user_id="
                + conversation.getSender().getId(), null) == 0) {
            throw new SQLException("Failed to delete message from DB");
        } else if (this.database.delete(InboxSQLiteHelper.TABLE_CONVERSATIONS, "_sender_user_id="
                + conversation.getSender().getId(), null) != 1) {
            throw new SQLException("Failed to delete message from DB");
        } else {
            this.database.setTransactionSuccessful();
            success = true;
            return success;
        }
    } catch (SQLException e) {
        Log.d(TAG, "Error trying to delete a message");
        success = false;
    } finally {
        this.database.endTransaction();
    }
    return success;
}
 
Example 17
Project: KBUnitTest   File: ShadowSQLiteDatabase.java   Source Code and License 6 votes vote down vote up
private void beginTransaction(SQLiteTransactionListener transactionListener, boolean exclusive) {
    acquireReference();
    try {
        //            getThreadSession().beginTransaction(
        //                    exclusive ? ShadowSQLiteSession.TRANSACTION_MODE_EXCLUSIVE :
        //                            ShadowSQLiteSession.TRANSACTION_MODE_IMMEDIATE,
        //                    transactionListener,
        //                    getThreadDefaultConnectionFlags(false /*readOnly*/), null);
        isTransaction = true;
        mConnection.setAutoCommit(false);
    } catch (java.sql.SQLException e) {
        e.printStackTrace();
    } finally {
        releaseReference();
    }
}
 
Example 18
Project: NISTGammaSearch   File: NISTDBAdapter.java   Source Code and License 6 votes vote down vote up
public Cursor getInfoFromElemTable(String[] strQuery, String strTableName)
{
    if(strQuery==null) return null;
    try
    {
        StringBuilder tempStrBuilder = new StringBuilder();
        tempStrBuilder.append("SELECT ");
        for(int i=0; i<strQuery.length-1; i++){
            tempStrBuilder.append(strQuery[i]);
            tempStrBuilder.append(", ");
        }
        tempStrBuilder.append(strQuery[strQuery.length-1]);
        tempStrBuilder.append(" FROM ");
        //tempStrBuilder.append("SELECT energy FROM ");
        tempStrBuilder.append(strTableName);
        String sql =tempStrBuilder.toString();

        Cursor mCur = mDb.rawQuery(sql, null);
        return mCur;
    }
    catch (SQLException mSQLException)
    {
        Log.e(TAG, "getTestData >>"+ mSQLException.toString());
        throw mSQLException;
    }
}
 
Example 19
Project: Quran   File: DatabaseHandler.java   Source Code and License 6 votes vote down vote up
private int getProperty(@NonNull String column) {
  int value = 1;
  if (!validDatabase()) {
    return value;
  }

  Cursor cursor = null;
  try {
    cursor = database.query(PROPERTIES_TABLE, new String[]{ COL_VALUE },
        COL_PROPERTY + "= ?", new String[]{ column }, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
      value = cursor.getInt(0);
    }
    return value;
  } catch (SQLException se) {
    return value;
  } finally {
    DatabaseUtils.closeCursor(cursor);
  }
}
 
Example 20
Project: AndiCar   File: DBAdapter.java   Source Code and License 6 votes vote down vote up
/**
 * Return a Cursor positioned at the record that matches the given rowId
 * from the given table
 *
 * @param rowId id of the record to retrieve
 * @return Cursor positioned to matching record, if found. Otherwise null.
 * @throws SQLException if the record could not be found/retrieved
 */
@Nullable
public Cursor fetchRecord(String tableName, String[] columns, long rowId) throws SQLException {
    Cursor mCursor = mDb.query(true, tableName, columns, COL_NAME_GEN_ROWID + "=" + rowId, null, null, null, null, null);
    if (mCursor != null) {
        if (mCursor.moveToFirst()) {
            return mCursor;
        }
        else {
            mCursor.close();
            return null;
        }
    }
    else {
        return null;
    }

}
 
Example 21
Project: NISTGammaSearch   File: NISTDBAdapter.java   Source Code and License 6 votes vote down vote up
public Cursor getElementName(int nInputAtomNum)
{
    try
    {
        StringBuilder tempStrBuilder = new StringBuilder();
        tempStrBuilder.append(nInputAtomNum);
        String sql ="SELECT name, density FROM elements WHERE atom_number LIKE " + tempStrBuilder.toString();

        Cursor mCur = mDb.rawQuery(sql, null);
        return mCur;
    }
    catch (SQLException mSQLException)
    {
        Log.e(TAG, "getTestData >>"+ mSQLException.toString());
        throw mSQLException;
    }
}
 
Example 22
Project: LucaHome-AndroidApplication   File: DatabaseMoneyMeterDataList.java   Source Code and License 6 votes vote down vote up
public boolean Update(@NonNull MoneyMeterData updateEntry) throws SQLException {
    ContentValues contentValues = new ContentValues();

    contentValues.put(KEY_ROW_ID, updateEntry.GetId());
    contentValues.put(KEY_TYPE_ID, String.valueOf(updateEntry.GetTypeId()));
    contentValues.put(KEY_BANK, updateEntry.GetBank());
    contentValues.put(KEY_PLAN, updateEntry.GetPlan());
    contentValues.put(KEY_AMOUNT, String.valueOf(updateEntry.GetAmount()));
    contentValues.put(KEY_UNIT, updateEntry.GetUnit());
    contentValues.put(KEY_SAVE_DATE, updateEntry.GetSaveDate().toString());
    contentValues.put(KEY_USER, updateEntry.GetUser());

    _database.update(DATABASE_TABLE, contentValues, KEY_ROW_ID + "=" + updateEntry.GetId(), null);

    return true;
}
 
Example 23
Project: KBUnitTest   File: ShadowSQLiteDatabase.java   Source Code and License 5 votes vote down vote up
private int executeSql(String sql, Object[] bindArgs) throws SQLException {
    acquireReference();
    try {
        if (ShadowDatabaseUtils.getSqlStatementType(sql) == ShadowDatabaseUtils.STATEMENT_ATTACH) {
            boolean disableWal = false;
            synchronized (mLock) {
                if (!mHasAttachedDbsLocked) {
                    mHasAttachedDbsLocked = true;
                    disableWal = true;
                }
            }
            if (disableWal) {
                disableWriteAheadLogging();
            }
        }

        ShadowSQLiteStatement statement = new ShadowSQLiteStatement(this, sql, bindArgs);
        try {
            // PRAGMA user_version = x
            if (sql.startsWith("PRAGMA") && sql.contains("=")) {
                statement.execute();
                return 1;
            }
            return statement.executeUpdateDelete();
        } finally {
            statement.close();
        }
    } finally {
        releaseReference();
    }
}
 
Example 24
Project: SimpleUILauncher   File: LauncherProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Deletes any empty folder from the DB.
 * @return Ids of deleted folders.
 */
private ArrayList<Long> deleteEmptyFolders() {
    ArrayList<Long> folderIds = new ArrayList<>();
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        // Select folders whose id do not match any container value.
        String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
                + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
                + LauncherSettings.Favorites._ID +  " NOT IN (SELECT " +
                        LauncherSettings.Favorites.CONTAINER + " FROM "
                            + Favorites.TABLE_NAME + ")";
        Cursor c = db.query(Favorites.TABLE_NAME,
                new String[] {LauncherSettings.Favorites._ID},
                selection, null, null, null, null);
        while (c.moveToNext()) {
            folderIds.add(c.getLong(0));
        }
        c.close();
        if (!folderIds.isEmpty()) {
            db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
                    LauncherSettings.Favorites._ID, folderIds), null);
        }
        db.setTransactionSuccessful();
    } catch (SQLException ex) {
        Log.e(TAG, ex.getMessage(), ex);
        folderIds.clear();
    } finally {
        db.endTransaction();
    }
    return folderIds;
}
 
Example 25
Project: PlusGram   File: hideDBAdapter.java   Source Code and License 5 votes vote down vote up
public void onCreate(SQLiteDatabase db) {
    try {
        db.execSQL(CREATE_MAINTABLE_HIDES);
    } catch (SQLException e) {
        FirebaseCrash.report(e);
        e.printStackTrace();
    }
}
 
Example 26
Project: oma-riista-android   File: DiaryDataSource.java   Source Code and License 5 votes vote down vote up
boolean insertReceivedEvent(GameHarvest event) {
    try {
        mDatabase = mDbHelper.getWritableDatabase();
        QueryConditionList whereConditions = new QueryConditionList();
        whereConditions.add(DiaryHelper.COLUMN_ID + " = " + event.mId, null);
        addCommonWhereConditions(whereConditions);

        String query = "SELECT * FROM " + DiaryHelper.TABLE_DIARY + " WHERE " + whereConditions.getWhereCondition();
        Cursor cursor = mDatabase.rawQuery(query, whereConditions.getValueArray());
        if (cursor.getCount() == 0) {
            addLocalEvent(event, true);
            return true;
        } else {
            cursor.moveToFirst();
            boolean isRemote = (cursor.getInt(cursor.getColumnIndex(DiaryHelper.COLUMN_REMOTE)) == 1);
            boolean isSent = (cursor.getInt(cursor.getColumnIndex(DiaryHelper.COLUMN_SENT)) == 1);
            int currentRev = cursor.getInt(cursor.getColumnIndex(DiaryHelper.COLUMN_REV));
            int storedFormatVersion = cursor.getInt(cursor.getColumnIndex(DiaryHelper.COLUMN_CLIENT_DATA_FORMAT));
            // Event can be replaced if server rev is newer or if it's same and the event has not been modified
            if (!isRemote || event.mRev > currentRev || (event.mClientDataFormat > storedFormatVersion && isSent) || (event.mRev == currentRev && isSent)) {
                cursor.moveToFirst();
                event.mLocalId = cursor.getInt(cursor.getColumnIndex(DiaryHelper.COLUMN_LOCALID));
                editLocalEvent(event, true);
                return true;
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 27
Project: NISTGammaSearch   File: NISTDBAdapter.java   Source Code and License 5 votes vote down vote up
public NISTDBAdapter open() throws SQLException
{
    try
    {
        mDbHelper.openDataBase();
        mDbHelper.close();
        mDb = mDbHelper.getReadableDatabase();
    }
    catch (SQLException mSQLException)
    {
        Log.e(TAG, "open >>"+ mSQLException.toString());
        throw mSQLException;
    }
    return this;
}
 
Example 28
Project: oneKey2Alarm   File: DBAdapter.java   Source Code and License 5 votes vote down vote up
public Cursor getContact(long rowId) throws SQLException  
{  
    Cursor mCursor =   
            db.query(true, DATABASE_TABLE, new String[]{ KEY_ROWID,  
                     KEY_NAME, KEY_PHONENUM}, KEY_ROWID + "=" + rowId, null, null, null, null, null);  
    if (mCursor != null)  
        mCursor.moveToFirst();  
    return mCursor;  
}
 
Example 29
Project: eyeRS   File: EyeRSDatabaseHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Method is used to create the db tables. It accepts a SQLite db object.
 *
 * @param db the acsepted SQLite object
 */
@Override
public void onCreate(SQLiteDatabase db) {

    try {
        /*
         * Creates the Item table
         */
        db.execSQL(CREATE_ITEM_TABLE_QUERY);
        Log.e("DATABASE OPERATIONS", "...Item table created!");
        /*
         * Creates the Category table
         */
        db.execSQL(CREATE_CATEGORY_TABLE_QUERY);
        Log.e("DATABASE OPERATIONS", "...Category table created!");
        /*
         * Creates the User Registration table
         */
        db.execSQL(CREATE_USER_REGISTRATION_TABLE_QUERY);
        Log.e("DATABASE OPERATIONS", "...User Registration table created!");

        insertDefaultCategoryBooks(db);
        insertDefaultCategoryClothes(db);
        insertDefaultCategoryAccessories(db);
        insertDefaultCategoryGames(db);
        insertDefaultCategoryOther(db);

        Log.e("DATABASE OPERATIONS", "...Default categories created successfully!");

    } catch (SQLException ex) {
        Log.e("DATABASE OPERATIONS", "Unable to perform default DDL & DML operations!", ex);
    }
}
 
Example 30
Project: punti-burraco   File: ScoreDB.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db)
{
    try {
        db.execSQL(DATABASE_CREATION);
    }
    catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 31
Project: KBUnitTest   File: ShadowSQLiteDatabase.java   Source Code and License 5 votes vote down vote up
/**
 * Compiles an SQL statement into a reusable pre-compiled statement object.
 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
 * statement and fill in those values with {@link SQLiteProgram#bindString}
 * and {@link SQLiteProgram#bindLong} each time you want to run the
 * statement. Statements may not return result sets larger than 1x1.
 * <p>
 * No two threads should be using the same {@link SQLiteStatement} at the same time.
 *
 * @param sql The raw SQL statement, may contain ? for unknown values to be
 *            bound later.
 * @return A pre-compiled {@link SQLiteStatement} object. Note that
 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
 */
public SQLiteStatement compileStatement(String sql) throws SQLException {
    acquireReference();
    try {
        ShadowSQLiteStatement shadowSQLiteStatement = new ShadowSQLiteStatement(this, sql, null);

        // SQLiteDatabase db, String sql, Object[] bindArgs
        //            Class[] argTypes = new Class[]{SQLiteDatabase.class, String.class, Object[].class};

        // SQLiteStatement只有 public SQLiteStatement()构造函数
        return new CGLibProxy().proxy(SQLiteStatement.class, shadowSQLiteStatement);
    } finally {
        releaseReference();
    }
}
 
Example 32
Project: Android-Copy-Database   File: DBQuery.java   Source Code and License 5 votes vote down vote up
public DBQuery open() throws SQLException {
    try {
        dbHelper.openDataBase();
        dbHelper.close();
        db = dbHelper.getReadableDatabase();
    } catch (SQLException ignored) {
    }
    return this;
}
 
Example 33
Project: YuiHatano   File: ShadowSQLiteDatabase.java   Source Code and License 5 votes vote down vote up
/**
 * Compiles an SQL statement into a reusable pre-compiled statement object.
 * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
 * statement and fill in those values with {@link SQLiteProgram#bindString}
 * and {@link SQLiteProgram#bindLong} each time you want to run the
 * statement. Statements may not return result sets larger than 1x1.
 * <p>
 * No two threads should be using the same {@link SQLiteStatement} at the same time.
 *
 * @param sql The raw SQL statement, may contain ? for unknown values to be
 *            bound later.
 * @return A pre-compiled {@link SQLiteStatement} object. Note that
 * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
 */
public SQLiteStatement compileStatement(String sql) throws SQLException {
    acquireReference();
    try {
        ShadowSQLiteStatement shadowSQLiteStatement = new ShadowSQLiteStatement(this, sql, null);

        // SQLiteDatabase db, String sql, Object[] bindArgs
        //            Class[] argTypes = new Class[]{SQLiteDatabase.class, String.class, Object[].class};

        // SQLiteStatement只有 public SQLiteStatement()构造函数
        return new CGLibProxy().proxy(SQLiteStatement.class, shadowSQLiteStatement);
    } finally {
        releaseReference();
    }
}
 
Example 34
Project: LaunchEnr   File: LauncherProvider.java   Source Code and License 5 votes vote down vote up
@Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
    db.beginTransaction();
    try {
        if (addRankColumn) {
            // Insert new column for holding rank
            db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
        }

        // Get a map for folder ID to folder width
        Cursor c = db.rawQuery("SELECT container, MAX(cellX) FROM favorites"
                + " WHERE container IN (SELECT _id FROM favorites WHERE itemType = ?)"
                + " GROUP BY container;",
                new String[] {Integer.toString(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)});

        while (c.moveToNext()) {
            db.execSQL("UPDATE favorites SET rank=cellX+(cellY*?) WHERE "
                    + "container=? AND cellX IS NOT NULL AND cellY IS NOT NULL;",
                    new Object[] {c.getLong(1) + 1, c.getLong(0)});
        }

        c.close();
        db.setTransactionSuccessful();
    } catch (SQLException ex) {
        // Old version remains, which means we wipe old data
        ex.printStackTrace();
        return false;
    } finally {
        db.endTransaction();
    }
    return true;
}
 
Example 35
Project: Monolith   File: DataProvider.java   Source Code and License 5 votes vote down vote up
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {

    final SQLiteDatabase db_g = mOpenHelper_gallery.getReadableDatabase();
    final SQLiteDatabase db_a = mOpenHelper_article.getReadableDatabase();
    final int match = sUriMatcher.match(uri);
    Uri returnUri;

    switch (match) {
        case IMAGE:
            long _id = db_g.insert(TABLE_NAME_GALLERY, null, values);
            if (_id > 0) {
                returnUri = GalleryEntry.buildGalleryUri(_id);
            } else {
                throw new SQLException("Failed to add a record into " + uri);
            }
            break;

        case ARTICLE:
            long id = db_a.insert(TABLE_NAME_ARTICLE, null, values);
            if (id > 0) {
                returnUri = ArticleEntry.buildArticleUri(id);
            } else {
                throw new SQLException("Failed to add a record into " + uri);
            }
            break;

        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    db_g.close();
    db_a.close();

    return returnUri;
}
 
Example 36
Project: orgzly-android   File: NotesClient.java   Source Code and License 5 votes vote down vote up
public static Cursor getCursorForBook(Context context, String bookName) throws SQLException {
    /* Create a query with a book name condition. */
    InternalQueryBuilder builder = new InternalQueryBuilder();
    String query = builder.build(new Query(new Condition.InBook(bookName)));

    return context.getContentResolver().query(
            ProviderContract.Notes.ContentUri.notesSearchQueried(query),
            null,
            null,
            null,
            DbNoteView.LFT); // For book view, force ordering by position only
}
 
Example 37
Project: PlusGram   File: userDBAdapter.java   Source Code and License 5 votes vote down vote up
public void onCreate(SQLiteDatabase db) {
    try {
        db.execSQL(userDBAdapter.CREATE_MAINTABLE_USER);
    } catch (SQLException e) {
        FirebaseCrash.report(e);
        e.printStackTrace();
    }
}
 
Example 38
Project: FlickLauncher   File: LauncherProvider.java   Source Code and License 5 votes vote down vote up
private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
    db.beginTransaction();
    try {
        db.execSQL("ALTER TABLE favorites ADD COLUMN "
                + columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
        db.setTransactionSuccessful();
    } catch (SQLException ex) {
        Log.e(TAG, ex.getMessage(), ex);
        return false;
    } finally {
        db.endTransaction();
    }
    return true;
}
 
Example 39
Project: Saiy-PS   File: DBCustomCommand.java   Source Code and License 5 votes vote down vote up
@Override
public void close() throws SQLException {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "close");
    }
    database.close();
}
 
Example 40
Project: natumassas-app   File: DBConnection.java   Source Code and License 5 votes vote down vote up
public void createConnection(Activity activity){
    try{
        dataOpenHelper = new DataOpenHelper(activity);

        connection = dataOpenHelper.getWritableDatabase();
    }
    catch (SQLException e) {
        AlertDialog.Builder alert = new AlertDialog.Builder(activity);
        alert.setTitle(R.string.title_erro);
        alert.setMessage(e.getMessage());
        alert.setNeutralButton("OK", null);
        alert.show();
    }
}