List of usage examples for android.database Cursor getLong
long getLong(int columnIndex);
From source file:com.calgen.prodek.sunshine.Data.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. *///from ww w . j a va 2 s . c o m public long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID long locationId; //Checking if the location already exists Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, new String[] { WeatherContract.LocationEntry._ID }, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting }, null); if (locationCursor.moveToFirst()) { int locationIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = locationCursor.getLong(locationIndex); } else { ContentValues locationValues = new ContentValues(); locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); Uri uri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, locationValues); locationId = ContentUris.parseId(uri); } locationCursor.close(); return locationId; }
From source file:gov.wa.wsdot.android.wsdot.service.TravelTimesSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null; long now = System.currentTimeMillis(); boolean shouldUpdate = true; String responseString = ""; /** // www. j a v a 2 s.c o m * Check the cache table for the last time data was downloaded. If we are within * the allowed time period, don't sync, otherwise get fresh data from the server. */ try { cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED }, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "travel_times" }, null); if (cursor != null && cursor.moveToFirst()) { long lastUpdated = cursor.getLong(0); //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS; //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min"); shouldUpdate = (Math.abs(now - lastUpdated) > (5 * DateUtils.MINUTE_IN_MILLIS)); } } finally { if (cursor != null) { cursor.close(); } } // Ability to force a refresh of camera data. boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false); if (shouldUpdate || forceUpdate) { List<Integer> starred = new ArrayList<Integer>(); starred = getStarred(); try { URL url = new URL(TRAVEL_TIMES_URL); URLConnection urlConn = url.openConnection(); BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream()); GZIPInputStream gzin = new GZIPInputStream(bis); InputStreamReader is = new InputStreamReader(gzin); BufferedReader in = new BufferedReader(is); String jsonFile = ""; String line; while ((line = in.readLine()) != null) jsonFile += line; in.close(); JSONObject obj = new JSONObject(jsonFile); JSONObject result = obj.getJSONObject("traveltimes"); JSONArray items = result.getJSONArray("items"); List<ContentValues> times = new ArrayList<ContentValues>(); int numItems = items.length(); for (int j = 0; j < numItems; j++) { JSONObject item = items.getJSONObject(j); ContentValues timesValues = new ContentValues(); timesValues.put(TravelTimes.TRAVEL_TIMES_TITLE, item.getString("title")); timesValues.put(TravelTimes.TRAVEL_TIMES_CURRENT, item.getInt("current")); timesValues.put(TravelTimes.TRAVEL_TIMES_AVERAGE, item.getInt("average")); timesValues.put(TravelTimes.TRAVEL_TIMES_DISTANCE, item.getString("distance") + " miles"); timesValues.put(TravelTimes.TRAVEL_TIMES_ID, Integer.parseInt(item.getString("routeid"))); timesValues.put(TravelTimes.TRAVEL_TIMES_UPDATED, item.getString("updated")); if (starred.contains(Integer.parseInt(item.getString("routeid")))) { timesValues.put(TravelTimes.TRAVEL_TIMES_IS_STARRED, 1); } times.add(timesValues); } // Purge existing travel times covered by incoming data resolver.delete(TravelTimes.CONTENT_URI, null, null); // Bulk insert all the new travel times resolver.bulkInsert(TravelTimes.CONTENT_URI, times.toArray(new ContentValues[times.size()])); // Update the cache table with the time we did the update ContentValues values = new ContentValues(); values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis()); resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?", new String[] { "travel_times" }); responseString = "OK"; } catch (Exception e) { Log.e(DEBUG_TAG, "Error: " + e.getMessage()); responseString = e.getMessage(); } } else { responseString = "NOP"; } Intent broadcastIntent = new Intent(); broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.TRAVEL_TIMES_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java
private ContentProviderResult[] optimisticallyCreateGroupAndContacts(JSONObject group, ContentProviderClient provider, ContentProviderClient contactsProvider, String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException, OperationApplicationException { String groupCloudId = group.getString(JSONKeys.KEY_ID); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); // If the first operation asserts, that means the group already exists // Operation 0 ContentProviderOperation.Builder op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI) .withValue(GMSGroup._ID, "").withValue(GMSGroup.CLOUD_ID, "") .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withExpectedCount(0); ops.add(op.build());/* w w w .j a v a2 s.c om*/ // If we get this far, create the group from the information the JSON object // Operation 1 ContentValues groupValues = GMSApplication.getGroupValues(group); op = ContentProviderOperation.newInsert(GMSGroups.CONTENT_URI).withValues(groupValues) .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED); ops.add(op.build()); // And add the contacts // Operations 2 - N + 2 where N is the number of members in group if (group.has(JSONKeys.KEY_MEMBERS)) { JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS); int numMembers = membersArray.length(); for (int j = 0; j < numMembers; ++j) { JSONObject member = membersArray.getJSONObject(j); ContentValues memberValues = GMSApplication.getMemberValues(member); op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI).withValues(memberValues) .withValueBackReference(GMSContact.GROUP_ID, 1) .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED); ops.add(op.build()); } } ContentProviderResult[] results = provider.applyBatch(ops); // Create the contact on the device Uri groupUri = results[1].uri; if (groupUri != null) { Cursor cursor = null; try { cursor = GMSContactOperations.findGroupInContacts(contactsProvider, account, groupCloudId); if (cursor.getCount() > 0) { Assert.assertTrue(cursor.moveToFirst()); long oldContactId = cursor.getLong(0); GMSContactOperations.removeGroupFromContacts(contactsProvider, account, oldContactId, syncResult); } long contactId = GMSContactOperations.addGroupToContacts(getContext(), contactsProvider, account, group, syncResult); if (contactId > 0) { ContentValues values = new ContentValues(); values.put(GMSGroup.RAW_CONTACT_ID, contactId); provider.update(groupUri, values, null, null); addNewGroupNotification(group); } } finally { if (cursor != null) { cursor.close(); } } } return results; }
From source file:it.jaschke.alexandria.model.view.BookDetailViewModel.java
/** * Retrieves the data from the cursor passed as argument and sets it onto the * {@link BookDetailViewModel}'s current {@link Book}. The projection used * must be {@link BookDetailQuery#PROJECTION}. This method also notifies the * data binding of the change, so the visual elements can be updated. * * @param cursor the {@link Cursor} containing the data to load. * @throws IllegalStateException if there is no {@link Book} currently set * in the {@link BookDetailViewModel}. * @throws IllegalArgumentException if the data passed does not belong to * the {@link Book} currently set (i.e. does not have the same id). *///from www . j a v a 2 s . c o m public void setBookData(Cursor cursor) { if (mBook == null) { throw new IllegalStateException("No book currently set in BookDetailViewModel."); } if (cursor == null) { return; } if (!cursor.moveToFirst()) { Log.w(LOG_TAG, "The cursor contains no data. Ignoring book details."); return; } if (mBook.getId() != cursor.getLong(BookDetailQuery.COL_ID)) { throw new IllegalArgumentException("The data passed does not belong to the book"); } mBook.setTitle(cursor.getString(BookDetailQuery.COL_TITLE)); mBook.setSubtitle(cursor.getString(BookDetailQuery.COL_SUBTITLE)); mBook.setDescription(cursor.getString(BookDetailQuery.COL_DESCRIPTION)); String coverUrl = cursor.getString(BookDetailQuery.COL_COVER_IMAGE_URL); mBook.setCoverUri(Uri.parse(StringUtils.trimToEmpty(coverUrl))); notifyPropertyChanged(BR._all); }
From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java
/** * ?message?/*from ww w.j a va 2 s. c o m*/ */ private JSONObject getMessageFromCursor(Cursor cursor) throws JSONException { // ?? String msgId = cursor.getString(cursor.getColumnIndex("_id")); String subject = cursor.getString(cursor.getColumnIndex("subject")); String smsBody = cursor.getString(cursor.getColumnIndex("body")); long date = cursor.getLong(cursor.getColumnIndex("date")); boolean isRead = cursor.getInt(cursor.getColumnIndex("read")) == 0 ? false : true; String destAddress = cursor.getString(cursor.getColumnIndex("address")); JSONObject message = new JSONObject(); message.put("messageId", msgId); message.put("subject", subject); message.put("body", smsBody); message.put("destinationAddresses", destAddress); message.put("messageType", MESSAGE_TYPE_SMS); message.put("date", date); message.put("isRead", isRead); return message; }
From source file:gov.wa.wsdot.android.wsdot.service.HighwayAlertsSyncService.java
@SuppressLint("SimpleDateFormat") @Override//from w ww . j a v a 2 s .c o m protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null; long now = System.currentTimeMillis(); boolean shouldUpdate = true; String responseString = ""; DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a"); /** * Check the cache table for the last time data was downloaded. If we are within * the allowed time period, don't sync, otherwise get fresh data from the server. */ try { cursor = resolver.query(Caches.CONTENT_URI, projection, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "highway_alerts" }, null); if (cursor != null && cursor.moveToFirst()) { long lastUpdated = cursor.getLong(0); //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS; //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min"); shouldUpdate = (Math.abs(now - lastUpdated) > (5 * DateUtils.MINUTE_IN_MILLIS)); } } finally { if (cursor != null) { cursor.close(); } } // Tapping the refresh button will force a data refresh. boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false); if (shouldUpdate || forceUpdate) { try { URL url = new URL(HIGHWAY_ALERTS_URL); URLConnection urlConn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String jsonFile = ""; String line; while ((line = in.readLine()) != null) { jsonFile += line; } in.close(); JSONObject obj = new JSONObject(jsonFile); JSONObject result = obj.getJSONObject("alerts"); JSONArray items = result.getJSONArray("items"); List<ContentValues> alerts = new ArrayList<ContentValues>(); int numItems = items.length(); for (int j = 0; j < numItems; j++) { JSONObject item = items.getJSONObject(j); JSONObject startRoadwayLocation = item.getJSONObject("StartRoadwayLocation"); ContentValues alertData = new ContentValues(); alertData.put(HighwayAlerts.HIGHWAY_ALERT_ID, item.getString("AlertID")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_HEADLINE, item.getString("HeadlineDescription")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_CATEGORY, item.getString("EventCategory")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_PRIORITY, item.getString("Priority")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_LATITUDE, startRoadwayLocation.getString("Latitude")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_LONGITUDE, startRoadwayLocation.getString("Longitude")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_ROAD_NAME, startRoadwayLocation.getString("RoadName")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_LAST_UPDATED, dateFormat .format(new Date(Long.parseLong(item.getString("LastUpdatedTime").substring(6, 19))))); alerts.add(alertData); } // Purge existing highway alerts covered by incoming data resolver.delete(HighwayAlerts.CONTENT_URI, null, null); // Bulk insert all the new highway alerts resolver.bulkInsert(HighwayAlerts.CONTENT_URI, alerts.toArray(new ContentValues[alerts.size()])); // Update the cache table with the time we did the update ContentValues values = new ContentValues(); values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis()); resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "highway_alerts" }); responseString = "OK"; } catch (Exception e) { Log.e(DEBUG_TAG, "Error: " + e.getMessage()); responseString = e.getMessage(); } } else { responseString = "NOP"; } Intent broadcastIntent = new Intent(); broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.HIGHWAY_ALERTS_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:export.format.FacebookCourse.java
private JSONArray trail(long activityId) throws JSONException { final String cols[] = { DB.LOCATION.TYPE, DB.LOCATION.LATITUDE, DB.LOCATION.LONGITUDE, DB.LOCATION.TIME, DB.LOCATION.SPEED };/*from w ww. j a va 2 s .c om*/ Cursor c = mDB.query(DB.LOCATION.TABLE, cols, DB.LOCATION.ACTIVITY + " = " + activityId, null, null, null, null); if (c.moveToFirst()) { Location prev = null, last = null; double sumDist = 0; long sumTime = 0; double accTime = 0; final double period = 30; JSONArray arr = new JSONArray(); do { switch (c.getInt(0)) { case DB.LOCATION.TYPE_START: case DB.LOCATION.TYPE_RESUME: last = new Location("Dill"); last.setLatitude(c.getDouble(1)); last.setLongitude(c.getDouble(2)); last.setTime(c.getLong(3)); accTime = period * 1000; // always emit first point // start/resume break; case DB.LOCATION.TYPE_END: accTime = period * 1000; // always emit last point case DB.LOCATION.TYPE_GPS: case DB.LOCATION.TYPE_PAUSE: Location l = new Location("Sill"); l.setLatitude(c.getDouble(1)); l.setLongitude(c.getDouble(2)); l.setTime(c.getLong(3)); if (!c.isNull(4)) l.setSpeed(c.getFloat(4)); if (last != null) { sumDist += l.distanceTo(last); sumTime += l.getTime() - last.getTime(); accTime += l.getTime() - last.getTime(); } prev = last; last = l; } if (Math.round(accTime / 1000) >= period) { arr.put(point(prev, last, sumTime, sumDist)); accTime -= period * 1000; } } while (c.moveToNext()); c.close(); return arr; } c.close(); return null; }
From source file:com.example.binht.thoitiet.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. *//*from w w w .java 2s . c om*/ long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID // Otherwise, insert it using the content resolver and the base URI long locationId; // First, check if the location with this city name exists in the db Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, new String[] { WeatherContract.LocationEntry._ID }, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting }, null); if (locationCursor.moveToFirst()) { int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = locationCursor.getLong(locationIdIndex); } else { // Now that the content provider is set up, inserting rows of data is pretty simple. // First create a ContentValues object to hold the data you want to insert. ContentValues locationValues = new ContentValues(); // Then add the data, along with the corresponding name of the data type, // so the content provider knows what kind of value is being inserted. locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); // Finally, insert location data into the database. Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, locationValues); // The resulting URI contains the ID for the row. Extract the locationId from the Uri. locationId = ContentUris.parseId(insertedUri); } locationCursor.close(); // Wait, that worked? Yes! return locationId; }
From source file:com.example.dhrumil.sunshine.app.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city/*from www. jav a 2 s . co m*/ * @param lon the longitude of the city * @return the row ID of the added location. */ public long addLocation(String locationSetting, String cityName, double lat, double lon) { long locationId; // First, check if the location with this city name exists in the db Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, new String[] { WeatherContract.LocationEntry._ID }, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting }, null); if (locationCursor.moveToFirst()) { int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = locationCursor.getLong(locationIdIndex); } else { // Now that the content provider is set up, inserting rows of data is pretty simple. // First create a ContentValues object to hold the data you want to insert. ContentValues locationValues = new ContentValues(); // Then add the data, along with the corresponding name of the data type, // so the content provider knows what kind of value is being inserted. locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); // Finally, insert location data into the database. Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, locationValues); // The resulting URI contains the ID for the row. Extract the locationId from the Uri. locationId = ContentUris.parseId(insertedUri); } locationCursor.close(); // Wait, that worked? Yes! return locationId; }
From source file:org.dvbviewer.controller.ui.fragments.ChannelEpg.java
/** * Cursor to timer.//from w w w . ja va2 s . c o m * * @param c the c * @return the timer * @author RayBa * @date 07.04.2013 */ private Timer cursorToTimer(Cursor c) { String name = mCHannel.getName(); long channelID = mCHannel.getId(); String epgTitle = !c.isNull(c.getColumnIndex(EpgTbl.TITLE)) ? c.getString(c.getColumnIndex(EpgTbl.TITLE)) : name; long epgStart = c.getLong(c.getColumnIndex(EpgTbl.START)); long epgEnd = c.getLong(c.getColumnIndex(EpgTbl.END)); DVBViewerPreferences prefs = new DVBViewerPreferences(getSherlockActivity()); int epgBefore = prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_TIME_BEFORE, 5); int epgAfter = prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_TIME_AFTER, 5); Date start = epgStart > 0 ? new Date(epgStart) : new Date(); Date end = epgEnd > 0 ? new Date(epgEnd) : new Date(); Log.i(ChannelList.class.getSimpleName(), start.toString()); Log.i(ChannelList.class.getSimpleName(), start.toString()); Log.i(ChannelList.class.getSimpleName(), start.toString()); start = DateUtils.addMinutes(start, 0 - epgBefore); end = DateUtils.addMinutes(end, epgAfter); Timer timer = new Timer(); timer.setTitle(epgTitle); timer.setChannelId(channelID); timer.setChannelName(name); timer.setStart(start); timer.setEnd(end); timer.setTimerAction(prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_DEF_AFTER_RECORD, 0)); return timer; }