Java Code Examples for android.database.sqlite.SQLiteException

The following are top voted examples for showing how to use android.database.sqlite.SQLiteException. 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: PeSanKita-android   File: ApnDatabase.java   Source Code and License 10 votes vote down vote up
private ApnDatabase(final Context context) throws IOException {
  this.context = context;

  File dbFile = context.getDatabasePath(DATABASE_NAME);

  if (!dbFile.getParentFile().exists() && !dbFile.getParentFile().mkdir()) {
    throw new IOException("couldn't make databases directory");
  }

  Util.copy(context.getAssets().open(ASSET_PATH, AssetManager.ACCESS_STREAMING),
            new FileOutputStream(dbFile));

  try {
    this.db = SQLiteDatabase.openDatabase(context.getDatabasePath(DATABASE_NAME).getPath(),
                                          null,
                                          SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
  } catch (SQLiteException e) {
    throw new IOException(e);
  }
}
 
Example 2
Project: AIMSICDL   File: AIMSICDDbAdapter.java   Source Code and License 7 votes vote down vote up
/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 *
 * ToDo: NOTE:  This is a dumb check, as it currently only tries to open it.
 *              It may be other reasons why it can't be opened even if it already exists.
 *
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;
    try {
        Log.i(TAG, mTAG + "Checking if DB exists...");
        checkDB = SQLiteDatabase.openDatabase(mDatabasePath, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        Log.i(TAG, mTAG + "SQL Exception! Database can\'t be opened: " + e);
        //Log.i(TAG, mTAG + "Database not yet created: " + e);
    }

    if (checkDB != null) {
        checkDB.close();
        Log.i(TAG, mTAG + "OK (found)");
        return true;
    }
    Log.i(TAG, mTAG + "Database probably not yet created.");
    return false;
}
 
Example 3
Project: q-mail   File: MigrationTo45.java   Source Code and License 6 votes vote down vote up
public static void changeThreadingIndexes(SQLiteDatabase db) {
    try {
        db.execSQL("DROP INDEX IF EXISTS msg_empty");
        db.execSQL("CREATE INDEX IF NOT EXISTS msg_empty ON messages (empty)");

        db.execSQL("DROP INDEX IF EXISTS msg_thread_root");
        db.execSQL("CREATE INDEX IF NOT EXISTS msg_thread_root ON messages (thread_root)");

        db.execSQL("DROP INDEX IF EXISTS msg_thread_parent");
        db.execSQL("CREATE INDEX IF NOT EXISTS msg_thread_parent ON messages (thread_parent)");
    } catch (SQLiteException e) {
        if (!e.getMessage().startsWith("duplicate column name:")) {
            throw e;
        }
    }
}
 
Example 4
Project: sealtalk-android-master   File: RongDatabaseDriver.java   Source Code and License 6 votes vote down vote up
public Database.ExecuteSQLResponse executeSQL(String databaseName, String query, ExecuteResultHandler<Database.ExecuteSQLResponse> handler)
        throws SQLiteException {
    Util.throwIfNull(query);
    Util.throwIfNull(handler);
    SQLiteDatabase database = openDatabase(databaseName);
    try {
        String firstWordUpperCase = getFirstWord(query).toUpperCase();
        switch (firstWordUpperCase) {
            case "UPDATE":
            case "DELETE":
                return executeUpdateDelete(database, query, handler);
            case "INSERT":
                return executeInsert(database, query, handler);
            case "SELECT":
            case "PRAGMA":
            case "EXPLAIN":
                return executeSelect(database, query, handler);
            default:
                return executeRawQuery(database, query, handler);
        }
    } finally {
        database.close();
    }
}
 
Example 5
Project: q-mail   File: LockableDatabase.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @throws UnavailableStorageException
 */
private void openOrCreateDataspace() throws UnavailableStorageException {

    lockWrite();
    try {
        final File databaseFile = prepareStorage(mStorageProviderId);
        try {
            doOpenOrCreateDb(databaseFile);
        } catch (SQLiteException e) {
            // TODO handle this error in a better way!
            Timber.w(e, "Unable to open DB %s - removing file and retrying", databaseFile);
            if (databaseFile.exists() && !databaseFile.delete()) {
                Timber.d("Failed to remove %s that couldn't be opened", databaseFile);
            }
            doOpenOrCreateDb(databaseFile);
        }
        if (mDb.getVersion() != mSchemaDefinition.getVersion()) {
            mSchemaDefinition.doDbUpgrade(mDb);
        }
    } finally {
        unlockWrite();
    }
}
 
Example 6
Project: justintrain-client-android   File: SQLiteAssetHelper.java   Source Code and License 6 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()}.
 *
 * @return a database object valid until {@link #getWritableDatabase}
 * or {@link #close} is called.
 * @throws SQLiteException if the database cannot be opened
 */
@Override
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 (mName == null) throw e;  // Can't open a temp database read-only!
        Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
    }

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

        onOpen(db);
        Log.w(TAG, "Opened " + mName + " in read-only mode");
        mDatabase = db;
        return mDatabase;
    } finally {
        mIsInitializing = false;
        if (db != null && db != mDatabase) db.close();
    }
}
 
Example 7
Project: justintrain-client-android   File: SQLiteAssetHelper.java   Source Code and License 6 votes vote down vote up
private SQLiteDatabase returnDatabase() {
    try {
        SQLiteDatabase db = SQLiteDatabase.openDatabase(mDatabasePath + "/" + mName, mFactory, SQLiteDatabase.OPEN_READWRITE);
        Log.i(TAG, "successfully opened database " + mName);
        return db;
    } catch (SQLiteException e) {
        Log.w(TAG, "could not open database " + mName + " - " + e.getMessage());
        return null;
    }
}
 
Example 8
Project: youkes_browser   File: BrowserActivity.java   Source Code and License 6 votes vote down vote up
public boolean getSystemBrowser() {
	Cursor c = null;
	String[] columns = new String[] { "url", "title" };
	boolean browserFlag;
	try {

		//Uri bookmarks = Browser.BOOKMARKS_URI;
		//c = getContentResolver().query(bookmarks, columns, null, null, null);
	} catch (SQLiteException | IllegalStateException | NullPointerException e) {
		e.printStackTrace();
	}

	if (c != null) {
		Log.d("Browser", "System Browser Available");
		browserFlag = true;
	} else {
		Log.e("Browser", "System Browser Unavailable");
		browserFlag = false;
	}
	if (c != null) {
		c.close();
	}
	mPreferences.setSystemBrowserPresent(browserFlag);
	return browserFlag;
}
 
Example 9
Project: yyox   File: KF5SDKtoHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @throws SQLiteException
 */
public void openDatabase() throws SQLiteException {

    openHelper = new DBOpenHelper(context, MD5Utils.GetMD5Code("kf5_ticket_" + SPUtils.getUserId()) + ".db", null, VERSION);
    try {
        db = openHelper.getWritableDatabase();
    } catch (SQLiteException e) {
        e.printStackTrace();
        db = openHelper.getReadableDatabase();
    }
    boolean isTableExit = tableIsExist(openHelper, DB_TABLE);
    if (!isTableExit) {
        db.execSQL(DB_CREATE);
    }

}
 
Example 10
Project: sealtalk-android-master   File: RongDatabaseDriver.java   Source Code and License 6 votes vote down vote up
public List<String> getTableNames(String databaseName)
        throws SQLiteException {
    SQLiteDatabase database = openDatabase(databaseName);
    try {
        Cursor cursor = database.rawQuery("SELECT name FROM sqlite_master WHERE type IN (?, ?)",
                new String[]{"table", "view"});
        try {
            List<String> tableNames = new ArrayList<String>();
            while (cursor.moveToNext()) {
                tableNames.add(cursor.getString(0));
            }
            return tableNames;
        } finally {
            cursor.close();
        }
    } finally {
        database.close();
    }
}
 
Example 11
Project: MyCalendar   File: DBHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @param isGetAll   true if want to get all subject
 * @param teacher_id Integer
 * @return {@link ArrayList<Subject>}
 * @throws NullObjectException if connect to database fail or day_start after day_end
 */
public ArrayList<Subject> getSubjectList(Boolean isGetAll, @Nonnegative Integer teacher_id) throws NullObjectException {
    SQLiteDatabase db;
    try {
        db = this.getReadableDatabase();
    } catch (SQLiteException e) {
        Log.d(TAG, "getSubjectList error: " + e.toString());
        throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL));
    }

    String query;
    if (isGetAll) {
        query = "SELECT * FROM " + TABLE_SUBJECTS;
    } else if (teacher_id != null) {
        query = "SELECT * FROM " + TABLE_SUBJECTS + " WHERE " + Teacher_ID + " = " + teacher_id;
    } else {
        return new ArrayList<>();
    }
    return getSubjectListByQuery(query, db);
}
 
Example 12
Project: MyCalendar   File: DBHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @param subject_id   Integer
 * @param subject_name String
 * @return Subject
 * @throws NullObjectException if connect to database fail or not found subject
 */
public Subject getSubject(@Nonnegative @Nullable Integer subject_id, @Nullable String subject_name) throws NullObjectException {
    SQLiteDatabase db;
    try {
        db = this.getReadableDatabase();
    } catch (SQLiteException e) {
        Log.d(TAG, "getSubject error:" + e.toString());
        throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL));
    }

    String query;
    if (subject_id != null) {
        query = "SELECT * FROM " + TABLE_SUBJECTS + " WHERE " + Subjects_ID + " = " + subject_id;
    } else if (subject_name != null) {
        query = "SELECT * FROM " + TABLE_SUBJECTS + " WHERE " + Subjects_Name + " = '" + subject_name + "'";
    } else {
        Log.d(TAG, "getSubject error: Not found subject");
        throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.NOT_FOUND_SUBJECT));
    }
    return getSubjectByQuery(query, db);
}
 
Example 13
Project: MyCalendar   File: DBHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Delete a subject
 *
 * @param subject_id subject id
 * @return DATABASE_CODE
 */
public DATABASE_CODE deleteSubject(@Nonnegative int subject_id) {
    SQLiteDatabase db;
    try {
        db = this.getWritableDatabase();
    } catch (SQLiteException e) {
        Log.d(TAG, "deleteSubject error: " + e.toString());
        return DATABASE_CODE.CONNECT_FAIL;
    }

    String whereClause = Subjects_ID + " = " + subject_id;

    if (db.delete(TABLE_SUBJECTS, whereClause, null) != 0) {
        Log.d(TAG, "deleteSubject success");
        return DATABASE_CODE.DELETE_SUBJECT_SUCCESS;
    }
    Log.d(TAG, "deleteSubject error");
    return DATABASE_CODE.DELETE_SUBJECT_FAIL;
}
 
Example 14
Project: MyCalendar   File: DBHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @param repeat_id   Integer
 * @param repeat_name String
 * @return Repeat
 * @throws NullObjectException if connect to database fail or not found repeat
 */
public Repeat getRepeat(@Nonnegative Integer repeat_id, String repeat_name) throws NullObjectException {
    SQLiteDatabase db;
    try {
        db = this.getReadableDatabase();
    } catch (SQLiteException e) {
        Log.d(TAG, "getRepeat error: " + e.toString());
        throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL));
    }
    String query;
    if (repeat_id != null) {
        query = "SELECT *  FROM " + TABLE_REPEAT + " WHERE " + Repeat_ID + " = " + repeat_id;
    } else if (repeat_name != null) {
        query = "SELECT *  FROM " + TABLE_REPEAT + " WHERE " + Repeat_Name + " = '" + repeat_name + "'";
    } else {
        Log.d(TAG, "getRepeat error: Not found repeat");
        throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.NOT_FOUND_REPEAT));
    }
    return getRepeatByQuery(query, db);
}
 
Example 15
Project: MyCalendar   File: DBHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @param subject_id Integer
 * @return {@link ArrayList<WeekLesson>}
 * @throws NullObjectException if connect database fail or day_start after day_end
 */
public ArrayList<WeekLesson> getWeekLessonList(Integer subject_id) throws NullObjectException {
    SQLiteDatabase db;
    try {
        db = this.getReadableDatabase();
    } catch (SQLiteException e) {
        Log.d(TAG, "getWeekLessonList error: " + e.toString());
        throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL));
    }

    String query;
    if (subject_id != null) {
        query = "SELECT * FROM " + TABLE_WEEK_LESSON + " WHERE " + Subjects_ID + " = " + subject_id;
    } else {
        query = "SELECT * FROM " + TABLE_WEEK_LESSON;
    }
    return getWeekLessonListByQuery(query, db);
}
 
Example 16
Project: KBUnitTest   File: ShadowDatabaseUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Prints the contents of a Cursor's current row to a StringBuilder.
 *
 * @param cursor the cursor to print
 * @param sb     the StringBuilder to print to
 */
public static void dumpCurrentRow(Cursor cursor, StringBuilder sb) {
    String[] cols = cursor.getColumnNames();
    sb.append("" + cursor.getPosition() + " {\n");
    int length = cols.length;
    for (int i = 0; i < length; i++) {
        String value;
        try {
            value = cursor.getString(i);
        } catch (SQLiteException e) {
            // assume that if the getString threw this exception then the column is not
            // representable by a string, e.g. it is a BLOB.
            value = "<unprintable>";
        }
        sb.append("   " + cols[i] + '=' + value + "\n");
    }
    sb.append("}\n");
}
 
Example 17
Project: YuiHatano   File: ShadowDatabaseUtils.java   Source Code and License 6 votes vote down vote up
private static final void readExceptionFromParcel(Parcel reply, String msg, int code) {
    switch (code) {
        case 2:
            throw new IllegalArgumentException(msg);
        case 3:
            throw new UnsupportedOperationException(msg);
        case 4:
            throw new SQLiteAbortException(msg);
        case 5:
            throw new SQLiteConstraintException(msg);
        case 6:
            throw new SQLiteDatabaseCorruptException(msg);
        case 7:
            throw new SQLiteFullException(msg);
        case 8:
            throw new SQLiteDiskIOException(msg);
        case 9:
            throw new SQLiteException(msg);
        case 11:
            throw new OperationCanceledException(msg);
        default:
            reply.readException(code, msg);
    }
}
 
Example 18
Project: MyCalendar   File: DBHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @param location_id   Integer
 * @param location_name Integer
 * @return Location
 * @throws NullObjectException if connect to database fail or not found location
 */
public Location getLocation(@Nonnegative Integer location_id, String location_name) throws NullObjectException {
    SQLiteDatabase db;
    try {
        db = this.getReadableDatabase();
    } catch (SQLiteException e) {
        Log.d(TAG, "getLocation error: " + e.toString());
        throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.CONNECT_FAIL));
    }

    String selectQuery;
    if (location_id != null) {
        selectQuery = "SELECT *  FROM " + TABLE_LOCATION + " WHERE " + Location_ID + " = " + location_id;
    } else if (location_name != null) {
        selectQuery = "SELECT *  FROM " + TABLE_LOCATION + " WHERE " + Location_Name + " = '" + location_name + "'";
    } else {
        Log.d(TAG, "getLocation error: Not found location");
        throw new NullObjectException(mDBStringHelper.getDBString(DATABASE_CODE.NOT_FOUND_LOCATION));
    }
    return getLocationByQuery(selectQuery, db);
}
 
Example 19
Project: MyCalendar   File: DBHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @param location_id location_id
 * @return {@link DATABASE_CODE#CONNECT_FAIL},{@link DATABASE_CODE#DELETE_LOCATION_SUCCESS},{@link DATABASE_CODE#DELETE_LOCATION_FAIL}
 */
public DATABASE_CODE deleteLocation(@Nonnegative int location_id) {
    SQLiteDatabase db;
    try {
        db = this.getWritableDatabase();
    } catch (SQLiteException e) {
        Log.d(TAG, "deleteLocation error: " + e.toString());
        return DATABASE_CODE.CONNECT_FAIL;
    }

    String whereClause = Location_ID + " = " + location_id;

    //Deleting a record
    if (db.delete(TABLE_LOCATION, whereClause, null) != 0) {
        Log.d(TAG, "deleteLocation success");
        return DATABASE_CODE.DELETE_LOCATION_SUCCESS;
    }
    Log.d(TAG, "deleteLocation error");
    return DATABASE_CODE.DELETE_LOCATION_FAIL;
}
 
Example 20
Project: jackknife   File: Transaction.java   Source Code and License 6 votes vote down vote up
public static boolean execute(Worker worker) {
    SQLiteDatabase db = Orm.getDatabase();
    db.beginTransaction();
    try {
        boolean isOk = worker.doTransition(db);
        if (isOk) {
            db.setTransactionSuccessful();
        }
        return isOk;
    } catch(SQLiteException e) {
        e.printStackTrace();
    } finally {
        db.endTransaction();
    }
    return false;
}
 
Example 21
Project: MyCalendar   File: DBHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @param day_lesson_id day_lesson_id
 * @return {@link DATABASE_CODE#CONNECT_FAIL}, {@link DATABASE_CODE#DELETE_DAY_LESSON_SUCCESS}
 * ,{@link DATABASE_CODE#DELETE_DAY_LESSON_FAIL}
 */
public DATABASE_CODE deleteDayLesson(int day_lesson_id) {
    SQLiteDatabase db;
    try {
        db = this.getWritableDatabase();
    } catch (SQLiteException e) {
        Log.d(TAG, "deleteDayLesson error: " + e.toString());
        return DATABASE_CODE.CONNECT_FAIL;
    }

    String whereClause = DayLesson_ID + " = " + day_lesson_id;

    if (db.delete(TABLE_DAY_LESSON, whereClause, null) != 0) {
        Log.d(TAG, "deleteDayLesson success");
        return DATABASE_CODE.DELETE_DAY_LESSON_SUCCESS;
    }

    Log.d(TAG, "deleteDayLesson error");
    return DATABASE_CODE.DELETE_DAY_LESSON_FAIL;
}
 
Example 22
Project: browser   File: BrowserActivity.java   Source Code and License 6 votes vote down vote up
public boolean getSystemBrowser() {
	Cursor c = null;
	String[] columns = new String[] { "url", "title" };
	boolean browserFlag;
	try {

		//Uri bookmarks = Browser.BOOKMARKS_URI;
		//c = getContentResolver().query(bookmarks, columns, null, null, null);
	} catch (SQLiteException | IllegalStateException | NullPointerException e) {
		e.printStackTrace();
	}

	if (c != null) {
		Log.d("Browser", "System Browser Available");
		browserFlag = true;
	} else {
		Log.e("Browser", "System Browser Unavailable");
		browserFlag = false;
	}
	if (c != null) {
		c.close();
	}
	mPreferences.setSystemBrowserPresent(browserFlag);
	return browserFlag;
}
 
Example 23
Project: gitio   File: SeanDBHelper.java   Source Code and License 6 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
        case 0:
            try {
                db.execSQL("CREATE TABLE main.history " +
                        "(_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                        "url TEXT NOT NULL, " +
                        "code TEXT NOT NULL," +
                        "date INTEGER NOT NULL)");

                db.execSQL("CREATE TABLE main.params " +
                        "(_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                        "kind TEXT NOT NULL, " +
                        "value TEXT)");
            } catch (SQLiteException e) {
                Log.e("db", "onUpgrade", e);
            }
    }
}
 
Example 24
Project: Pocket-Plays-for-Twitch   File: SubscriptionsDbHelper.java   Source Code and License 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 25
Project: KBUnitTest   File: ShadowDatabaseUtils.java   Source Code and License 6 votes vote down vote up
private static final void readExceptionFromParcel(Parcel reply, String msg, int code) {
    switch (code) {
        case 2:
            throw new IllegalArgumentException(msg);
        case 3:
            throw new UnsupportedOperationException(msg);
        case 4:
            throw new SQLiteAbortException(msg);
        case 5:
            throw new SQLiteConstraintException(msg);
        case 6:
            throw new SQLiteDatabaseCorruptException(msg);
        case 7:
            throw new SQLiteFullException(msg);
        case 8:
            throw new SQLiteDiskIOException(msg);
        case 9:
            throw new SQLiteException(msg);
        case 11:
            throw new OperationCanceledException(msg);
        default:
            reply.readException(code, msg);
    }
}
 
Example 26
Project: weex-3d-map   File: HistoryManager.java   Source Code and 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 27
Project: letv   File: LiveBookFragment.java   Source Code and License 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 (this.mAdapter != null) {
            this.mAdapter.setBookedPrograms(mBookedPrograms);
        }
    }
}
 
Example 28
Project: nifi-android-s2s   File: SQLiteDataPacketIterator.java   Source Code and License 6 votes vote down vote up
public void transactionFailed() throws SQLiteIOException {
    close();
    SQLiteDatabase writableDatabase = siteToSiteDB.getWritableDatabase();
    writableDatabase.beginTransaction();
    try {
        ContentValues contentValues = new ContentValues();
        contentValues.putNull(DATA_PACKET_QUEUE_TRANSACTION_COLUMN);
        writableDatabase.update(DATA_PACKET_QUEUE_TABLE_NAME, contentValues, DATA_PACKET_QUEUE_TRANSACTION_COLUMN + " = ?", new String[] {Long.toString(transactionId)});
        writableDatabase.delete(DATA_PACKET_QUEUE_TRANSACTIONS_TABLE_NAME, DATA_PACKET_QUEUE_TRANSACTION_COLUMN + " = ?", new String[] {Long.toString(transactionId)});
        writableDatabase.setTransactionSuccessful();
    } catch (SQLiteException e) {
        throw new SQLiteIOException("Unable to clear transaction from failed data packets.", e);
    } finally {
        writableDatabase.endTransaction();
        writableDatabase.close();
    }
}
 
Example 29
Project: Android-Bubble-Game   File: DataBaseHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Check if the database already exist to avoid re-copying the file each time you open the
 * application.
 *
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {
  SQLiteDatabase checkDB = null;
  try {
    String myPath = DB_PATH + DB_NAME;
    checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
  } catch (SQLiteException e) {
    // database doesn't exist yet.
  }
  if (checkDB != null) {
    checkDB.close();
  }
  return checkDB != null ? true : false;
}
 
Example 30
Project: Inflix   File: FavoritesProvider.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values)
        throws UnsupportedOperationException, SQLiteException {
    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    int match = sUriMatcher.match(uri);
    long res = -1;
    switch (match) {
        case FAVORITES_WITH_ID:
            List<String> pathSegments = uri.getPathSegments();
            if (pathSegments != null && pathSegments.size() > 2) {
                String type = pathSegments.get(1);
                String id = pathSegments.get(2);

                if (values != null) {
                    values.put(MediaEntry.COLUMN_IS_FAVORED, 1);
                    values.put(MediaEntry.COLUMN_MEDIA_TYPE, type);
                    int numRows = db.update(MediaEntry.TABLE_NAME, values,
                            MediaEntry.COLUMN_MEDIA_TYPE + " = ? AND " +
                                    MediaEntry.COLUMN_MEDIA_ID + " = ? ", new String[]{type, id});
                    if (numRows <= 0) {
                        res = db.insert(MediaEntry.TABLE_NAME, null, values);
                        if (res == -1) {
                            throw new SQLiteException("Failed to insert record: " + uri);
                        }
                    }
                }
            }
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    mContext.getContentResolver().notifyChange(uri, null);
    return ContentUris.withAppendedId(uri, res);
}
 
Example 31
Project: q-mail   File: MigrationTo30.java   Source Code and License 5 votes vote down vote up
public static void addDeletedColumn(SQLiteDatabase db) {
    try {
        db.execSQL("ALTER TABLE messages ADD deleted INTEGER default 0");
    } catch (SQLiteException e) {
        if (!e.toString().startsWith("duplicate column name: deleted")) {
            throw e;
        }
    }
}
 
Example 32
Project: q-mail   File: MigrationTo36.java   Source Code and License 5 votes vote down vote up
public static void addAttachmentsContentIdColumn(SQLiteDatabase db) {
    try {
        db.execSQL("ALTER TABLE attachments ADD content_id TEXT");
    } catch (SQLiteException e) {
        Timber.e("Unable to add content_id column to attachments");
    }
}
 
Example 33
Project: q-mail   File: MigrationTo40.java   Source Code and License 5 votes vote down vote up
public static void addMimeTypeColumn(SQLiteDatabase db) {
    try {
        db.execSQL("ALTER TABLE messages ADD mime_type TEXT");
    } catch (SQLiteException e) {
        Timber.e("Unable to add mime_type column to messages");
    }
}
 
Example 34
Project: AndiCar   File: DB.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean columnExists(SQLiteDatabase db, String table, String column) {
    String testSql = "SELECT " + column + " FROM " + table + " WHERE 1=2";
    try {
        db.rawQuery(testSql, null);
        return true;
    }
    catch (SQLiteException e) {
        return false;
    }
}
 
Example 35
Project: q-mail   File: MigrationTo44.java   Source Code and License 5 votes vote down vote up
public static void addMessagesThreadingColumns(SQLiteDatabase db) {
    try {
        db.execSQL("ALTER TABLE messages ADD thread_root INTEGER");
        db.execSQL("ALTER TABLE messages ADD thread_parent INTEGER");
        db.execSQL("ALTER TABLE messages ADD normalized_subject_hash INTEGER");
        db.execSQL("ALTER TABLE messages ADD empty INTEGER");
    } catch (SQLiteException e) {
        if (!e.getMessage().startsWith("duplicate column name:")) {
            throw e;
        }
    }
}
 
Example 36
Project: Pocket-Plays-for-Twitch   File: SubscriptionsDbHelper.java   Source Code and License 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	try {
		if (newVersion == 7) {
			new Settings(mContext).setUsersNotToNotifyWhenLive(getUsersNotToNotify(db));
		}
	} catch (SQLiteException e) {
		e.printStackTrace();
	}


	db.execSQL(SQL_DELETE_ENTRIES);
	onCreate(db);
	//db.close();
}
 
Example 37
Project: q-mail   File: MigrationTo35.java   Source Code and License 5 votes vote down vote up
public static void updateRemoveXNoSeenInfoFlag(SQLiteDatabase db) {
    try {
        db.execSQL("update messages set flags = replace(flags, 'X_NO_SEEN_INFO', 'X_BAD_FLAG')");
    } catch (SQLiteException e) {
        Timber.e(e, "Unable to get rid of obsolete flag X_NO_SEEN_INFO");
    }
}
 
Example 38
Project: AndiCar   File: DB.java   Source Code and License 5 votes vote down vote up
public void close() {
    try {
        mDbHelper.close();
        mDbHelper = null;
        mDb.close();
        mDb = null;
    }
    catch (SQLiteException ignored) {
    }
}
 
Example 39
Project: GitHub   File: UpdateUsingUpdateMethodTest.java   Source Code and License 5 votes vote down vote up
public void testUpdateWithStaticUpdateButWrongClass() {
	ContentValues values = new ContentValues();
	values.put("TEACHERNAME", "Toy");
	try {
		DataSupport.update(Object.class, values, teacher.getId());
	} catch (SQLiteException e) {
	}
}
 
Example 40
Project: GitHub   File: UpdateUsingUpdateMethodTest.java   Source Code and License 5 votes vote down vote up
public void testUpdateWithStaticUpdateButWrongColumn() {
	ContentValues values = new ContentValues();
	values.put("TEACHERYEARS", 13);
	try {
		DataSupport.update(Teacher.class, values, teacher.getId());
		fail("no such column: TEACHERYEARS");
	} catch (SQLiteException e) {
	}
}