List of usage examples for android.database Cursor getInt
int getInt(int columnIndex);
From source file:com.hichinaschool.flashcards.libanki.Note.java
public void load() { Cursor cursor = null; try {/*from w w w . j av a 2s . co m*/ cursor = mCol.getDb().getDatabase().rawQuery( "SELECT guid, mid, mod, usn, tags, flds, flags, data FROM notes WHERE id = " + mId, null); if (!cursor.moveToFirst()) { Log.w(AnkiDroidApp.TAG, "Notes.load(): No result from query."); return; } mGuId = cursor.getString(0); mMid = cursor.getLong(1); mMod = cursor.getLong(2); mUsn = cursor.getInt(3); mFields = Utils.splitFields(cursor.getString(5)); mTags = mCol.getTags().split(cursor.getString(4)); mFlags = cursor.getInt(6); mData = cursor.getString(7); mScm = mCol.getScm(); } finally { if (cursor != null) { cursor.close(); } } mModel = mCol.getModels().get(mMid); mFMap = mCol.getModels().fieldMap(mModel); }
From source file:com.amazonaws.mobileconnectors.pinpoint.internal.event.EventRecorder.java
JSONArray getBatchOfEvents(final Cursor cursor, final List<Integer> idsToDeletes, final List<Integer> sizeToDeletes) { final JSONArray eventArray = new JSONArray(); long currentRequestSize = 0; long eventLength; final long maxRequestSize = pinpointContext.getConfiguration().optLong(KEY_MAX_SUBMISSION_SIZE, DEFAULT_MAX_SUBMISSION_SIZE); JSONObject json = translateFromCursor(cursor); idsToDeletes.add(cursor.getInt(EventTable.COLUMN_INDEX.ID.getValue())); sizeToDeletes.add(cursor.getInt(EventTable.COLUMN_INDEX.ID.getValue())); if (json != null) { eventLength = json.length();// w ww .j av a2 s.co m currentRequestSize += eventLength; eventArray.put(json); } while (cursor.moveToNext()) { json = translateFromCursor(cursor); idsToDeletes.add(cursor.getInt(EventTable.COLUMN_INDEX.ID.getValue())); sizeToDeletes.add(cursor.getInt(EventTable.COLUMN_INDEX.ID.getValue())); if (json != null) { eventLength = json.length(); currentRequestSize += eventLength; eventArray.put(json); if (currentRequestSize > maxRequestSize) { break; } } } return eventArray; }
From source file:com.ichi2.libanki.Note.java
public void load() { Cursor cursor = null; try {/* w ww. j a va2 s. c o m*/ cursor = mCol.getDb().getDatabase().rawQuery( "SELECT guid, mid, mod, usn, tags, flds, flags, data FROM notes WHERE id = " + mId, null); if (!cursor.moveToFirst()) { throw new RuntimeException("Notes.load(): No result from query for note " + mId); } mGuId = cursor.getString(0); mMid = cursor.getLong(1); mMod = cursor.getLong(2); mUsn = cursor.getInt(3); mTags = mCol.getTags().split(cursor.getString(4)); mFields = Utils.splitFields(cursor.getString(5)); mFlags = cursor.getInt(6); mData = cursor.getString(7); mModel = mCol.getModels().get(mMid); mFMap = mCol.getModels().fieldMap(mModel); mScm = mCol.getScm(); } finally { if (cursor != null) { cursor.close(); } } }
From source file:com.ptts.sync.SyncAdapter.java
/** * Read JSON from an input stream, storing it into the content provider. * * <p>This is where incoming data is persisted, committing the results of a sync. In order to * minimize (expensive) disk operations, we compare incoming data with what's already in our * database, and compute a merge. Only changes (insert/update/delete) will result in a database * write.// ww w . ja v a 2 s . c o m * * <p>As an additional optimization, we use a batch operation to perform all database writes at * once. * * <p>Merge strategy: * 1. Get cursor to all items in feed<br/> * 2. For each item, check if it's in the incoming data.<br/> * a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform * database UPDATE.<br/> * b. NO: Schedule DELETE from database.<br/> * (At this point, incoming database only contains missing items.)<br/> * 3. For any items remaining in incoming list, ADD to database. */ public void updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException, JSONException, RemoteException, OperationApplicationException, ParseException { final FeedParserJson feedParser = new FeedParserJson(); final ContentResolver contentResolver = getContext().getContentResolver(); Log.i(TAG, "Parsing stream as Json feed"); final List<FeedParserJson.Entry> entries = feedParser.parse(stream); Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Build hash table of incoming entries HashMap<String, FeedParserJson.Entry> entryMap = new HashMap<String, FeedParserJson.Entry>(); for (FeedParserJson.Entry e : entries) { entryMap.put(e.id, e); } // Get list of all items Log.i(TAG, "Fetching local entries for merge"); Uri uri = FeedContract.Entry.CONTENT_URI; // Get all entries Cursor c = contentResolver.query(uri, PROJECTION, null, null, null); assert c != null; Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution..."); // Find stale data int id; String entryId; String name; String start; String end; String stops; while (c.moveToNext()) { syncResult.stats.numEntries++; id = c.getInt(COLUMN_ID); entryId = c.getString(COLUMN_ENTRY_ID); name = c.getString(COLUMN_NAME); start = c.getString(COLUMN_START); end = c.getString(COLUMN_END); stops = c.getString(COLUMN_STOPS); Log.i("STOPS FROM PROJECTION", stops); FeedParserJson.Entry match = entryMap.get(entryId); if (match != null) { // Entry exists. Remove from entry map to prevent insert later. entryMap.remove(entryId); // Check to see if the entry needs to be updated Uri existingUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)) .build(); if ((match.name != null && !match.name.equals(name)) || (match.start != null && !match.start.equals(start)) || (match.stops != null && !match.stops.equals(stops)) || (match.end != end)) { Log.i("STOPS FROM HASHMAP", match.stops); if (!match.stops.equals(stops)) { Log.i("COMPARING PROJECTION " + match.stops + " & HASHMAP " + stops, "The two aren't equal"); } else { Log.i("COMPARING PROJECTION & HASHMAP", "The two are equal"); } // Update existing record Log.i(TAG, "Scheduling update: " + existingUri); batch.add(ContentProviderOperation.newUpdate(existingUri) .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, entryId) .withValue(FeedContract.Entry.COLUMN_NAME_NAME, name) .withValue(FeedContract.Entry.COLUMN_NAME_START, start) .withValue(FeedContract.Entry.COLUMN_NAME_END, end) .withValue(FeedContract.Entry.COLUMN_NAME_STOPS, stops).build()); syncResult.stats.numUpdates++; } else { Log.i(TAG, "No action: " + existingUri); } } else { // Entry doesn't exist. Remove it from the database. Uri deleteUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build(); Log.i(TAG, "Scheduling delete: " + deleteUri); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); syncResult.stats.numDeletes++; } } c.close(); // Add new items for (FeedParserJson.Entry e : entryMap.values()) { Log.i(TAG, "Scheduling insert: entry_id=" + e.id); batch.add(ContentProviderOperation.newInsert(FeedContract.Entry.CONTENT_URI) .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, e.id) .withValue(FeedContract.Entry.COLUMN_NAME_NAME, e.name) .withValue(FeedContract.Entry.COLUMN_NAME_START, e.start) .withValue(FeedContract.Entry.COLUMN_NAME_END, e.end) .withValue(FeedContract.Entry.COLUMN_NAME_STOPS, e.stops).build()); syncResult.stats.numInserts++; } Log.i(TAG, "Merge solution ready. Applying batch update"); mContentResolver.applyBatch(FeedContract.CONTENT_AUTHORITY, batch); mContentResolver.notifyChange(FeedContract.Entry.CONTENT_URI, // URI where data was modified null, // No local observer false); // IMPORTANT: Do not sync to network // This sample doesn't support uploads, but if *your* code does, make sure you set // syncToNetwork=false in the line above to prevent duplicate syncs. }
From source file:mp.teardrop.Song.java
/** * Populate fields with data from the supplied cursor. * * @param cursor Cursor queried with FILLED_PROJECTION projection *///w w w. j av a 2 s .c o m public void populate(Cursor cursor) { id = cursor.getLong(0); path = cursor.getString(1); title = cursor.getString(2); album = cursor.getString(3); artist = cursor.getString(4); albumId = cursor.getLong(5); artistId = cursor.getLong(6); //duration = cursor.getLong(7); trackNumber = cursor.getInt(8); }
From source file:com.nononsenseapps.feeder.db.FeedItemSQL.java
/** * Convert information from the database into a FeedItem object. */// w ww. ja v a2 s . c o m public FeedItemSQL(final Cursor cursor) { // Indices expected to match order in FIELDS! this.id = cursor.getLong(0); this.title = cursor.getString(1); this.description = cursor.getString(2); this.plaintitle = cursor.getString(3); this.plainsnippet = cursor.getString(4); this.imageurl = cursor.getString(5); this.link = cursor.getString(6); this.author = cursor.getString(7); setPubDate(cursor.getString(8)); this.unread = cursor.getInt(9); this.feed_id = cursor.getLong(10); this.tag = cursor.getString(11); this.enclosurelink = cursor.getString(12); this.feedtitle = cursor.getString(13); this.notified = cursor.getInt(14); this.json = cursor.getString(15); this.guid = cursor.getString(16); }
From source file:org.droidpres.activity.TransferActivity.java
private void setBtExportEnable() { Cursor cur = mDataBase.rawQuery("select count(*) + (select count(*) from " + DB.TABLE_LOCATION + ") from " + DB.TABLE_DOCUMENT + " where docstate = " + Const.DOCSTATE_PREPARE_SEND, null); if (cur.moveToFirst()) { boolean flag = cur.getInt(0) > 0; mBtExport.setEnabled(flag);/*from w w w . ja v a 2s. co m*/ } else { mBtExport.setEnabled(false); } cur.close(); }
From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java
public void notifyWeather() { Context context = getContext(); //checking the last update and notify if it' the first of the day SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key); boolean displayNotifications = prefs.getBoolean(displayNotificationsKey, Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default))); if (displayNotifications) { String lastNotificationKey = context.getString(R.string.pref_last_notification); long lastSync = prefs.getLong(lastNotificationKey, 0); if (System.currentTimeMillis() - lastSync >= getNotificationTimeGap()) { // Last sync was more than 1 day ago, let's send a notification with the weather. String locationQuery = WeatherUtil.getPreferredLocation(context); Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis()); // we'll query our contentProvider, as always Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null);/*w w w .j av a2 s . c o m*/ if (cursor.moveToFirst()) { int weatherId = cursor.getInt(INDEX_WEATHER_ID); double high = cursor.getDouble(INDEX_MAX_TEMP); double low = cursor.getDouble(INDEX_MIN_TEMP); String desc = cursor.getString(INDEX_SHORT_DESC); int iconId = WeatherUtil.getIconResourceForWeatherCondition(weatherId); Resources resources = context.getResources(); Bitmap largeIcon = BitmapFactory.decodeResource(resources, WeatherUtil.getArtResourceForWeatherCondition(weatherId)); String title = getTitle(); // Define the text of the forecast. String contentText = String.format(context.getString(R.string.format_notification), desc, WeatherUtil.formatTemperature(context, high), WeatherUtil.formatTemperature(context, low)); // NotificationCompatBuilder is a very convenient way to build backward-compatible // notifications. Just throw in some data. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext()) .setColor(resources.getColor(R.color.weather4u_light_blue)).setSmallIcon(iconId) .setLargeIcon(largeIcon).setContentTitle(title).setContentText(contentText); mBuilder.setAutoCancel(true); // Make something interesting happen when the user clicks on the notification. // In this case, opening the app is sufficient. Intent resultIntent = new Intent(context, MainActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getContext() .getSystemService(Context.NOTIFICATION_SERVICE); // WEATHER_NOTIFICATION_ID allows you to update the notification later on. mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build()); //refreshing last sync SharedPreferences.Editor editor = prefs.edit(); editor.putLong(lastNotificationKey, System.currentTimeMillis()); editor.commit(); } cursor.close(); } } }
From source file:org.noorganization.instalistsynch.controller.synch.impl.RecipeSynch.java
@Override public void indexLocal(int _groupId, Date _lastIndexTime) { String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000"); boolean isLocal = false; GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup(); if (groupAuth != null) { isLocal = groupAuth.getGroupId() == _groupId; }//from w ww. ja va2 s . co m Cursor logCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType); if (logCursor.getCount() == 0) { logCursor.close(); return; } try { while (logCursor.moveToNext()) { // fetch the action type int actionId = logCursor.getInt(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION)); eActionType actionType = eActionType.getTypeById(actionId); List<ModelMapping> modelMappingList = mRecipeMappingController.get( ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID + " LIKE ?", new String[] { String.valueOf(_groupId), logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) }); ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0); switch (actionType) { case INSERT: // skip insertion because this should be decided by the user if the non local groups should have access to the category // and also skip if a mapping for this case already exists! if (!isLocal || modelMapping != null) { continue; } String clientUuid = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)); Date clientDate = ISO8601Utils.parse( logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)), new ParsePosition(0)); modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid, new Date(Constants.INITIAL_DATE), clientDate, false); mRecipeMappingController.insert(modelMapping); break; case UPDATE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } String timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mRecipeMappingController.update(modelMapping); break; case DELETE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } modelMapping.setDeleted(true); timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mRecipeMappingController.update(modelMapping); break; default: } } } catch (Exception e) { logCursor.close(); } }
From source file:com.ericsender.android_nanodegree.popmovie.com.ericsender.android_nanodegree.popmovie.data.TestProvider.java
public void testGettingMinutes() { testAddingMinutesToMovieRow();// w ww. jav a 2s . c o m Cursor c = mContext.getContentResolver().query(MovieContract.MovieEntry.buildUriMinutes(curr_movie_id), null, null, null, null); assertTrue(c.moveToFirst()); int mins = c.getInt(1); assertEquals(expected_mins, mins); c.close(); }