Code example for SQLiteDatabase

Methods: execSQLinsertqueryupdate

0
	public long createFile(String fileName, String keyFile) {
		 
		// Check to see if this filename is already used 
		Cursor cursor;
		try { 
			cursor = mDb.query(true, FILE_TABLE, new String[] {KEY_FILE_ID}, 
					KEY_FILE_FILENAME + "=?", new String[] {fileName}, null, null, null, null);
		} catch (Exception e ) {
			assert(true); 
			return -1; 
		} 
		 
		long result;
		// If there is an existing entry update it with the new key file 
		if ( cursor.getCount() > 0 ) {
			cursor.moveToFirst();
			long id = cursor.getLong(cursor.getColumnIndexOrThrow(KEY_FILE_ID));
			 
			ContentValues vals = new ContentValues();
			vals.put(KEY_FILE_KEYFILE, keyFile);
			vals.put(KEY_FILE_UPDATED, System.currentTimeMillis());
			 
			result = mDb.update(FILE_TABLE, vals, KEY_FILE_ID + " = " + id, null);
		 
		// Otherwise add the new entry 
		} else { 
			ContentValues vals = new ContentValues();
			vals.put(KEY_FILE_FILENAME, fileName);
			vals.put(KEY_FILE_KEYFILE, keyFile);
			vals.put(KEY_FILE_UPDATED, System.currentTimeMillis());
			 
			result = mDb.insert(FILE_TABLE, null, vals);
			 
		} 
		// Delete all but the last five records 
		try { 
			deleteAllBut(MAX_FILES);
		} catch (Exception e) {
			e.printStackTrace();
			assert(true); 
		} 
		 
		cursor.close();
		 
		return result;
		 
	} 
	 
	private void deleteAllBut(int limit) {
		Cursor cursor = mDb.query(FILE_TABLE, new String[] {KEY_FILE_UPDATED}, null, null, null, null, KEY_FILE_UPDATED);
		 
		if ( cursor.getCount() > limit ) {
			cursor.moveToFirst();
			long time = cursor.getLong(cursor.getColumnIndexOrThrow(KEY_FILE_UPDATED));
			 
			mDb.execSQL("DELETE FROM " + FILE_TABLE + " WHERE " + KEY_FILE_UPDATED + "<" + time + ";");
		} 
		 
		cursor.close();
		 
	}