Java Code Examples for android.database.sqlite.SQLiteDatabase

The following are top voted examples for showing how to use android.database.sqlite.SQLiteDatabase. 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: grow-tracker-android   File: DBHelper.java   Source Code and License 9 votes vote down vote up
public ArrayList<Plant> getAllPlants() {
    ArrayList<Plant> array_list = new ArrayList<Plant>();

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "SELECT id, name, start_date, image FROM plants", null );
    res.moveToFirst();

    while(res.isAfterLast() == false) {
        int id = res.getInt(res.getColumnIndex("id"));
        String name = res.getString(res.getColumnIndex(PLANTS_COLUMN_NAME));
        String startDate = res.getString(res.getColumnIndex(PLANTS_COLUMN_START_DATE));
        String image = res.getString(res.getColumnIndex(PLANTS_COLUMN_IMAGE));
        Plant p = new Plant(id, name, startDate, image);
        array_list.add(p);
        res.moveToNext();
    }
    db.close();
    return array_list;
}
 
Example 2
Project: orgzly-android   File: DatabaseUtils.java   Source Code and License 6 votes vote down vote up
public static String ancestorsIds(SQLiteDatabase db, long bookId, long noteId) {
    Cursor cursor = db.query(
            DbNote.TABLE,
            new String[] { "group_concat(" + DbNote._ID + ", ',')" },
            DatabaseUtils.whereAncestors(bookId, String.valueOf(noteId)),
            null, null, null, null);
    try {
        if (cursor.moveToFirst()) {
            return cursor.getString(0);
        }
    } finally {
        cursor.close();
    }

    return null;
}
 
Example 3
Project: PeSanKita-android   File: SmsDatabase.java   Source Code and License 6 votes vote down vote up
public int getMessageCountForThread(long threadId) {
  SQLiteDatabase db = databaseHelper.getReadableDatabase();
  Cursor cursor     = null;

  try {
    cursor = db.query(TABLE_NAME, new String[] {"COUNT(*)"}, THREAD_ID + " = ?",
                      new String[] {threadId+""}, null, null, null);

    if (cursor != null && cursor.moveToFirst())
      return cursor.getInt(0);
  } finally {
    if (cursor != null)
      cursor.close();
  }

  return 0;
}
 
Example 4
Project: orgzly-android   File: DbProperty.java   Source Code and License 6 votes vote down vote up
public static long getOrInsert(SQLiteDatabase db, long nameId, long valueId) {
    long id = DatabaseUtils.getId(
            db,
            TABLE,
            "name_id = " + nameId + " AND value_id = " + valueId, null);

    if (id == 0) {
        ContentValues values = new ContentValues();
        values.put("name_id", nameId);
        values.put("value_id", valueId);

        id = db.insertOrThrow(TABLE, null, values);
    }

    return id;
}
 
Example 5
Project: Inflix   File: FavoritesProvider.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,
                    @Nullable String[] selectionArgs, @Nullable String sortOrder)
        throws UnsupportedOperationException {
    final SQLiteDatabase db = mDbHelper.getReadableDatabase();
    int match = sUriMatcher.match(uri);
    Cursor cursor;
    switch (match) {
        case FAVORITES:
            cursor = db.query(MediaEntry.TABLE_NAME, projection, MediaEntry.COLUMN_IS_FAVORED + " = 1 ",
                    null, null, null, sortOrder);
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    mContext.getContentResolver().notifyChange(uri, null);
    return cursor;
}
 
Example 6
Project: fitnotifications   File: AppSelectionDbHelper.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {
    Log.d("DB_CREATE", "Creating table " + AppChoiceTable.NAME);
    db.execSQL("create table " + AppChoiceTable.NAME + "(" +
            " _id integer primary key autoincrement, " +
            AppChoiceTable.Cols.APP_PACKAGE_NAME + ", " +
            AppChoiceTable.Cols.APP_NAME + ", " +
            AppChoiceTable.Cols.SELECTION + ", " +
            AppChoiceTable.Cols.FILTER_TEXT + ", " +
            AppChoiceTable.Cols.START_TIME_HOUR + ", " +
            AppChoiceTable.Cols.START_TIME_MINUTE + ", " +
            AppChoiceTable.Cols.STOP_TIME_HOUR + ", " +
            AppChoiceTable.Cols.STOP_TIME_MINUTE + ", " +
            AppChoiceTable.Cols.DISCARD_EMPTY_NOTIFICATIONS + ", " +
            AppChoiceTable.Cols.DISCARD_ONGOING_NOTIFICATIONS + ", " +
            AppChoiceTable.Cols.ALL_DAY_SCHEDULE + ", " +
            AppChoiceTable.Cols.DAYS_OF_WEEK +
            ")"
            // ALERT!!! Make sure you have a comma to separate all names! Had a bug because I forgot it of ALL_DAY_SCHEDULE
    );
}
 
Example 7
Project: XERUNG   File: GroupDb.java   Source Code and License 6 votes vote down vote up
public int getContactCount() {
    int count = 0;
    try {
        String countQuery = "SELECT COUNT(1) FROM " + CONTACT_DB;
        SQLiteDatabase sq = this.getReadableDatabase();
        Cursor cursor = sq.rawQuery(countQuery, null);
        cursor.close();
        count = cursor.getCount();
        sq.close();
    } catch (Exception e) {
        // TODO: handle exception
        //Log.e("GroupDBErro", "GetGroup Count "+e.getMessage());
        e.printStackTrace();
    }
    return count;
}
 
Example 8
Project: QuranAndroid   File: DatabaseAccess.java   Source Code and License 6 votes vote down vote up
/**
 * Function to get aya touched rectangle dimensions and info
 *
 * @param pageNumber Page number
 * @param positionX  Touch X position
 * @param positionY  Touch Y position
 * @return Aya Selection
 */
public Aya getTouchedAya(int pageNumber, float positionX, float positionY) {
    int suraID = -1;
    int ayaID = -1;
    SQLiteDatabase db = openDB(SELECTION_DATABASE);
    String sqlPosition = "select soraid , ayaid from ayarects where page = " +
            "" + pageNumber + " and minx <= " + positionX + " and maxx >= " +
            positionX + " and miny <= " + positionY + " and maxy >= " + positionY + " ;";
    Cursor cursor = db.rawQuery(sqlPosition, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        suraID = cursor.getInt(0);
        ayaID = cursor.getInt(1);
        cursor.moveToNext();
    }

    cursor.close();
    closeDB(db);

    return new Aya(pageNumber, suraID, ayaID, getAyaRectsMap(pageNumber, suraID, ayaID));
}
 
Example 9
Project: Sanxing   File: TaskRepo.java   Source Code and License 6 votes vote down vote up
public void update(Task task) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(Task.KEY_TITLE,task.getTitle());
        values.put(Task.KEY_BEGIN_TIME,task.getBeginDate());
        values.put(Task.KEY_DESCRIPTION,task.getContent());
        values.put(Task.KEY_IMPORTANCE,task.getImportance());
        values.put(Task.KEY_STATE,task.getState());
        values.put(Task.KEY_END_TIME,task.getEndDate());


        // It's a good practice to use parameter ?, instead of concatenate string

        db.update(Task.TABLE, values, Task.KEY_ID + " = ?", new String[] { String.valueOf(task.ID) });
        Log.e("task sta "+task.getState(),"has changed in db");
        db.close(); // Closing database connection
    }
 
Example 10
Project: simple-share-android   File: ExplorerProvider.java   Source Code and License 6 votes vote down vote up
@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = mHelper.getWritableDatabase();
    switch (sMatcher.match(uri)) {
        case URI_BOOKMARK:
            // Ensure that row exists, then update with changed values
            //db.insertWithOnConflict(TABLE_BOOKMARK, null, key, SQLiteDatabase.CONFLICT_IGNORE);
            db.insert(TABLE_BOOKMARK, null, values);

            return uri;
        case URI_CONNECTION:
            db.insert(TABLE_CONNECTION, null, values);

            return uri;
        default:
            throw new UnsupportedOperationException("Unsupported Uri " + uri);
    }
}
 
Example 11
Project: financisto1-holo   File: DatabaseSchemaEvolution.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {
	try {
		Log.i(TAG, "Creating ALTERLOG table");
		db.execSQL("create table "+ALTERLOG+" (script text not null, datetime long not null);");
		db.execSQL("create index "+ALTERLOG+"_script_idx on "+ALTERLOG+" (script);");
		Log.i(TAG, "Running create scripts...");
		runAllScripts(db, CREATE_PATH, false);
		Log.i(TAG, "Running alter scripts...");
		runAllScripts(db, ALTER_PATH, true);
		Log.i(TAG, "Running create view scripts...");
		runAllScripts(db, VIEW_PATH, false);
	} catch (Exception ex) {
		throw new RuntimeException("Failed to create database", ex);
	}
}
 
Example 12
Project: MKAPP   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public void deleteForward(int protocol, int dport) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            db.delete("forward", "protocol = ? AND dport = ?",
                    new String[]{Integer.toString(protocol), Integer.toString(dport)});

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } finally {
        lock.writeLock().unlock();
    }

    notifyForwardChanged();
}
 
Example 13
Project: MainCalendar   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 创建闹钟记录数据表
 * @param db 数据库
 */
private void createAlarmRecord(SQLiteDatabase db){
    String createSQL = "CREATE TABLE [" + AlarmRecordMng.TABLE_NAME + "] (";
    createSQL += "[alarm_index] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ";
    createSQL += "[action_type] INTEGER,";
    createSQL += "[alarm_time] INTEGER,";
    createSQL += "[date_year] INTEGER,";
    createSQL += "[date_month] INTEGER,";
    createSQL += "[date_day] INTEGER,";
    createSQL += "[title] TEXT,";
    createSQL += "[content] TEXT,";
    createSQL += "[display] INTEGER,";
    createSQL += "[pause] INTEGER,";
    createSQL += "[create_time] INTEGER)";

    // 执行创建表的SQL语句
    db.execSQL(createSQL);
}
 
Example 14
Project: q-mail   File: StoreSchemaDefinitionTest.java   Source Code and License 6 votes vote down vote up
private void assertMessageWithSubjectExists(SQLiteDatabase database, String subject) {
    Cursor cursor = database.query("messages", new String[] { "subject" }, null, null, null, null, null);
    try {
        assertTrue(cursor.moveToFirst());
        assertEquals(subject, cursor.getString(0));
    } finally {
        cursor.close();
    }
}
 
Example 15
Project: kuliah-pemrograman-mobile   File: ListDBHelper.java   Source Code and License 6 votes vote down vote up
public List<ItemData> getAll(){
    SQLiteDatabase db = getReadableDatabase();
    List<ItemData> res = new LinkedList<ItemData>();
    Cursor cur = db.rawQuery("SELECT  id, text FROM data", null);
    if (!cur.moveToFirst()){
        cur.close();
        return res;
    }

    do {
        ItemData data = new ItemData();
        data.id = cur.getLong(0);
        data.text = cur.getString(1);
        res.add(data);
    } while (cur.moveToNext());

    cur.close();
    db.close();

    return res;
}
 
Example 16
Project: PeSanKita-android   File: AttachmentDatabase.java   Source Code and License 6 votes vote down vote up
public @NonNull List<DatabaseAttachment> getAttachmentsForMessage(long mmsId) {
  SQLiteDatabase           database = databaseHelper.getReadableDatabase();
  List<DatabaseAttachment> results  = new LinkedList<>();
  Cursor                   cursor   = null;

  try {
    cursor = database.query(TABLE_NAME, PROJECTION, MMS_ID + " = ?", new String[] {mmsId+""},
                            null, null, null);

    while (cursor != null && cursor.moveToNext()) {
      results.add(getAttachment(cursor));
    }

    return results;
  } finally {
    if (cursor != null)
      cursor.close();
  }
}
 
Example 17
Project: UbiBike-client   File: MyDBHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Get a list of all stations
 */
public List<Station> getAllStations() {
    List<Station> listOfAllStations = new ArrayList<Station>();

    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_STATIONS;
    Cursor c = db.rawQuery(query, null);
    while(c.moveToNext()) {
        Station entry = new Station(
                c.getString(c.getColumnIndex(COLUMN_ID_SERVER)),
                c.getString(c.getColumnIndex(COLUMN_NAME)),
                c.getString(c.getColumnIndex(COLUMN_LOCATION)),
                c.getInt(c.getColumnIndex(COLUMN_BIKESAVAILABLE)),
                c.getFloat(c.getColumnIndex(COLUMN_LATITUDE)),
                c.getFloat(c.getColumnIndex(COLUMN_LONGITUDE)),
                c.getFloat(c.getColumnIndex(COLUMN_CLIENT_DISTANCE))
        );
        listOfAllStations.add(entry);
    }

    db.close();
    c.close();
    return listOfAllStations;
}
 
Example 18
Project: Cable-Android   File: ThreadDatabase.java   Source Code and License 6 votes vote down vote up
public long getThreadIdFor(Recipients recipients, int distributionType) {
  long[] recipientIds    = getRecipientIds(recipients);
  String recipientsList  = getRecipientsAsString(recipientIds);
  SQLiteDatabase db      = databaseHelper.getReadableDatabase();
  String where           = RECIPIENT_IDS + " = ?";
  String[] recipientsArg = new String[] {recipientsList};
  Cursor cursor          = null;

  try {
    cursor = db.query(TABLE_NAME, new String[]{ID}, where, recipientsArg, null, null, null);

    if (cursor != null && cursor.moveToFirst())
      return cursor.getLong(cursor.getColumnIndexOrThrow(ID));
    else
      return createThreadForRecipients(recipientsList, recipientIds.length, distributionType);
  } finally {
    if (cursor != null)
      cursor.close();
  }
}
 
Example 19
Project: Sanxing   File: TimeLeftRepo.java   Source Code and License 6 votes vote down vote up
public void update(TimeLeft timeLeft) {

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(TimeLeft.KEY_TITLE,timeLeft.getTitle());
        values.put(TimeLeft.KEY_BEGIN_TIME,timeLeft.getBeginDate());
        values.put(TimeLeft.KEY_DESCRIPTION,timeLeft.getContent());
        values.put(TimeLeft.KEY_IMPORTANCE,timeLeft.getImportance());
        values.put(TimeLeft.KEY_STATE,timeLeft.getState());
        values.put(TimeLeft.KEY_END_TIME,timeLeft.getEndDate());


        // It's a good practice to use parameter ?, instead of concatenate string

        db.update(TimeLeft.TABLE, values, TimeLeft.KEY_ID + " = ?", new String[] { String.valueOf(timeLeft.ID) });
        Log.e("timeLeft sta "+timeLeft.getState(),"has changed in db");
        db.close(); // Closing database connection
    }
 
Example 20
Project: keepass2android   File: AutoDictionary.java   Source Code and License 6 votes vote down vote up
private Cursor query(String selection, String[] selectionArgs) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(AUTODICT_TABLE_NAME);
    qb.setProjectionMap(sDictProjectionMap);

    // Get the database and run the query
    SQLiteDatabase db = sOpenHelper.getReadableDatabase();
    Cursor c = qb.query(db, null, selection, selectionArgs, null, null,
            DEFAULT_SORT_ORDER);
    return c;
}
 
Example 21
Project: SimpleUILauncher   File: LauncherProvider.java   Source Code and License 6 votes vote down vote up
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
    createDbIfNotExists();
    SqlArguments args = new SqlArguments(uri);

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        int numValues = values.length;
        for (int i = 0; i < numValues; i++) {
            addModifiedTime(values[i]);
            if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
                return 0;
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    notifyListeners();
    reloadLauncherIfExternal();
    return values.length;
}
 
Example 22
Project: orgzly-android   File: DatabaseMigration.java   Source Code and License 6 votes vote down vote up
private static void migrateOrgTimestamps(SQLiteDatabase db) {
    db.execSQL("ALTER TABLE org_timestamps RENAME TO org_timestamps_prev");

    for (String sql : DbOrgTimestamp.CREATE_SQL) db.execSQL(sql);

    Cursor cursor = db.query(
            "org_timestamps_prev", new String[] { "_id", "string" }, null, null, null, null, null);
    try {
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            long id = cursor.getLong(0);
            String string = cursor.getString(1);

            OrgDateTime orgDateTime = OrgDateTime.parse(string);

            ContentValues values = new ContentValues();
            values.put("_id", id);
            DbOrgTimestamp.toContentValues(values, orgDateTime);

            db.insert("org_timestamps", null, values);
        }
    } finally {
        cursor.close();
    }

    db.execSQL("DROP TABLE org_timestamps_prev");
}
 
Example 23
Project: android-apkbox   File: AbstractDao.java   Source Code and License 6 votes vote down vote up
/**
 * deleteData
 *
 * @param context   context
 * @param tableName tableName
 * @param where     where
 */
protected int deleteData(Context context, String tableName, String where) {
    int delete = 0;
    try {
        SQLiteDatabase db = getHelper(context).getWritableDatabase();
        try {
            delete = db.delete(tableName, where, null);
        } finally {
            db.close();
            db = null;
        }
    } catch (Exception e) {
        handleException(e);
    }
    return delete;
}
 
Example 24
Project: AndiCar   File: DB.java   Source Code and License 6 votes vote down vote up
private void createExpenses(SQLiteDatabase db, boolean isUpdate) throws SQLException {
    // expenses table
    db.execSQL(CREATE_SQL_EXPENSE_TABLE);
    if (!isUpdate) {
        return;
    }
    // initialize refuel expenses
    String sql = "INSERT INTO " + TABLE_NAME_EXPENSE + "( " + COL_NAME_GEN_NAME + ", " + COL_NAME_GEN_USER_COMMENT + ", " + COL_NAME_GEN_ISACTIVE
            + ", " + COL_NAME_EXPENSE__CAR_ID + ", " + COL_NAME_EXPENSE__DRIVER_ID + ", " + COL_NAME_EXPENSE__EXPENSECATEGORY_ID + ", "
            + COL_NAME_EXPENSE__EXPENSETYPE_ID + ", " + COL_NAME_EXPENSE__AMOUNT + ", " + COL_NAME_EXPENSE__CURRENCY_ID + ", " + COL_NAME_EXPENSE__DATE
            + ", " + COL_NAME_EXPENSE__DOCUMENTNO + ", " + COL_NAME_EXPENSE__INDEX + ", " + COL_NAME_EXPENSE__FROMTABLE + ", "
            + COL_NAME_EXPENSE__FROMRECORD_ID + " " + ") " + "SELECT " + COL_NAME_GEN_NAME + ", " + COL_NAME_GEN_USER_COMMENT + ", "
            + COL_NAME_GEN_ISACTIVE + ", " + COL_NAME_REFUEL__CAR_ID + ", " + COL_NAME_REFUEL__DRIVER_ID + ", " + COL_NAME_REFUEL__EXPENSECATEGORY_ID
            + ", " + COL_NAME_REFUEL__EXPENSETYPE_ID + ", " + COL_NAME_REFUEL__QUANTITY + " * " + COL_NAME_REFUEL__PRICE + ", "
            + COL_NAME_REFUEL__CURRENCY_ID + ", " + COL_NAME_REFUEL__DATE + ", " + COL_NAME_REFUEL__DOCUMENTNO + ", " + COL_NAME_REFUEL__INDEX + ", "
            + "'Refuel' " + ", " + COL_NAME_GEN_ROWID + " " + "FROM " + TABLE_NAME_REFUEL;
    db.execSQL(sql);
}
 
Example 25
Project: Cable-Android   File: DatabaseFactory.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {
  db.execSQL(SmsDatabase.CREATE_TABLE);
  db.execSQL(MmsDatabase.CREATE_TABLE);
  db.execSQL(AttachmentDatabase.CREATE_TABLE);
  db.execSQL(ThreadDatabase.CREATE_TABLE);
  db.execSQL(MmsAddressDatabase.CREATE_TABLE);
  db.execSQL(IdentityDatabase.CREATE_TABLE);
  db.execSQL(DraftDatabase.CREATE_TABLE);
  db.execSQL(PushDatabase.CREATE_TABLE);
  db.execSQL(GroupDatabase.CREATE_TABLE);
  db.execSQL(RecipientPreferenceDatabase.CREATE_TABLE);

  executeStatements(db, SmsDatabase.CREATE_INDEXS);
  executeStatements(db, MmsDatabase.CREATE_INDEXS);
  executeStatements(db, AttachmentDatabase.CREATE_INDEXS);
  executeStatements(db, ThreadDatabase.CREATE_INDEXS);
  executeStatements(db, MmsAddressDatabase.CREATE_INDEXS);
  executeStatements(db, DraftDatabase.CREATE_INDEXS);
  executeStatements(db, GroupDatabase.CREATE_INDEXS);
}
 
Example 26
Project: android-tdd-persistence   File: TaskDBStorage.java   Source Code and License 6 votes vote down vote up
@Override
public List<TaskDBModel> findAll() {
    SQLiteDatabase db = openDB();

    Cursor cursor = db.query(
            TABLE_NAME,                     // The table to query
            dbProjection(),                               // The columns to return
            null,                                // The columns for the WHERE clause
            null,                            // The values for the WHERE clause
            null,                                     // don't group the rows
            null,                                     // don't filter by row groups
            null
    );

    return toTaskDBModels(cursor);
}
 
Example 27
Project: editor-sql   File: DBCore.java   Source Code and License 6 votes vote down vote up
private static List<String> getColumns(SQLiteDatabase db, String tableName) {
    List<String> columns = new ArrayList<>();
    Cursor cursor = null;

    try {
        cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 1", null);
        if (cursor != null) {
            columns = new ArrayList<>(Arrays.asList(cursor.getColumnNames()));
        }
    } catch (Exception e) {
        Log.v(tableName, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (cursor != null)
            cursor.close();
    }

    return columns;
}
 
Example 28
Project: DereHelper   File: DBHelper.java   Source Code and License 6 votes vote down vote up
public List<String> getAll(String tableName, String column){
    if (Utils.checkEmpty(tableName, column)){
        SQLiteDatabase db = getReadableDatabase();
        if (db == null){
            return null;
        }
        List<String> result = new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from " + tableName, null);
        while (cursor.moveToNext()) {
            result.add(cursor.getString(cursor.getColumnIndex(column)));
        }
        cursor.close();
        return result;
    }else {
        return null;
    }
}
 
Example 29
Project: pivaa   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Getter of record from DB
 * @param id
 * @return
 */
public DatabaseRecord getRecord(int id) {
    DatabaseRecord record = new DatabaseRecord();

    try {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from data where id='" + String.valueOf(id) + '"', null);

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

        record.setId(Integer.parseInt(cursor.getString(0)));
        record.setTitle(cursor.getString(1));
        record.setAuthor(cursor.getString(2));

        Log.d("htbridge","getRecord(" + id + "): " + record.toString());

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

    return record;
}
 
Example 30
Project: GitHub   File: RouteService.java   Source Code and License 6 votes vote down vote up
public void insertData(String routeListStr) {
    ContentValues values = new ContentValues();
    // 向该对象中插入键值对,其中键是列名,值是希望插入到这一列的值,值必须和数据当中的数据类型一致
    values.put("cycle_date", Utils.getDateFromMillisecond(beginTime));
    values.put("cycle_time", totalTime);
    values.put("cycle_distance", totalDistance);
    values.put("cycle_price", totalPrice);
    values.put("cycle_points", routeListStr);
    // 创建DatabaseHelper对象
    RouteDBHelper dbHelper = new RouteDBHelper(this);
    // 得到一个可写的SQLiteDatabase对象
    SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
    // 调用insert方法,就可以将数据插入到数据库当中
    // 第一个参数:表名称
    // 第二个参数:SQl不允许一个空列,如果ContentValues是空的,那么这一列被明确的指明为NULL值
    // 第三个参数:ContentValues对象
    sqliteDatabase.insert("cycle_route", null, values);
    sqliteDatabase.close();
}
 
Example 31
Project: PrivacyShield   File: DatabaseOperations.java   Source Code and License 5 votes vote down vote up
public DatabaseOperations(Context context) {
        super(context, dbname, null, 1);

//------------------------------------Database Opening/ (Database Creation and Table Creations)--------------
        db = context.openOrCreateDatabase(dbname,SQLiteDatabase.CREATE_IF_NECESSARY,null);
        String tbl="create table if not exists notes ( noteid integer primary key autoincrement, notetitle text, notecontent text, notecreated DATETIME DEFAULT CURRENT_TIMESTAMP)";
        db.execSQL(tbl);


//-----------------------------------------------------------------------------------------------------------
    }
 
Example 32
Project: musicplayer   File: MusicListBizImpl.java   Source Code and License 5 votes vote down vote up
@Override
    public List<MusicList> findByAlbum(Context mcontext, String album) {
//        获取数据库连接对象
        ConnectionManager connectionManager = new ConnectionManager();
        SQLiteDatabase sqLiteDatabase = connectionManager.openConnection(mcontext, "read");
//        调用DAO实现操作
        List<MusicList> list = this.musicListDao.selectByAlbum(sqLiteDatabase,album);
//        关闭数据库连接
        connectionManager.closeConnection(sqLiteDatabase);

        return list;
    }
 
Example 33
Project: HiBangClient   File: MeHelpMsgDB.java   Source Code and License 5 votes vote down vote up
public int getMeHelpMsgNoReadCount() {
	SQLiteDatabase db = this.getReadableDatabase();
	Cursor cursor;
	cursor = db.rawQuery("select * from " + TABLE_NAME
			+ " where isNoRead=1", null);
	return cursor.getCount();
}
 
Example 34
Project: SpecialNotebook   File: MovieDb.java   Source Code and License 5 votes vote down vote up
public List<MovieModel> getWatchedItems() {
    List<MovieModel> titles = new ArrayList<MovieModel>();
    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.query(TABLE_MOVIE, new String[]{"id","original_title", "title","imdbRating","plot","poster","release_date","iswatched"}, null, null, null, null, null);
    while (cursor.moveToNext()) {
        if(cursor.getInt(7) == 1) {
            titles.add(new MovieModel(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5),
                    cursor.getString(6), cursor.getInt(7)));
        }
    }
    db.close();

    return titles;
}
 
Example 35
Project: TrackPlan-app   File: DatabaseHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}
 
Example 36
Project: Google-Android-Developer   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void deleteAllData() {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
//        为删除表中所有行,暂无需 where 子句
//        // 定义 'where' 部分
//        String selection = FeedEntry.COLUMN_NAME_TITLE + " LIKE ?";
//        // 按照占位符顺序指定对应的值
//        String[] selectionArgs = { DUMMY_DATA_TITLE };
        // 执行 SQL 语句
        db.delete(FeedEntry.TABLE_NAME, null, null);
    }
 
Example 37
Project: disclosure-android-app   File: AddLibraryFeaturesMigration.java   Source Code and License 5 votes vote down vote up
@Override public void update(SQLiteDatabase db) {
  String dropTable = "DROP TABLE IF EXISTS ";
  db.execSQL(dropTable + App.TABLE_NAME);
  db.execSQL(dropTable + LibraryApp.TABLE_NAME);
  db.execSQL(dropTable + Version.TABLE_NAME);
  db.execSQL(dropTable + Library.TABLE_NAME);

  db.execSQL(App.CREATE_TABLE);
  db.execSQL(Version.CREATE_TABLE);
  db.execSQL(Library.CREATE_TABLE);
  db.execSQL(LibraryApp.CREATE_TABLE);
}
 
Example 38
Project: ceji_android   File: BookmarkDatabaseHelper.java   Source Code and License 5 votes vote down vote up
private synchronized SQLiteDatabase getDataBase() {
    if (this.database == null || !this.database.isOpen()) {
        this.database = getWritableDatabase();
    }

    return this.database;
}
 
Example 39
Project: XERUNG   File: GroupDb.java   Source Code and License 5 votes vote down vote up
public ArrayList<ContactBean> getAllMember(String tableName) {

        ArrayList<ContactBean> gbList = new ArrayList<ContactBean>();
        try {
            String selectQuery = "SELECT " + MEMBER_NAME + ", " + MEMBER_PHONE + ", " + MEMBER_SEARCHKEY + ", " + MEMBER_UID + ", " + MEMBER_FLAG + ", " + MEMBER_ORG_NAME + ", "
                    + MEMBER_PH_BOK_NAME + ", " + MEMBER_ISMY_CONTACT + ", " + MEMBER_BLOOD_GROUP + ", " + MEMBER_ADMIN_FLAG + ", " + MEMBER_CREATED_DATE + " FROM " + tableName;

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    ContactBean contact = new ContactBean();
                    contact.setName(cursor.getString(0));
                    contact.setNumber(cursor.getString(1));
                    contact.setSearchKey(cursor.getString(2));
                    contact.setUID(cursor.getString(3));
                    contact.setRequestFlag(cursor.getString(4));
                    contact.setOrignalName(cursor.getString(5));
                    contact.setMyPhoneBookName(cursor.getString(6));
                    contact.setIsMyContact(cursor.getInt(7));
                    contact.setmBloodGroup(cursor.getString(8));
                    contact.setAdminFlag(cursor.getString(9));
                    contact.setmCreatedDate(cursor.getString(10));
                    gbList.add(contact);
                } while (cursor.moveToNext());
            }
            if (cursor != null)
                cursor.close();
            db.close();
            ;
        } catch (Exception e) {
            // TODO: handle exception
            //Log.e("GroupDBErro", "FetchAllDB "+e.getMessage());
            e.printStackTrace();
        }
        return gbList;
    }
 
Example 40
Project: boohee_v5.6   File: bc.java   Source Code and License 5 votes vote down vote up
public void a(MQMessage mQMessage, long j) {
    SQLiteDatabase c = c();
    try {
        String[] strArr = new String[]{j + ""};
        ContentValues contentValues = new ContentValues();
        a(mQMessage, contentValues);
        c.update("mq_message", contentValues, "id=?", strArr);
    } catch (Exception e) {
        Log.d("meiqia", "updateMessageId error");
    } finally {
        d();
    }
}
 
Example 41
Project: SimpleUILauncher   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 42
Project: android-dev-challenge   File: TaskDbHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Called when the tasks database is created for the first time.
 */
@Override
public void onCreate(SQLiteDatabase db) {

    // Create tasks table (careful to follow SQL formatting rules)
    final String CREATE_TABLE = "CREATE TABLE "  + TaskEntry.TABLE_NAME + " (" +
                    TaskEntry._ID                + " INTEGER PRIMARY KEY, " +
                    TaskEntry.COLUMN_DESCRIPTION + " TEXT NOT NULL, " +
                    TaskEntry.COLUMN_PRIORITY    + " INTEGER NOT NULL);";

    db.execSQL(CREATE_TABLE);
}
 
Example 43
Project: GCSApp   File: DemoDBManager.java   Source Code and License 5 votes vote down vote up
synchronized int getUnreadNotifyCount() {
    int count = 0;
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    if (db.isOpen()) {
        Cursor cursor = db.rawQuery("select " + InviteMessgeDao.COLUMN_NAME_UNREAD_MSG_COUNT + " from " + InviteMessgeDao.TABLE_NAME, null);
        if (cursor.moveToFirst()) {
            count = cursor.getInt(0);
        }
        cursor.close();
    }
    return count;
}
 
Example 44
Project: simple-share-android   File: ExplorerProvider.java   Source Code and License 5 votes vote down vote up
private void createTablesV1(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_BOOKMARK + " (" +
            BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            BookmarkColumns.TITLE + " TEXT," +
            BookmarkColumns.AUTHORITY + " TEXT," +
            BookmarkColumns.ROOT_ID + " TEXT," +
            BookmarkColumns.ICON + " INTEGER," +
            BookmarkColumns.PATH + " TEXT," +
            BookmarkColumns.FLAGS + " INTEGER," +
            "UNIQUE (" + BookmarkColumns.AUTHORITY + ", " + BookmarkColumns.ROOT_ID + ", " + BookmarkColumns.PATH + ") ON CONFLICT REPLACE " +
            ")");
}
 
Example 45
Project: Mybilibili   File: MySaveDatabaseHelper.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(CREATE_QIUSHI);
    sqLiteDatabase.execSQL(CREATE_QIUSHIPIN);
    sqLiteDatabase.execSQL(CREATE_DOWNQIUSHIPIN);
    sqLiteDatabase.execSQL(CREATE_DIARY);
    sqLiteDatabase.execSQL(CREATE_SEARCH);
}
 
Example 46
Project: SimpleUILauncher   File: LauncherProvider.java   Source Code and License 5 votes vote down vote up
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    createDbIfNotExists();
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        ContentProviderResult[] result =  super.applyBatch(operations);
        db.setTransactionSuccessful();
        reloadLauncherIfExternal();
        return result;
    } finally {
        db.endTransaction();
    }
}
 
Example 47
Project: TimeTrix   File: DatabaseAdapter.java   Source Code and License 5 votes vote down vote up
public int countRows() {
    String countQuery = "SELECT  * FROM " + DatabaseHelper.TABLE_NAME;
    SQLiteDatabase db = mDatabaseHelper.getReadableDatabase ();
    Cursor cursor = db.rawQuery (countQuery, null);
    int count = cursor.getCount ();
    cursor.close ();
    db.close ();
    return count; //return total no of rows in the database
}
 
Example 48
Project: TreasureHunting   File: QuestAndAnswDatabaseHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Method enables adding new line to the Database of Questions and answers
 * @param question Question the user will receive
 * @param rightAnswer correct answer
 * @param optionalAnswer1 optional anwer to choose from
 * @param optionalAnswer2 optional anwer to choose from
 * @param optionalAnswer3 optional anwer to choose from
 */
public void insertDataQA(String question, String rightAnswer, String optionalAnswer1, String optionalAnswer2, String optionalAnswer3, int passed, String secretCode) {
    SQLiteDatabase db  = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2, question);
    contentValues.put(COL_3, rightAnswer);
    contentValues.put(COL_4, optionalAnswer1);
    contentValues.put(COL_5, optionalAnswer2);
    contentValues.put(COL_6, optionalAnswer3);
    contentValues.put(COL_7, passed);
    contentValues.put(COL_SC, secretCode);
    long result = db.insert(TABLE_QA, null, contentValues);
}
 
Example 49
Project: Open-Quran-Radio   File: StationsDbHelper.java   Source Code and License 5 votes vote down vote up
public int ChangeIsFavouriteOfStation(long station_ID, int IsFavourite) {
    SQLiteDatabase db = this.getWritableDatabase();
    //update db
    ContentValues newValues = new ContentValues();
    newValues.put(StationsDbContract.StationEntry.COLUMN_IS_FAVOURITE, IsFavourite);
    String strFilter = StationsDbContract.StationEntry._ID + " = " + String.valueOf(station_ID);
    return db.update(TABLE_NAME, newValues, strFilter, null);
}
 
Example 50
Project: chat-sdk-android-push-firebase   File: BLinkedAccountDao.java   Source Code and License 5 votes vote down vote up
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
    String constraint = ifNotExists? "IF NOT EXISTS ": "";
    db.execSQL("CREATE TABLE " + constraint + "'BLINKED_ACCOUNT' (" + //
            "'_id' INTEGER PRIMARY KEY ," + // 0: id
            "'TOKEN' TEXT," + // 1: Token
            "'TYPE' INTEGER," + // 2: type
            "'BUSER_DAO_ID' INTEGER);"); // 3: BUserDaoId
}
 
Example 51
Project: UnforgetIt   File: DataBaseJPAHelper.java   Source Code and License 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
    try {
        Log.d(this.getClass().getName(), "onUpgrade");
        TableUtils.dropTable(connectionSource, Task.class, true);
        onCreate(database, connectionSource);
    } catch (SQLException e) {
        Log.e(this.getClass().getName(), "Can't drop databases", e);
        throw new RuntimeException(e);
    }

}
 
Example 52
Project: Retrospector-Android   File: RetroDbHelper.java   Source Code and License 5 votes vote down vote up
public boolean insertReview(Review review) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Co_Reviews_Id,review.getId());
    contentValues.put(Co_Reviews_MediaId,review.getMediaId());
    contentValues.put(Co_Reviews_Rating,review.getRating());
    contentValues.put(Co_Reviews_Date,review.getDate().getTime());
    contentValues.put(Co_Reviews_User,review.getUser());
    contentValues.put(Co_Reviews_Review,review.getReview());
    long result = db.insert(Tb_Reviews,null ,contentValues);
    if (result == -1)
        return false;
    else
        return true;
}
 
Example 53
Project: Hubs   File: PreferenceManager.java   Source Code and License 5 votes vote down vote up
@Override
public void removeHubPreferences(@NonNull HubPreference... preferences) {
    final SQLiteDatabase db = mDBHelper.getWritableDatabase();

    for (HubPreference preference : preferences) {
        db.delete(PreferenceDBHelper.TABLE_NAME, "hub_id=?", new String[] {preference.getHubId()});
    }

    db.close();
}
 
Example 54
Project: Bailan   File: DbDownUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取可读数据库
 */
private SQLiteDatabase getReadableDatabase() {
    if (openHelper == null) {
        openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
    }
    SQLiteDatabase db = openHelper.getReadableDatabase();
    return db;
}
 
Example 55
Project: vinyl-cast   File: DatabaseAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db)
		throws SQLiteConstraintException, SQLiteDiskIOException,
              SQLiteException {

	db.execSQL(CREATE_TABLE_SEARCH_HISTORY);
	db.execSQL(CREATE_TABLE_RESPONSES);
	db.execSQL(CREATE_INDEX_DATE);
	Log.i(TAG, "Tables created...");

}
 
Example 56
Project: EyeShopping   File: DBHelper.java   Source Code and License 5 votes vote down vote up
/***** UPDATE TABLE *****/

    public void updateSearchedProductLike(int id, int like) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("UPDATE searched_product SET like=" + like +
                " WHERE _id=" + id + ";");
        Log.i(id+"", " - updateSearchedProductLike complete!");
    }
 
Example 57
Project: q-mail   File: MigrationTest.java   Source Code and License 5 votes vote down vote up
private void insertSimplePlaintextMessage(SQLiteDatabase db) {
    String[] statements = new String[] {
            "INSERT INTO messages VALUES(2,0,16,'3','regular mail',1453380493000," +
                    "'X_GOT_ALL_HEADERS,X_DOWNLOADED_FULL','[email protected];','[email protected]'," +
                    "'','','','<pre class=\"k9mail\">nothing special here.<br /></pre>','nothing special here.\n'," +
                    "0,1453380499000,'<[email protected]>','nothing special here.'," +
                    "'text/plain',NULL,0,1,0,0,0)",

            "INSERT INTO headers (message_id, name, value) VALUES (2,'Return-Path','<[email protected]>')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'X-Original-To','[email protected]')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'Delivered-To','[email protected]')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'Date','Thu, 21 Jan 2016 13:48:13 +0100')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'From','Vincent Breitmoser <[email protected]>')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'To','[email protected]')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'Subject','regular mail')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'Message-ID','<[email protected]>')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'Content-Disposition','inline')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'User-Agent','Mutt/1.5.24 (2015-08-30)')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'MIME-Version','1.0')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'Content-Type','text/plain\n charset=utf-8')",
            "INSERT INTO headers (message_id, name, value) VALUES (2,'Content-Transfer-Encoding','8bit')",

            "INSERT INTO threads VALUES(3,2,3,NULL)",
    };

    for (String statement : statements) {
        db.execSQL(statement);
    }
}
 
Example 58
Project: android-dev-challenge   File: WeatherProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Handles requests to insert a set of new rows. In Sunshine, we are only going to be
 * inserting multiple rows of data at a time from a weather forecast. There is no use case
 * for inserting a single row of data into our ContentProvider, and so we are only going to
 * implement bulkInsert. In a normal ContentProvider's implementation, you will probably want
 * to provide proper functionality for the insert method as well.
 *
 * @param uri    The content:// URI of the insertion request.
 * @param values An array of sets of column_name/value pairs to add to the database.
 *               This must not be {@code null}.
 *
 * @return The number of values that were inserted.
 */
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    switch (sUriMatcher.match(uri)) {

        case CODE_WEATHER:
            db.beginTransaction();
            int rowsInserted = 0;
            try {
                for (ContentValues value : values) {
                    long weatherDate =
                            value.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
                    if (!SunshineDateUtils.isDateNormalized(weatherDate)) {
                        throw new IllegalArgumentException("Date must be normalized to insert");
                    }

                    long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
                    if (_id != -1) {
                        rowsInserted++;
                    }
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }

            if (rowsInserted > 0) {
                getContext().getContentResolver().notifyChange(uri, null);
            }

            return rowsInserted;

        default:
            return super.bulkInsert(uri, values);
    }
}
 
Example 59
Project: AndroidCrossPromotion   File: DatabaseHelper.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {
    //Table Query.
    String adsTable = "CREATE TABLE IF NOT EXISTS ads (_id INTEGER PRIMARY KEY AUTOINCREMENT, originalid INTEGER, fromid INTEGER, adtype INTEGER, status INTEGER, " +
            "segment TEXT, location TEXT, deviceversion INTEGER, weight INTEGER, price INTEGER, title TEXT, subtitle TEXT, description TEXT, descriptionshort TEXT, " +
            "category TEXT, rating INTEGER, installs INTEGER, version TEXT, developer TEXT, email TEXT, address TEXT, website TEXT, linkurl TEXT, packagename TEXT, " +
            "previewimageurl TEXT, imageurl TEXT, previewvideoimageurl TEXT, videourl TEXT, text1 TEXT, text2 TEXT, text3 TEXT, number1 INTEGER, number2 INTEGER, " +
            "number3 INTEGER, createat INTEGER DEFAULT 0, updateat INTEGER DEFAULT 0, startat INTEGER DEFAULT 0, endat INTEGER DEFAULT 0, removeat INTEGER DEFAULT 0);";
    String analyticsTable = "CREATE TABLE IF NOT EXISTS analytics (_id INTEGER PRIMARY KEY AUTOINCREMENT, analyticstype INTEGER, statid INTEGER, statint INTEGER, stattext TEXT, createat INTEGER DEFAULT 0, uploaded INTEGER DEFAULT 0);";

    //Execute Query
    db.execSQL(adsTable);
    Log.d("SQLite", "Tables created");
}
 
Example 60
Project: Android-DownloadManager   File: DownloadProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Set all existing downloads to the cache partition to be invisible in the downloads UI.
 */
private void makeCacheDownloadsInvisible(SQLiteDatabase db) {
    ContentValues values = new ContentValues();
    values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, false);
    String cacheSelection = Downloads.Impl.COLUMN_DESTINATION
            + " != " + Downloads.Impl.DESTINATION_EXTERNAL;
    db.update(DB_TABLE, values, cacheSelection, null);
}