Java Code Examples for android.database.Cursor#moveToLast()
The following examples show how to use
android.database.Cursor#moveToLast() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TvContractUtils.java From ChannelSurfer with MIT License | 6 votes |
public static long getLastProgramEndTimeMillis(ContentResolver resolver, Uri channelUri) { Uri uri = TvContract.buildProgramsUriForChannel(channelUri); String[] projection = {Programs.COLUMN_END_TIME_UTC_MILLIS}; Cursor cursor = null; try { // TvProvider returns programs chronological order by default. cursor = resolver.query(uri, projection, null, null, null); if (cursor == null || cursor.getCount() == 0) { return 0; } cursor.moveToLast(); return cursor.getLong(0); } catch (Exception e) { Log.w(TAG, "Unable to get last program end time for " + channelUri, e); } finally { if (cursor != null) { cursor.close(); } } return 0; }
Example 2
Source File: NoteDBHelper.java From nono-android with GNU General Public License v3.0 | 6 votes |
public List<NoteAllArray> getHistoryNote() { List<NoteAllArray> list = new ArrayList<>(); synchronized (dbAdapter){ dbAdapter.open(); Cursor cr=dbAdapter.getAllTitles(); if(cr!=null&&cr.moveToLast()) { do { list.add(new NoteAllArray( cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_TITLE)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_CONTENT)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_GROUP)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_DATE)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_TIME)), cr.getLong(cr.getColumnIndex(NoteDBAdapter.KEY_ROWID)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_IS_ON_CLOUD)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_UUID)) )); }while (cr.moveToPrevious()); } dbAdapter.close(); } return list; }
Example 3
Source File: SellsInfo.java From Android-POS with MIT License | 6 votes |
public int getLastSellItemCode(){ this.Open(); try { Cursor cursor = database.query(dbHelper.TABLE_SELL_NAME, null, null, null, null, null, null); cursor.moveToLast(); int temp = cursor.getCount(); String data[] = cursor.getString(cursor.getColumnIndex(dbHelper.COL_SELL_SELLS_CODE)).split("in-"); cursor.close(); this.Close(); if (temp > 0) { return Integer.parseInt(data[1]); } else { return 0; } } catch (Exception e) { return 0; } }
Example 4
Source File: PictureTask.java From PictureChooseLib with Apache License 2.0 | 6 votes |
private static List<String> getRecentlyPicturePath(ContentResolver mContentResolver,int maxCount) { Uri EXTERNAL_CONTENT_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; String MIME_TYPE = MediaStore.Images.Media.MIME_TYPE; String DATA = MediaStore.Images.Media.DATA; Cursor cursor = mContentResolver.query(EXTERNAL_CONTENT_URI, new String[]{DATA}, MIME_TYPE + "=? or " + MIME_TYPE + "=? or " + MIME_TYPE + "=?", new String[]{"image/jpg", "image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED); if(cursor == null){ return null; } List<String> recentlyPictures = new ArrayList<String>(); if (cursor.moveToLast()) { while (true) { String path = cursor.getString(0); if(!TextUtils.isEmpty(path)){ recentlyPictures.add(path); } if (recentlyPictures.size() >= maxCount || !cursor.moveToPrevious()) { break; } } } Utils.closeQuietly(cursor); return recentlyPictures; }
Example 5
Source File: NoteDBHelper.java From nono-android with GNU General Public License v3.0 | 6 votes |
public NoteAllArray getNoteById(long id){ synchronized (dbAdapter){ dbAdapter.open(); Cursor cr=dbAdapter.getNoteById(id); if(cr!=null&&cr.moveToLast()) { return new NoteAllArray( cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_TITLE)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_CONTENT)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_GROUP)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_DATE)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_TIME)), cr.getLong(cr.getColumnIndex(NoteDBAdapter.KEY_ROWID)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_IS_ON_CLOUD)), cr.getString(cr.getColumnIndex(NoteDBAdapter.KEY_UUID)) ); } dbAdapter.close(); } return null; }
Example 6
Source File: CameraLauncher.java From reader with MIT License | 6 votes |
/** * Used to find out if we are in a situation where the Camera Intent adds to images * to the content store. If we are using a FILE_URI and the number of images in the DB * increases by 2 we have a duplicate, when using a DATA_URL the number is 1. * * @param type FILE_URI or DATA_URL */ private void checkForDuplicateImage(int type) { int diff = 1; Uri contentStore = whichContentStore(); Cursor cursor = queryImgDB(contentStore); int currentNumOfImages = cursor.getCount(); if (type == FILE_URI && this.saveToPhotoAlbum) { diff = 2; } // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL if ((currentNumOfImages - numPics) == diff) { cursor.moveToLast(); int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))); if (diff == 2) { id--; } Uri uri = Uri.parse(contentStore + "/" + id); this.cordova.getActivity().getContentResolver().delete(uri, null, null); cursor.close(); } }
Example 7
Source File: ContentProviderTest.java From droitatedDB with Apache License 2.0 | 6 votes |
@Test public void getCurrentReturnsLastIfAfterLast() { Single s1 = new Single("s1"); Single s2 = new Single("s2"); EntityService<Single> service = entityService(Single.class); service.save(s1); service.save(s2); Cursor cursor = getSingleCursor(); ObjectCursor<Single> objectCursor = CursorUtil.getObjectCursor(cursor); cursor.moveToLast(); cursor.moveToNext(); assertThat(objectCursor.getCurrent()).isEqualTo(objectCursor.getLast()); }
Example 8
Source File: CameraLauncher.java From cordova-android-chromeview with Apache License 2.0 | 6 votes |
/** * Used to find out if we are in a situation where the Camera Intent adds to images * to the content store. If we are using a FILE_URI and the number of images in the DB * increases by 2 we have a duplicate, when using a DATA_URL the number is 1. * * @param type FILE_URI or DATA_URL */ private void checkForDuplicateImage(int type) { int diff = 1; Uri contentStore = whichContentStore(); Cursor cursor = queryImgDB(contentStore); int currentNumOfImages = cursor.getCount(); if (type == FILE_URI && this.saveToPhotoAlbum) { diff = 2; } // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL if ((currentNumOfImages - numPics) == diff) { cursor.moveToLast(); int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))); if (diff == 2) { id--; } Uri uri = Uri.parse(contentStore + "/" + id); this.cordova.getActivity().getContentResolver().delete(uri, null, null); } }
Example 9
Source File: LevelInfoDataSource.java From sopa with Apache License 2.0 | 5 votes |
public LevelInfo getLastUnlocked() { Cursor cursor = database.query(TABLE_LEVEL_INFO, allColumns, COLUMN_LOCKED + " = 0", null, null, null, COLUMN_LOCKED + " DESC"); cursor.moveToLast(); LevelInfo levelInfo = cursorToLevelInfo(cursor); cursor.close(); return levelInfo; }
Example 10
Source File: MainActivity.java From android-tv-launcher with MIT License | 5 votes |
private String getUrlDataFromDB() { Cursor cursor = mSQLiteDataBase.rawQuery("SELECT url_data FROM my_url_data", null); cursor.moveToLast(); String a = cursor.getString(cursor.getColumnIndex("url_data")); // String s = cursor.getString(2); return a; }
Example 11
Source File: NoteLabelDBAdapter.java From nono-android with GNU General Public License v3.0 | 5 votes |
public List<String> getHistoryLabelNames() { List<String> list = new ArrayList<>(); Cursor c = db.query(TABLE,new String[]{KEY_LABEL},null,null,null,null,null); if(c!=null && c.moveToLast()){ do{ list.add( c.getString(c.getColumnIndex(KEY_LABEL)) ); }while (c.moveToPrevious()); } return list; }
Example 12
Source File: FavoriteDao.java From GreenDamFileExploere with Apache License 2.0 | 5 votes |
public Favorite findFavoriteByFullPath(String canonicalPath) { Favorite favorite = null; SQLiteDatabase db = null; Cursor c = null; try { db = mAppNameDbHelper.openDatabase(); c = db.rawQuery(SQL_FIND_FAVORITE_BY_PATH, new String[] { canonicalPath }); if (c.moveToLast()) { String path = c.getString(c.getColumnIndex("path")); String name = c.getString(c.getColumnIndex("name")); String appName = c.getString(c.getColumnIndex("app_name")); int fileType = c.getInt(c.getColumnIndex("file_type")); long date = c.getLong(c.getColumnIndex("favorite_time")); long size = c.getLong(c.getColumnIndex("size")); String extra = c.getString(c.getColumnIndex("extra")); favorite = new Favorite(path, name, appName, fileType, date, size, extra); } } catch (SQLException e) { e.printStackTrace(); } finally { mAppNameDbHelper.closeDatabase(); if (c != null) { c.close(); } } return favorite; }
Example 13
Source File: SosContacterDAO.java From SmartOrnament with Apache License 2.0 | 5 votes |
public int getMaxId(){ Cursor cursor=db.rawQuery("select max(_id) from tb_sos",null); while (cursor.moveToLast()){ return cursor.getInt(0); } return 0; }
Example 14
Source File: NoteGroupDBHelper.java From nono-android with GNU General Public License v3.0 | 5 votes |
public List<NoteAllArray> getNoteArrayByTag(String tag){ List<Long > noteIdList = new ArrayList<>(); List<NoteAllArray> noteAllArrayList = new ArrayList<>(); synchronized (dbAdapter){ dbAdapter.open(); Cursor cr = dbAdapter.getAll(); if (cr != null && cr.moveToLast() && cr.getCount() > 0) { int group_json_index = cr.getColumnIndex(NoteGroupDBAdapter.KEY_GROUPJSON); int note_id_index = cr.getColumnIndex(NoteGroupDBAdapter.KEY_NOTEID); do{ String groupJson = cr.getString(group_json_index); if(groupJson.contains(tag)){ noteIdList.add(cr.getLong(note_id_index)); } }while (cr.moveToPrevious()); } dbAdapter.close(); } for (long noteId: noteIdList) { noteAllArrayList.add( NoteDBHelper.getInstance().getNoteById(noteId) ); } return noteAllArrayList; }
Example 15
Source File: DatabaseHelper.java From IdeaTrackerPlus with MIT License | 4 votes |
/** * Get the last (and bigger) order index of the given tab item list * * @param tabNumber * @return */ public int getLastOrderIndex(int tabNumber) { int lastOrderIndex = -1; if (!DataEntry.TABLE_NAME.equals("[]")) { SQLiteDatabase db = this.getReadableDatabase(); // Only the text and priority will be read String[] projection = {DataEntry.COLUMN_NAME_ENTRY_ID}; // How you want the results sorted in the resulting Cursor String sortOrder = DataEntry.COLUMN_NAME_ENTRY_ID + " ASC"; //Define the where condition String where = ""; String[] values = {}; switch (tabNumber) { case 1: where = "later=? and done=? and temp=?"; values = new String[]{"0", "0", "0"}; break; case 2: where = "later=? and temp=?"; values = new String[]{"1", "0"}; break; case 3: where = "done=? and temp=?"; values = new String[]{"1", "0"}; break; } Cursor cursor = null; try { cursor = db.query( DataEntry.TABLE_NAME, // The table to query projection, // The columns to return where, // The columns for the WHERE clause values, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups sortOrder // The sort order ); if (cursor.moveToLast()) { lastOrderIndex = cursor.getInt(cursor.getColumnIndex(DataEntry.COLUMN_NAME_ENTRY_ID)); } } finally { if (cursor != null) { cursor.close(); } } } return lastOrderIndex; }
Example 16
Source File: MessageSearchTask.java From Pix-Art-Messenger with GNU General Public License v3.0 | 4 votes |
@Override public void run() { long startTimestamp = SystemClock.elapsedRealtime(); Cursor cursor = null; try { final HashMap<String, Conversational> conversationCache = new HashMap<>(); final List<Message> result = new ArrayList<>(); cursor = xmppConnectionService.databaseBackend.getMessageSearchCursor(term); long dbTimer = SystemClock.elapsedRealtime(); if (isCancelled) { Log.d(Config.LOGTAG, "canceled search task"); return; } if (cursor != null && cursor.getCount() > 0) { cursor.moveToLast(); final int indexBody = cursor.getColumnIndex(Message.BODY); final int indexOob = cursor.getColumnIndex(Message.OOB); final int indexConversation = cursor.getColumnIndex(Message.CONVERSATION); final int indexAccount = cursor.getColumnIndex(Conversation.ACCOUNT); final int indexContact = cursor.getColumnIndex(Conversation.CONTACTJID); final int indexMode = cursor.getColumnIndex(Conversation.MODE); do { if (isCancelled) { Log.d(Config.LOGTAG, "canceled search task"); return; } final String body = cursor.getString(indexBody); final boolean oob = cursor.getInt(indexOob) > 0; if (MessageUtils.treatAsDownloadable(body, oob)) { continue; } final String conversationUuid = cursor.getString(indexConversation); Conversational conversation = conversationCache.get(conversationUuid); if (conversation == null) { String accountUuid = cursor.getString(indexAccount); String contactJid = cursor.getString(indexContact); int mode = cursor.getInt(indexMode); conversation = findOrGenerateStub(conversationUuid, accountUuid, contactJid, mode); conversationCache.put(conversationUuid, conversation); } Message message = IndividualMessage.fromCursor(cursor, conversation); result.add(message); } while (cursor.moveToPrevious()); } long stopTimestamp = SystemClock.elapsedRealtime(); Log.d(Config.LOGTAG, "found " + result.size() + " messages in " + (stopTimestamp - startTimestamp) + "ms" + " (db was " + (dbTimer - startTimestamp) + "ms)"); onSearchResultsAvailable.onSearchResultsAvailable(term, result); } catch (Exception e) { Log.d(Config.LOGTAG, "exception while searching ", e); } finally { if (cursor != null) { cursor.close(); } } }
Example 17
Source File: ImageLoader.java From SSForms with GNU General Public License v3.0 | 4 votes |
@Override public void run() { Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Media.DATE_ADDED); if (cursor == null) { listener.onFailed(new NullPointerException()); return; } List<Image> temp = new ArrayList<>(cursor.getCount()); Map<String, Folder> folderMap = null; if (isFolderMode) { folderMap = new HashMap<>(); } if (cursor.moveToLast()) { do { long id = cursor.getLong(cursor.getColumnIndex(projection[0])); String name = cursor.getString(cursor.getColumnIndex(projection[1])); String path = cursor.getString(cursor.getColumnIndex(projection[2])); String bucket = cursor.getString(cursor.getColumnIndex(projection[3])); File file = makeSafeFile(path); if (file != null && file.exists()) { Image image = new Image(id, name, path, false); temp.add(image); if (folderMap != null) { Folder folder = folderMap.get(bucket); if (folder == null) { folder = new Folder(bucket); folderMap.put(bucket, folder); } folder.getImages().add(image); } } } while (cursor.moveToPrevious()); } cursor.close(); /* Convert HashMap to ArrayList if not null */ List<Folder> folders = null; if (folderMap != null) { folders = new ArrayList<>(folderMap.values()); } listener.onImageLoaded(temp, folders); }
Example 18
Source File: DbMigration.java From LibreTasks with Apache License 2.0 | 4 votes |
/** * Modify the actions by replacing the username and password attributes into user account (this is * done for possible multi-account support and supporting different authentication methods like * OAuth). Also retrieves username and password from existing rules and the latest entry is used * if there are multiple actions that has username and password. * * @param db * the database instance to work with * @param appName * the name of the application associated with the action * @param actionName * the name of the action * @param usernameParamName * the action's parameter name for username * @param passwordParamName * the action's parameter name for password * @param userAccountParamName * the action's parameter name for user account * @param dataTypeIdAccount * primary key id for UserAccount datatype */ private static void modifyActionToSupportUserAccount(SQLiteDatabase db, String appName, String actionName, String usernameParamName, String passwordParamName, String userAccountParamName, long dataTypeIdAccount) { // Get the App ID RegisteredAppDbAdapter appDbAdapter = new RegisteredAppDbAdapter(db); Cursor cursor = appDbAdapter.fetchAll(appName, "", true); cursor.moveToFirst(); long appID = CursorHelper.getLongFromCursor(cursor, RegisteredAppDbAdapter.KEY_APPID); cursor.close(); // Get the Action ID RegisteredActionDbAdapter actionDbAdapter = new RegisteredActionDbAdapter(db); cursor = actionDbAdapter.fetchAll(actionName, appID); cursor.moveToFirst(); long actionId = CursorHelper.getLongFromCursor(cursor, RegisteredActionDbAdapter.KEY_ACTIONID); cursor.close(); RegisteredActionParameterDbAdapter actionParameterDbAdapter = new RegisteredActionParameterDbAdapter(db); /* * Modify the username parameter to user account. Update was used instead of delete then insert * to have the user account parameter appear on the top position when {@code * FactoryActions.buildUIFromAction} is called. */ cursor = actionParameterDbAdapter.fetchAll(usernameParamName, actionId, null); cursor.moveToFirst(); long paramID = CursorHelper.getLongFromCursor(cursor, RegisteredActionParameterDbAdapter.KEY_ACTIONPARAMETERID); actionParameterDbAdapter.update(paramID, userAccountParamName, null, dataTypeIdAccount); cursor.close(); /* * Get the username from existing rules and set it to the application. Use the last entry if * there are multiple actions in the database. */ RuleActionParameterDbAdapter ruleActionParamDb = new RuleActionParameterDbAdapter(db); cursor = ruleActionParamDb.fetchAll(null, paramID, null); if (cursor.moveToLast()) { String username = CursorHelper.getStringFromCursor(cursor, RuleActionParameterDbAdapter.KEY_RULEACTIONPARAMETERDATA); appDbAdapter.update(appID, null, null, null, null, username, null); } // No need to delete since paramID is now user account cursor.close(); // Remove the password parameter cursor = actionParameterDbAdapter.fetchAll(passwordParamName, actionId, null); cursor.moveToFirst(); paramID = CursorHelper.getLongFromCursor(cursor, RegisteredActionParameterDbAdapter.KEY_ACTIONPARAMETERID); actionParameterDbAdapter.delete(paramID); cursor.close(); /* * Get the password from existing rules and set it to the application. Use the last entry if * there are multiple gmail send actions in the database. And remove all rule action password * parameter entries. */ cursor = ruleActionParamDb.fetchAll(null, paramID, null); if (cursor.moveToLast()) { String password = CursorHelper.getStringFromCursor(cursor, RuleActionParameterDbAdapter.KEY_RULEACTIONPARAMETERDATA); appDbAdapter.update(appID, null, null, null, null, null, password); do { ruleActionParamDb.delete(CursorHelper.getLongFromCursor(cursor, RuleActionParameterDbAdapter.KEY_RULEACTIONPARAMETERID)); } while (cursor.moveToPrevious()); } cursor.close(); }
Example 19
Source File: SendTest.java From medical-data-android with GNU General Public License v3.0 | 4 votes |
@Override protected Boolean doInBackground(Context... params) { Context context = params[0]; SharedPreferences settings = context.getSharedPreferences(Variables.PREFS_NAME, Context.MODE_PRIVATE); int local_tests = settings.getInt("local_tests", 0); Log.v(TAG, "Tests: " + String.valueOf(local_tests)); if (local_tests > 0 && canConnect(context, settings)) { try { MongoClientURI mongoClientURI = new MongoClientURI(Variables.mongo_uri); MongoClient mongoClient = new MongoClient(mongoClientURI); MongoDatabase dbMongo = mongoClient.getDatabase(mongoClientURI.getDatabase()); MongoCollection<Document> coll = dbMongo.getCollection("mobileTests"); boolean isFemale = settings.getBoolean("gender", true); ObjectId user_id = new ObjectId(settings.getString("user_id", "")); Cursor c = getSQLCursor(context, local_tests); c.moveToLast(); for (; local_tests > 0; local_tests--) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(FeedTestContract.dateWithTimezone(c.getString(0))); String date_string = format.format(cal.getTime()); Log.v(TAG, date_string); Date original_date = format.parse(date_string); DateFormat format_day = new SimpleDateFormat("yyyy-MM-dd"); Date today_date = format_day.parse(date_string); Log.v(TAG, today_date.toString()); cal.setTime(today_date); cal.add(Calendar.DATE, 1); // number of days to add Date tomorrow_date = cal.getTime(); // dt is now the new date Log.v(TAG, tomorrow_date.toString()); Document document = getDoc(c, user_id, isFemale, original_date); MongoCursor<Document> it = coll.find(and(and(lt("date", tomorrow_date), gte("date", today_date)), eq("user_id", user_id))).limit(1).iterator(); if (it.hasNext()) { // replace the entire document except for the _id field coll.replaceOne(new Document("_id", it.next().getObjectId("_id")), document); } else { coll.insertOne(document); } c.moveToPrevious(); } mongoClient.close(); deleteSQLEntries(context); } catch (Exception e) { Log.v(TAG, e.toString()); } Variables.saveLocalTests(TAG, settings, local_tests); } boolean start = (local_tests > 0); Log.v(TAG, "Flag: " + (start ? "enabled" : "disabled") + ", Tests: " + String.valueOf(local_tests)); return start; }
Example 20
Source File: LocalyticsSession.java From ExtensionsPack with MIT License | 4 votes |
/** * @param provider The database to query. Cannot be null. * @return The {@link SessionsDbColumns#_ID} of the currently open session or {@code null} if no session is open. The * definition of "open" is whether a session has been opened without a corresponding close event. */ /* package */static Long getOpenSessionId(final LocalyticsProvider provider) { /* * Get the ID of the last session */ final Long sessionId; { Cursor sessionsCursor = null; try { /* * Query all sessions sorted by session ID, which guarantees to obtain the last session regardless of whether * the system clock changed. */ sessionsCursor = provider.query(SessionsDbColumns.TABLE_NAME, PROJECTION_GET_OPEN_SESSION_ID_SESSION_ID, null, null, SessionsDbColumns._ID); if (sessionsCursor.moveToLast()) { sessionId = Long.valueOf(sessionsCursor.getLong(sessionsCursor.getColumnIndexOrThrow(SessionsDbColumns._ID))); } else { return null; } } finally { if (null != sessionsCursor) { sessionsCursor.close(); sessionsCursor = null; } } } /* * See if the session has a close event. */ Cursor eventsCursor = null; try { eventsCursor = provider.query(EventsDbColumns.TABLE_NAME, PROJECTION_GET_OPEN_SESSION_ID_EVENT_COUNT, SELECTION_GET_OPEN_SESSION_ID_EVENT_COUNT, new String[] { sessionId.toString(), CLOSE_EVENT }, null); if (eventsCursor.moveToFirst()) { if (0 == eventsCursor.getInt(0)) { return sessionId; } } } finally { if (null != eventsCursor) { eventsCursor.close(); eventsCursor = null; } } return null; }