public void updateFavorite(int channelId, boolean isFavorite) { synchronized (lock) { SQLiteDatabase database = getWritableDatabase(); Cursor cursor = database.query( FAVORITE_TABLE_NAME, new String[] {KEY_CHANNEL_ID}, KEY_CHANNEL_ID + "=" + channelId, null, null, null, null); try { ContentValues values = new ContentValues(); values.put(KEY_CHANNEL_ID, channelId); values.put(KEY_IS_FAVORITE, isFavorite ? 1 : 0); if (cursor.getCount() > 0) { database.update(FAVORITE_TABLE_NAME, values, KEY_CHANNEL_ID + "=" + channelId, null); } else { database.insert(FAVORITE_TABLE_NAME, null, values); } } finally { cursor.close(); database.close(); } } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == RESULT_OK && data != null) { Uri selectedImage = data.getData(); String[] filePath = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePath, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePath[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); ImageView image = (ImageView) findViewById(R.id.imageView2); image.setImageBitmap(BitmapFactory.decodeFile(picturePath)); imagepath = picturePath; } else if (requestCode == 2 && resultCode == RESULT_OK) { Bitmap photo = (Bitmap) data.getExtras().get("data"); ImageView image = (ImageView) findViewById(R.id.imageView2); image.setImageBitmap(photo); try { File imagefile = createImageFile(photo); Log.d("dir", imagefile.getAbsolutePath()); imagepath = imagefile.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } } }
@LargeTest public void testManyRowsTxt() throws Exception { mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);"); StringBuilder sql = new StringBuilder(2100); sql.append("INSERT INTO test (data) VALUES ('"); Random random = new Random(System.currentTimeMillis()); StringBuilder randomString = new StringBuilder(1979); for (int i = 0; i < 1979; i++) { randomString.append((random.nextInt() & 0xf) % 10); } sql.append(randomString); sql.append("');"); // if cursor window size changed, adjust this value too final int count = 600; // more than two fillWindow needed for (int i = 0; i < count; i++) { mDatabase.execSQL(sql.toString()); } Cursor c = mDatabase.query("test", new String[] {"data"}, null, null, null, null, null); assertNotNull(c); int i = 0; while (c.moveToNext()) { assertEquals(randomString.toString(), c.getString(0)); i++; } assertEquals(count, i); assertEquals(count, c.getCount()); c.close(); }
void addUserRole(User user, String role) { SQLiteDatabase db = this.getWritableDatabase(); int role_id = 0; String selectQuery = "SELECT " + KEY_ROLE_ID + " FROM " + TABLE_ROLES + " WHERE " + KEY_ROLE + " = '" + role + "'"; Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { role_id = Integer.parseInt(cursor.getString(0)); } ContentValues values = new ContentValues(); values.put(KEY_USER_ID, user.getUserId()); values.put(KEY_ROLE_ID, role_id); // Insert Row db.insert(TABLE_USER_ROLES, null, values); db.close(); }
@MediumTest public void testCursor2() throws Exception { populateDefaultTable(); Cursor c = mDatabase.query("test", null, "_id > 1000", null, null, null, null); assertEquals(0, c.getCount()); assertTrue(c.isBeforeFirst()); try { c.getInt(0); fail("CursorIndexOutOfBoundsException expected"); } catch (CursorIndexOutOfBoundsException ex) { // expected } int i; for (c.moveToFirst(), i = 0; !c.isAfterLast(); c.moveToNext(), i++) { c.getInt(0); } assertEquals(0, i); try { c.getInt(0); fail("CursorIndexOutOfBoundsException expected"); } catch (CursorIndexOutOfBoundsException ex) { // expected } c.close(); }
@Override public long getItemId(int position) { if (mDataValid && mCursor != null && mCursor.moveToPosition(position)) { return mCursor.getLong(mRowIdColumn); } return 0; }
private void sendResults(Long attemptId) { dbHelper = new DbHelper(this); Cursor cur = dbHelper.getUnsubmitted(attemptId.intValue()); cur.moveToFirst(); String content = ""; while (cur.isAfterLast() == false) { content = dbHelper.createSubmitResponseObject(cur); cur.moveToNext(); } cur.close(); dbHelper.close(); APIRequest[] resultsToSend = new APIRequest[1]; APIRequest r = new APIRequest(); r.fullurl = prefs.getString("prefServer", getString(R.string.prefServerDefault)) + "api/?method=submit&format=json"; r.rowId = attemptId.intValue(); r.username = prefs.getString("prefUsername", ""); r.password = prefs.getString("prefPassword", ""); r.timeoutConnection = Integer.parseInt(prefs.getString("prefServerTimeoutConnection", "10000")); r.timeoutSocket = Integer.parseInt(prefs.getString("prefServerTimeoutResponse", "10000")); r.content = content; resultsToSend[0] = r; Toast.makeText(this, "Sending results", Toast.LENGTH_SHORT).show(); // send results to server SubmitResultsTask task = new SubmitResultsTask(QuizActivityEnd.this); task.setDownloaderListener(this); task.execute(resultsToSend); }
/** * Add only the SectionHeaders that have history items within their range to a SparseArray, where * the array index is the position of the header in the history-only (no clients) ordering. * * @param c data Cursor * @param sparseArray SparseArray to populate */ private static void populateSectionHeaders(Cursor c, SparseArray<SectionHeader> sparseArray) { sparseArray.clear(); if (c == null || !c.moveToFirst()) { return; } SectionHeader section = null; do { final int historyPosition = c.getPosition(); final long visitTime = c.getLong(c.getColumnIndexOrThrow(BrowserContract.History.DATE_LAST_VISITED)); final SectionHeader itemSection = CombinedHistoryPanel.getSectionFromTime(visitTime); if (section != itemSection) { section = itemSection; sparseArray.append(historyPosition + sparseArray.size(), section); } if (section == SectionHeader.OLDER_THAN_SIX_MONTHS) { break; } } while (c.moveToNext()); }
@Override public int getNextWaypointNumber(long trackId, boolean statistics) { if (trackId < 0) { return -1; } Cursor cursor = null; try { String[] projection = {WaypointsColumns._ID}; String selection = WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns.TYPE + "=?"; int type = statistics ? Waypoint.TYPE_STATISTICS : Waypoint.TYPE_WAYPOINT; String[] selectionArgs = new String[] {Long.toString(trackId), Integer.toString(type)}; cursor = getWaypointCursor(projection, selection, selectionArgs, WaypointsColumns._ID, 0); if (cursor != null) { int count = cursor.getCount(); /* * For statistics markers, the first marker is for the track statistics, * so return the count as the next user visible number. */ return statistics ? count : count + 1; } } finally { if (cursor != null) { cursor.close(); } } return -1; }
// 查找下载完成后本地保存路径 public synchronized String getLocalByUrl(String sMovieurl) { // TODO Auto-generated method stub try { database = pipiDBHelp.getReadableDatabase(); String sql = "select * from " + PipiDBHelp.STORE_TABLENAME + " where " + TableName.MovieUrl + "= '" + sMovieurl + "'"; cursor = database.rawQuery(sql, null); if (cursor.moveToNext()) { return cursor.getString(cursor.getColumnIndex(TableName.MovieLocalUrl)); } } catch (Exception e) { // TODO: handle exception } finally { closeCursor(); } return null; }
public static Uri getUserImageUri(Context context) { if (Build.VERSION.SDK_INT > 14) { String[] mProjection = new String[] { ContactsContract.Profile._ID, ContactsContract.Profile.DISPLAY_NAME_PRIMARY, ContactsContract.Profile.LOOKUP_KEY, ContactsContract.Profile.PHOTO_THUMBNAIL_URI }; Cursor mProfileCursor = context .getContentResolver() .query(ContactsContract.Profile.CONTENT_URI, mProjection, null, null, null); try { if (mProfileCursor.moveToFirst()) { String photo = mProfileCursor.getString( mProfileCursor.getColumnIndex(ContactsContract.Profile.PHOTO_THUMBNAIL_URI)); if (!TextUtils.isEmpty(photo)) { return Uri.parse(photo); } } } finally { if (mProfileCursor != null) { mProfileCursor.close(); } } } return null; }
/** * Calculate where this task should appear on the list for the given project. If no project is * defined, order is meaningless, so return -1. New tasks go on the end of the list, so the * highest current order value for tasks for this project and add one to this. For existing tasks, * check if the project changed, and if so treat like a new task, otherwise leave the order as is. * * @param projectId the project selected for this task * @return 0-indexed order of task when displayed in the project view */ private Integer calculateTaskOrder(Id projectId) { if (!projectId.isInitialised()) return -1; int order; if (mState == State.STATE_INSERT || !projectId.equals(mOriginalItem.getProjectId())) { // get current highest order value Cursor cursor = getContentResolver() .query( TaskProvider.Tasks.CONTENT_URI, new String[] {TaskProvider.Tasks.PROJECT_ID, TaskProvider.Tasks.DISPLAY_ORDER}, TaskProvider.Tasks.PROJECT_ID + " = ?", new String[] {String.valueOf(projectId.getId())}, TaskProvider.Tasks.DISPLAY_ORDER + " desc"); if (cursor.moveToFirst()) { // first entry is current highest value int highest = cursor.getInt(1); order = highest + 1; } else { // no tasks in the project yet. order = 0; } cursor.close(); } else { order = mOriginalItem.getOrder(); } return order; }
public boolean hasFavorites() { boolean found = false; synchronized (lock) { SQLiteDatabase database = getReadableDatabase(); Cursor cursor = database.query( FAVORITE_TABLE_NAME, new String[] {KEY_IS_FAVORITE}, KEY_IS_FAVORITE + "=1", null, null, null, null); try { if (cursor.getCount() > 0) { found = true; } } finally { cursor.close(); database.close(); } } return found; }
private Word cursorToWord(Cursor cursor) { Word word = new Word(); word.setWord(cursor.getString(cursor.getColumnIndex(NewWordsTable.Cols.ORIGINAL_WORD))); word.setTranslation(cursor.getString(cursor.getColumnIndex(NewWordsTable.Cols.TRANSLATION))); return word; }
void revokeUserRole(User user, String role) { SQLiteDatabase db = this.getWritableDatabase(); int role_id = 0; String selectQuery = "SELECT " + KEY_ROLE_ID + " FROM " + TABLE_ROLES + " WHERE " + KEY_ROLE + " = '" + role + "'"; Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { role_id = Integer.parseInt(cursor.getString(0)); } if (role_id > 0) { // Delete Row db.delete( TABLE_USER_ROLES, KEY_USER_ID + " = ? AND " + KEY_ROLE_ID + " = ?", new String[] {String.valueOf(user.getUserId()), String.valueOf(role_id)}); } db.close(); }
public void setAsCurrent() { if (mUri == null) { return; } Cursor cur = mContext.getContentResolver().query(mUri, null, null, null, null); cur.moveToFirst(); int index = cur.getColumnIndex("_id"); String apnId = cur.getString(index); cur.close(); ContentValues values = new ContentValues(); values.put("apn_id", apnId); if (mSlot == -1) { mContext .getContentResolver() .update(Uri.parse("content://telephony/carriers/preferapn"), values, null, null); } else { int simNo = mSlot + 1; mContext .getContentResolver() .update( Uri.parse("content://telephony/carriers_sim" + simNo + "/preferapn"), values, null, null); } }
@Override public Waypoint getLastStatisticsWaypoint(long trackId) { if (trackId < 0) { return null; } Cursor cursor = null; try { String selection = WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS; String[] selectionArgs = new String[] {Long.toString(trackId)}; cursor = getWaypointCursor(null, selection, selectionArgs, WaypointsColumns._ID + " DESC", 1); if (cursor != null && cursor.moveToFirst()) { return createWaypoint(cursor); } } finally { if (cursor != null) { cursor.close(); } } return null; }
// 查找第几集播放进度 public synchronized long getHistroyProgressByID(String sMovieID, int position) { // TODO Auto-generated method stub try { database = pipiDBHelp.getReadableDatabase(); String sql = "select * from " + PipiDBHelp.HISTROY_TABLENAME + " where " + TableName.MovieID + "= '" + sMovieID + "'"; cursor = database.rawQuery(sql, null); if (cursor.moveToNext()) { if (position == cursor.getInt(cursor.getColumnIndex(TableName.MoviePlayPosition))) { long progress = cursor.getLong(cursor.getColumnIndex(TableName.MoviePlayProgress)); Log.i("TAG999", "insertMovieHistroy = " + position + "*******" + progress); return progress; } } } catch (Exception e) { // TODO: handle exception } finally { closeCursor(); } return 0; }
@Override public long getLastTrackPointId(long trackId) { if (trackId < 0) { return -1L; } Cursor cursor = null; try { String selection = TrackPointsColumns._ID + "=(select max(" + TrackPointsColumns._ID + ") from " + TrackPointsColumns.TABLE_NAME + " WHERE " + TrackPointsColumns.TRACKID + "=?)"; String[] selectionArgs = new String[] {Long.toString(trackId)}; cursor = getTrackPointCursor( new String[] {TrackPointsColumns._ID}, selection, selectionArgs, TrackPointsColumns._ID); if (cursor != null && cursor.moveToFirst()) { return cursor.getLong(cursor.getColumnIndexOrThrow(TrackPointsColumns._ID)); } } finally { if (cursor != null) { cursor.close(); } } return -1L; }
// 查找播放当前第几集 public synchronized int getHistroyPositionByID(String sMovieID) { // TODO Auto-generated method stub int position = 0; try { database = pipiDBHelp.getReadableDatabase(); String sql = "select * from " + PipiDBHelp.HISTROY_TABLENAME + " where " + TableName.MovieID + "= '" + sMovieID + "'"; cursor = database.rawQuery(sql, null); if (cursor.moveToNext()) { position = cursor.getInt(cursor.getColumnIndex(TableName.MoviePlayPosition)); if (position < 0) position = 0; ; } } catch (Exception e) { // TODO: handle exception } finally { closeCursor(); } return position; }
@Override public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // TODO Auto-generated method stub // check uri // first 通过SQLiteQueryBuilder,设置数据库查询的信息.Uri有两种情况,一种是collect, // 一种已经指定某个item,两者需要区别对待,item将获取_ID,并在where中增加一个匹配条件. SQLiteQueryBuilder dbQuery = new SQLiteQueryBuilder(); final int match = sUriMatch.match(uri); switch (match) { case HISTORY_COLLECTION_URI_INDICATOR: dbQuery.setTables(ChatHistoryTable.TABLE_NAME); dbQuery.setProjectionMap(sHistoryProjectionMap); break; case HISTORY_ITEM_URI_INDICATION: dbQuery.setTables(ChatHistoryTable.TABLE_NAME); dbQuery.setProjectionMap(sHistoryProjectionMap); dbQuery.appendWhere(ChatHistoryTable._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknow uri=" + uri); } // second v 对排序进行缺省设置 // String order = TextUtils.isEmpty(sortOrder) ? HistoryTable.DEFAULE_SORT_ORDER : sortOrder; SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // third start query final Cursor c = dbQuery.query(db, projection, selection, selectionArgs, null, null, sortOrder); // fourth 向系统注册通知:观察所要查询的数据,即Uri对应的数据是否发生变化 // 开发者通过provider接口获取数据,可通过通知获知数据已经发生变更 if (c != null) { c.setNotificationUri(mContentResolver, ChatHistoryTable.CONTENT_URI); } return c; }
public Indices(Cursor cursor) { type = cursor.getColumnIndex(Suggestions.TYPE); title = cursor.getColumnIndex(Suggestions.TITLE); summary = cursor.getColumnIndex(Suggestions.SUMMARY); icon = cursor.getColumnIndex(Suggestions.ICON); extra_id = cursor.getColumnIndex(Suggestions.EXTRA_ID); }
private void updateCalendarInfoFromListItem(int position) { Cursor cursor = (Cursor) calendarListView.getItemAtPosition(position); currentSelection.setDisplayName(cursor.getString(0)); currentSelection.setId(cursor.getInt(1)); updateListener.onUpdate(getCurrentSelection()); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); overridePendingTransition(R.anim.pull_in_from_left, R.anim.pull_out_to_left); setContentView(R.layout.pass); close = (Button) findViewById(R.id.pass_cl); login = (Button) findViewById(R.id.pass_yes); forget = (Button) findViewById(R.id.pass_no); uName = (EditText) findViewById(R.id.pass_username); pass = (EditText) findViewById(R.id.pass_pwd); tView = (TextView) findViewById(R.id.pass_title); close.setOnClickListener(this); login.setOnClickListener(this); forget.setOnClickListener(this); db.open(); Cursor mCursor = db.getAllRecords(); mCursor.moveToFirst(); rName = mCursor.getString(1); if (mCursor.getCount() > 0) { uName.setClickable(false); uName.setBackgroundResource(R.drawable.keypad1); } db.close(); tView.setText(rName + " @ MoneyMan"); uName.setText(rName); } // end onCreate()
@Override protected void executeBadge(int badgeCount) throws ShortcutBadgeException { Uri mUri = Uri.parse(CONTENT_URI); ContentResolver contentResolver = mContext.getContentResolver(); Cursor cursor = null; try { cursor = contentResolver.query( mUri, CONTENT_PROJECTION, "package=?", new String[] {getContextPackageName()}, null); if (cursor != null) { String entryActivityName = getEntryActivityName(); boolean entryActivityExist = false; while (cursor.moveToNext()) { int id = cursor.getInt(0); ContentValues contentValues = getContentValues(badgeCount, false); contentResolver.update(mUri, contentValues, "_id=?", new String[] {String.valueOf(id)}); if (entryActivityName.equals(cursor.getString(cursor.getColumnIndex("class")))) { entryActivityExist = true; } } if (!entryActivityExist) { ContentValues contentValues = getContentValues(badgeCount, true); contentResolver.insert(mUri, contentValues); } } } finally { CloseHelper.close(cursor); } }
/** @inheritdoc */ @Override public void readEntity(Cursor cursor, Category entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setTitle(cursor.getString(offset + 1)); entity.setDescription(cursor.getString(offset + 2)); entity.setImage(cursor.getString(offset + 3)); }
public static ArrayList<Long> getCalendarList(Context c) { ArrayList<Long> calendarIdList = new ArrayList<Long>(); try { Cursor cur = c.getApplicationContext() .getContentResolver() .query( CalendarContract.Calendars.CONTENT_URI, CALENDAR_PROJECTION, selection, selectionArgs, null); while (cur.moveToNext()) { long calID = 0; // Get the field values calID = cur.getLong(PROJECTION_ID_INDEX); calendarIdList.add(calID); } } catch (SecurityException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return calendarIdList; }
// TODO: if uploadingComplete() when activity backgrounded, won't work. public void uploadingComplete(ArrayList<String> result) { int resultSize = result.size(); boolean success = false; if (resultSize == totalCount) { Toast.makeText( this, getString(R.string.upload_all_successful, totalCount), Toast.LENGTH_SHORT) .show(); success = true; } else { String s = totalCount - resultSize + " of " + totalCount; Toast.makeText(this, getString(R.string.upload_some_failed, s), Toast.LENGTH_LONG).show(); } Intent in = new Intent(); in.putExtra(GlobalConstants.KEY_SUCCESS, success); setResult(RESULT_OK, in); // for each path, update the status FileDbAdapter fda = new FileDbAdapter(this); fda.open(); for (int i = 0; i < resultSize; i++) { Cursor c = fda.fetchFilesByPath(result.get(i), null); if (c != null) { if (c.getString(c.getColumnIndex(FileDbAdapter.KEY_STATUS)) .equals(FileDbAdapter.STATUS_COMPLETED)) fda.updateFile(result.get(i), FileDbAdapter.STATUS_SUBMITTED, null); } } fda.close(); finish(); }
@Override public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Uisng SQLiteQueryBuilder instead of query() method SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); // Check if the caller has requested a column which does not exists checkColumns(projection); // Set the table queryBuilder.setTables(DontForgetMomDbInformation.Trip.CONTENT_PROVIDER_TABLE_NAME); int uriType = sURIMatcher.match(uri); switch (uriType) { case TRIPS: break; case TRIP_ID: // Adding the ID to the original query queryBuilder.appendWhere( DontForgetMomDbInformation.Trip._ID + "=" + uri.getLastPathSegment()); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); // Make sure that potential listeners are getting notified cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; }
public String getDDESetting(String mode, String setting) { String result = ""; // Select All Query String selectQuery = "SELECT " + setting + " FROM " + TABLE_DDE_SETTINGS + " WHERE " + KEY_MODE + " = '" + mode + "'"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { result = cursor.getString(0); } cursor.close(); return result; }