List of usage examples for android.database Cursor isAfterLast
boolean isAfterLast();
From source file:com.stfalcon.contentmanager.ContentManager.java
/** * Process result of camera intent//from ww w.j a va 2 s. c o m */ private void onCameraIntentResult(int requestCode, int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK) { Cursor myCursor = null; Date dateOfPicture = null; try { // Create a Cursor to obtain the file Path for the large image String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.ORIENTATION, MediaStore.Images.ImageColumns.DATE_TAKEN }; String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC"; myCursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort); myCursor.moveToFirst(); if (!myCursor.isAfterLast()) { // This will actually give you the file path location of the image. String largeImagePath = myCursor .getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)); photoUri = Uri.fromFile(new File(largeImagePath)); if (photoUri != null) { dateOfPicture = new Date(myCursor.getLong( myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATE_TAKEN))); if (dateOfPicture != null && dateOfPicture.after(dateCameraIntentStarted)) { rotateXDegrees = myCursor.getInt( myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION)); } else { photoUri = null; } } if (myCursor.moveToNext() && !myCursor.isAfterLast()) { String largeImagePath3rdLocation = myCursor .getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)); Date dateOfPicture3rdLocation = new Date(myCursor.getLong( myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATE_TAKEN))); if (dateOfPicture3rdLocation != null && dateOfPicture3rdLocation.after(dateCameraIntentStarted)) { photoUriIn3rdLocation = Uri.fromFile(new File(largeImagePath3rdLocation)); } } } } catch (Exception e) { } finally { if (myCursor != null && !myCursor.isClosed()) { myCursor.close(); } } if (photoUri == null) { try { photoUri = intent.getData(); } catch (Exception e) { } } if (photoUri == null) { photoUri = preDefinedCameraUri; } try { if (photoUri != null && new File(photoUri.getPath()).length() <= 0) { if (preDefinedCameraUri != null) { Uri tempUri = photoUri; photoUri = preDefinedCameraUri; preDefinedCameraUri = tempUri; } } } catch (Exception e) { } photoUri = getFileUriFromContentUri(photoUri); preDefinedCameraUri = getFileUriFromContentUri(preDefinedCameraUri); try { if (photoUriIn3rdLocation != null) { if (photoUriIn3rdLocation.equals(photoUri) || photoUriIn3rdLocation.equals(preDefinedCameraUri)) { photoUriIn3rdLocation = null; } else { photoUriIn3rdLocation = getFileUriFromContentUri(photoUriIn3rdLocation); } } } catch (Exception e) { } if (photoUri != null) { pickContentListener.onContentLoaded(photoUri, Content.IMAGE.toString()); } else { pickContentListener.onError(""); } } else if (resultCode == Activity.RESULT_CANCELED) { pickContentListener.onCanceled(); } else { pickContentListener.onCanceled(); } }
From source file:edu.pdx.cecs.orcycle.TripUploader.java
@SuppressLint("SimpleDateFormat") private JSONObject getCoordsJSON(long tripId) throws JSONException { JSONObject jsonTripCoords = null;/*from ww w.j a v a 2s. co m*/ JSONArray jsonSensorReadings = null; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mDb.openReadOnly(); try { Cursor cursorTripCoords = mDb.fetchAllCoordsForTrip(tripId); // Build the map between JSON field name and phone db field name: Map<String, Integer> fieldMap = new HashMap<String, Integer>(); fieldMap.put(TRIP_COORDS_TIME, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_TIME)); fieldMap.put(TRIP_COORDS_LAT, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_LAT)); fieldMap.put(TRIP_COORDS_LON, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_LGT)); fieldMap.put(TRIP_COORDS_ALT, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_ALT)); fieldMap.put(TRIP_COORDS_SPEED, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_SPEED)); fieldMap.put(TRIP_COORDS_HACCURACY, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_ACC)); fieldMap.put(TRIP_COORDS_VACCURACY, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_ACC)); // Build JSON objects for each coordinate: jsonTripCoords = new JSONObject(); double coordTime; while (!cursorTripCoords.isAfterLast()) { // ***************** // * Get coordinates // ***************** coordTime = cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_TIME)); JSONObject jsonCoord = new JSONObject(); jsonCoord.put(TRIP_COORDS_TIME, df.format(coordTime)); jsonCoord.put(TRIP_COORDS_LAT, cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6); jsonCoord.put(TRIP_COORDS_LON, cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6); jsonCoord.put(TRIP_COORDS_ALT, dr1(cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_ALT)))); jsonCoord.put(TRIP_COORDS_SPEED, dr1(cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_SPEED)))); jsonCoord.put(TRIP_COORDS_HACCURACY, cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY))); jsonCoord.put(TRIP_COORDS_VACCURACY, cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY))); // ********************************************************** // * Get all sensor readings corresponding to this time index // ********************************************************** jsonSensorReadings = getJsonSensorReadings(coordTime); if ((null != jsonSensorReadings) && (jsonSensorReadings.length() > 0)) { jsonCoord.put(TRIP_COORDS_SENSOR_READINGS, jsonSensorReadings); } // **************************************************** // * Insert sensor readings into jSON coordinate object // **************************************************** jsonTripCoords.put(jsonCoord.getString("r"), jsonCoord); // move to next coordinate cursorTripCoords.moveToNext(); } cursorTripCoords.close(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); } finally { mDb.close(); } return jsonTripCoords; }
From source file:com.parse.OfflineStore.java
/** * Gets the data for the given object from the offline database. Returns a task that will be * completed if data for the object was available. If the object is not in the cache, the task * will be faulted, with a CACHE_MISS error. * * @param object/* www . j a v a 2 s.c o m*/ * The object to fetch. * @param db * A database connection to use. */ /* package for OfflineQueryLogic */ <T extends ParseObject> Task<T> fetchLocallyAsync(final T object, final ParseSQLiteDatabase db) { final Task<T>.TaskCompletionSource tcs = Task.create(); Task<String> uuidTask; synchronized (lock) { if (fetchedObjects.containsKey(object)) { /* * The object has already been fetched from the offline store, so any data that's in there * is already reflected in the in-memory version. There's nothing more to do. */ //noinspection unchecked return (Task<T>) fetchedObjects.get(object); } /* * Put a placeholder so that anyone else who attempts to fetch this object will just wait for * this call to finish doing it. */ //noinspection unchecked fetchedObjects.put(object, (Task<ParseObject>) tcs.getTask()); uuidTask = objectToUuidMap.get(object); } String className = object.getClassName(); String objectId = object.getObjectId(); /* * If this gets set, then it will contain data from the offline store that needs to be merged * into the existing object in memory. */ Task<String> jsonStringTask = Task.forResult(null); if (objectId == null) { // This Object has never been saved to Parse. if (uuidTask == null) { /* * This object was not pulled from the data store or previously saved to it, so there's * nothing that can be fetched from it. This isn't an error, because it's really convenient * to try to fetch objects from the offline store just to make sure they are up-to-date, and * we shouldn't force developers to specially handle this case. */ } else { /* * This object is a new ParseObject that is known to the data store, but hasn't been * fetched. The only way this could happen is if the object had previously been stored in * the offline store, then the object was removed from memory (maybe by rebooting), and then * a object with a pointer to it was fetched, so we only created the pointer. We need to * pull the data out of the database using the UUID. */ final String[] select = { OfflineSQLiteOpenHelper.KEY_JSON }; final String where = OfflineSQLiteOpenHelper.KEY_UUID + " = ?"; final Capture<String> uuid = new Capture<>(); jsonStringTask = uuidTask.onSuccessTask(new Continuation<String, Task<Cursor>>() { @Override public Task<Cursor> then(Task<String> task) throws Exception { uuid.set(task.getResult()); String[] args = { uuid.get() }; return db.queryAsync(OfflineSQLiteOpenHelper.TABLE_OBJECTS, select, where, args); } }).onSuccess(new Continuation<Cursor, String>() { @Override public String then(Task<Cursor> task) throws Exception { Cursor cursor = task.getResult(); cursor.moveToFirst(); if (cursor.isAfterLast()) { cursor.close(); throw new IllegalStateException("Attempted to find non-existent uuid " + uuid.get()); } String json = cursor.getString(0); cursor.close(); return json; } }); } } else { if (uuidTask != null) { /* * This object is an existing ParseObject, and we must've already pulled its data out of the * offline store, or else we wouldn't know its UUID. This should never happen. */ tcs.setError(new IllegalStateException("This object must have already been " + "fetched from the local datastore, but isn't marked as fetched.")); synchronized (lock) { // Forget we even tried to fetch this object, so that retries will actually... retry. fetchedObjects.remove(object); } return tcs.getTask(); } /* * We've got a pointer to an existing ParseObject, but we've never pulled its data out of the * offline store. Since fetching from the server forces a fetch from the offline store, that * means this is a pointer. We need to try to find any existing entry for this object in the * database. */ String[] select = { OfflineSQLiteOpenHelper.KEY_JSON, OfflineSQLiteOpenHelper.KEY_UUID }; String where = String.format("%s = ? AND %s = ?", OfflineSQLiteOpenHelper.KEY_CLASS_NAME, OfflineSQLiteOpenHelper.KEY_OBJECT_ID); String[] args = { className, objectId }; jsonStringTask = db.queryAsync(OfflineSQLiteOpenHelper.TABLE_OBJECTS, select, where, args) .onSuccess(new Continuation<Cursor, String>() { @Override public String then(Task<Cursor> task) throws Exception { Cursor cursor = task.getResult(); cursor.moveToFirst(); if (cursor.isAfterLast()) { /* * This is a pointer that came from Parse that references an object that has * never been saved in the offline store before. This just means there's no data * in the store that needs to be merged into the object. */ cursor.close(); throw new ParseException(ParseException.CACHE_MISS, "This object is not available in the offline cache."); } // we should fetch its data and record its UUID for future reference. String jsonString = cursor.getString(0); String newUUID = cursor.getString(1); cursor.close(); synchronized (lock) { /* * It's okay to put this object into the uuid map. No one will try to fetch * it, because it's already in the fetchedObjects map. And no one will try to * save to it without fetching it first, so everything should be just fine. */ objectToUuidMap.put(object, Task.forResult(newUUID)); uuidToObjectMap.put(newUUID, object); } return jsonString; } }); } return jsonStringTask.onSuccessTask(new Continuation<String, Task<Void>>() { @Override public Task<Void> then(Task<String> task) throws Exception { String jsonString = task.getResult(); if (jsonString == null) { /* * This means we tried to fetch an object from the database that was never actually saved * locally. This probably means that its parent object was saved locally and we just * created a pointer to this object. This should be considered a cache miss. */ return Task.forError(new ParseException(ParseException.CACHE_MISS, "Attempted to fetch an object offline which was never saved to the offline cache.")); } final JSONObject json; try { /* * We can assume that whatever is in the database is the last known server state. The only * things to maintain from the in-memory object are any changes since the object was last * put in the database. */ json = new JSONObject(jsonString); } catch (JSONException e) { return Task.forError(e); } // Fetch all the offline objects before we decode. final Map<String, Task<ParseObject>> offlineObjects = new HashMap<>(); (new ParseTraverser() { @Override protected boolean visit(Object object) { if (object instanceof JSONObject && ((JSONObject) object).optString("__type").equals("OfflineObject")) { String uuid = ((JSONObject) object).optString("uuid"); offlineObjects.put(uuid, getPointerAsync(uuid, db)); } return true; } }).setTraverseParseObjects(false).setYieldRoot(false).traverse(json); return Task.whenAll(offlineObjects.values()).onSuccess(new Continuation<Void, Void>() { @Override public Void then(Task<Void> task) throws Exception { object.mergeREST(object.getState(), json, new OfflineDecoder(offlineObjects)); return null; } }); } }).continueWithTask(new Continuation<Void, Task<T>>() { @Override public Task<T> then(Task<Void> task) throws Exception { if (task.isCancelled()) { tcs.setCancelled(); } else if (task.isFaulted()) { tcs.setError(task.getError()); } else { tcs.setResult(object); } return tcs.getTask(); } }); }
From source file:edu.mit.mobile.android.locast.data.Sync.java
/** * Sync the given URI to the server. Will compare dates and do a two-way sync. * Does not yet handle the case where both server and and local are modified * (collisions)/*ww w . j a va2 s . co m*/ * * @param toSync URI of the object to sync. Generally, this should be the dir URI * @param sync A new object that extends JsonSyncableItem. This is needed for the JSON * serialization routine in it, as well as the sync map. * @throws IOException */ private void sync(Uri toSync, JsonSyncableItem sync, SyncProgressNotifier syncProgress, Bundle extras) throws SyncException, IOException { String netPath; boolean haveItemPubUri = false; if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) { netPath = toSync.getPath(); toSync = (Uri) extras.get(EXTRA_DESTINATION_URI); haveItemPubUri = true; } else { netPath = null; } final String contentType = getContentResolver().getType(toSync); final Cursor c = cr.query(toSync, sync.getFullProjection(), null, null, null); try { syncProgress.addPendingTasks(c.getCount()); // Handle a list of items. if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) { // load from the network first... if (netPath == null) { netPath = MediaProvider.getPublicPath(this, toSync); } syncNetworkList(toSync, netPath, sync, syncProgress); } else if (haveItemPubUri) { syncNetworkItem(toSync, netPath, sync, syncProgress); } // then load locally. if (DEBUG) { Log.d(TAG, "have " + c.getCount() + " local items to sync"); } for (c.moveToFirst(); (currentSyncTask != null && !currentSyncTask.isCancelled()) && !c.isAfterLast(); c .moveToNext()) { try { syncItem(toSync, c, null, sync, syncProgress, netPath); syncProgress.completeTask(); } catch (final SyncItemDeletedException side) { if (DEBUG) { Log.d(TAG, side.getLocalizedMessage() + " Deleting..."); } cr.delete(side.getItem(), null, null); //side.printStackTrace(); syncProgress.completeTask(); continue; } } } catch (final NoPublicPath npp) { // XXX this should be a hard error Log.e(TAG, "Sync Error: " + npp.getLocalizedMessage()); return; } finally { c.close(); } }
From source file:de.lebenshilfe_muenster.uk_gebaerden_muensterland.database.SignDAO.java
@NonNull private List<Sign> readInternal(String whereSignNameLocaleDeLike, boolean readStarredSignsOnly, boolean readOrderedByLearningProgress) { final List<Sign> signs = new ArrayList<>(); Cursor cursor; if (StringUtils.isNotEmpty(whereSignNameLocaleDeLike)) { Log.d(TAG,/*w w w.j a v a 2s.co m*/ MessageFormat.format("Reading signs with name_locale_de like: {0}", whereSignNameLocaleDeLike)); cursor = database.query(DbContract.SignTable.TABLE_NAME, DbContract.SignTable.ALL_COLUMNS, DbContract.SignTable.NAME_LOCALE_DE_LIKE, new String[] { "%" + whereSignNameLocaleDeLike + "%" }, null, null, DbContract.SignTable.ORDER_BY_NAME_DE_ASC); } else if (readStarredSignsOnly) { Log.d(TAG, "Reading starred signs only"); cursor = database.query(DbContract.SignTable.TABLE_NAME, DbContract.SignTable.ALL_COLUMNS, DbContract.SignTable.IS_STARRED, new String[] { DbContract.BOOLEAN_TRUE }, null, null, DbContract.SignTable.ORDER_BY_NAME_DE_ASC); } else if (readOrderedByLearningProgress) { Log.d(TAG, "Reading signs ordered by learning progress ascending"); cursor = database.query(DbContract.SignTable.TABLE_NAME, DbContract.SignTable.ALL_COLUMNS, null, null, null, null, DbContract.SignTable.ORDER_BY_LEARNING_PROGRESS_ASC); } else { Log.d(TAG, "Reading all signs"); cursor = database.query(DbContract.SignTable.TABLE_NAME, DbContract.SignTable.ALL_COLUMNS, null, null, null, null, DbContract.SignTable.ORDER_BY_NAME_DE_ASC); } cursor.moveToFirst(); while (!cursor.isAfterLast()) { final Sign sign = cursorToSign(cursor); signs.add(sign); cursor.moveToNext(); } cursor.close(); return signs; }
From source file:com.urs.triptracks.TripUploader.java
private String getCoordsJSON(long tripId) throws JSONException { JSONObject coord = new JSONObject(); //HS-SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates mDb.openReadOnly();/*from w ww . j a va 2 s . co m*/ Cursor tripCoordsCursor = mDb.fetchAllCoordsForTrip(tripId); // Build the map between JSON fieldname and phone db fieldname: Map<String, Integer> fieldMap = new HashMap<String, Integer>(); fieldMap.put(TRIP_COORDS_TIME, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME)); fieldMap.put(TRIP_COORDS_LAT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT)); fieldMap.put(TRIP_COORDS_LON, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT)); fieldMap.put(TRIP_COORDS_ALT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT)); fieldMap.put(TRIP_COORDS_SPEED, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED)); fieldMap.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC)); fieldMap.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC)); // Build JSON objects for each coordinate: JSONArray tripCoords = new JSONArray(); String str = new String(); JSONArray key = new JSONArray(); while (!tripCoordsCursor.isAfterLast()) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); coord.put(TRIP_COORDS_TIME, df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME)))); coord.put(TRIP_COORDS_LAT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6); coord.put(TRIP_COORDS_LON, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6); coord.put(TRIP_COORDS_ALT, tripCoordsCursor.getInt(fieldMap.get(TRIP_COORDS_ALT))); coord.put(TRIP_COORDS_SPEED, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED))); coord.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY))); coord.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY))); //tripCoords.put(coord.getString("rec"), coord); //JSONObject jo=new JSONObject(); /*key.put("coord"); // jo.put("coord", coord); tripCoords.put(coord); tripCoordsCursor.moveToNext(); Log.v("coordsoutputtosee1:", tripCoords.toString()); tripCoords.put(coord); Log.v("coordsoutputtosee2:", tripCoords.toString());*/ str = str.concat("{\"coord\":"); str = str.concat(coord.toString()); str = str.concat("}"); tripCoordsCursor.moveToNext(); if (!tripCoordsCursor.isAfterLast()) { str = str.concat(","); } } tripCoordsCursor.close(); mDb.close(); return str; }
From source file:org.mozilla.gecko.sync.repositories.android.AndroidBrowserBookmarksRepositorySession.java
@Override public void begin(RepositorySessionBeginDelegate delegate) { // Check for the existence of special folders // and insert them if they don't exist. Cursor cur; try {/* w ww. jav a 2s . c o m*/ Logger.debug(LOG_TAG, "Check and build special GUIDs."); dataAccessor.checkAndBuildSpecialGuids(); cur = dataAccessor.getGuidsIDsForFolders(); Logger.debug(LOG_TAG, "Got GUIDs for folders."); } catch (android.database.sqlite.SQLiteConstraintException e) { Logger.error(LOG_TAG, "Got sqlite constraint exception working with Fennec bookmark DB.", e); delegate.onBeginFailed(e); return; } catch (NullCursorException e) { delegate.onBeginFailed(e); return; } catch (Exception e) { delegate.onBeginFailed(e); return; } // To deal with parent mapping of bookmarks we have to do some // hairy stuff. Here's the setup for it. Logger.debug(LOG_TAG, "Preparing folder ID mappings."); // Fake our root. Logger.debug(LOG_TAG, "Tracking places root as ID 0."); idToGuid.put(0L, "places"); guidToID.put("places", 0L); try { cur.moveToFirst(); while (!cur.isAfterLast()) { String guid = getGUID(cur); long id = RepoUtils.getLongFromCursor(cur, BrowserContract.Bookmarks._ID); guidToID.put(guid, id); idToGuid.put(id, guid); Logger.debug(LOG_TAG, "GUID " + guid + " maps to " + id); cur.moveToNext(); } } finally { cur.close(); } Logger.debug(LOG_TAG, "Done with initial setup of bookmarks session."); super.begin(delegate); }
From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java
/** * @param toSync//from ww w .j a v a2 s . co m * @param account * @param extras * @param provider * @param syncResult * @return true if the item was sync'd successfully. Soft errors will cause this to return * false. * @throws RemoteException * @throws SyncException * @throws JSONException * @throws IOException * @throws NetworkProtocolException * @throws NoPublicPath * @throws OperationApplicationException * @throws InterruptedException */ public boolean sync(Uri toSync, Account account, Bundle extras, ContentProviderClient provider, SyncResult syncResult) throws RemoteException, SyncException, JSONException, IOException, NetworkProtocolException, NoPublicPath, OperationApplicationException, InterruptedException { String pubPath = null; // // Handle http or https uris separately. These require the // destination uri. // if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) { pubPath = toSync.toString(); if (!extras.containsKey(EXTRA_DESTINATION_URI)) { throw new IllegalArgumentException("missing EXTRA_DESTINATION_URI when syncing HTTP URIs"); } toSync = Uri.parse(extras.getString(EXTRA_DESTINATION_URI)); } final String type = provider.getType(toSync); final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); // skip any items already sync'd if (!manualSync && mLastUpdated.isUpdatedRecently(toSync)) { if (DEBUG) { Log.d(TAG, "not syncing " + toSync + " as it's been updated recently"); } syncResult.stats.numSkippedEntries++; return false; } // the sync map will convert the json data to ContentValues final SyncMap syncMap = MediaProvider.getSyncMap(provider, toSync); final Uri toSyncWithoutQuerystring = toSync.buildUpon().query(null).build(); final HashMap<String, SyncStatus> syncStatuses = new HashMap<String, SyncEngine.SyncStatus>(); final ArrayList<ContentProviderOperation> cpo = new ArrayList<ContentProviderOperation>(); final LinkedList<String> cpoPubUris = new LinkedList<String>(); // // first things first, upload any content that needs to be // uploaded. // try { uploadUnpublished(toSync, account, provider, syncMap, syncStatuses, syncResult); if (Thread.interrupted()) { throw new InterruptedException(); } // this should ensure that all items have a pubPath when we // query it below. if (pubPath == null) { // we should avoid calling this too much as it // can be expensive pubPath = MediaProvider.getPublicPath(mContext, toSync); } } catch (final NoPublicPath e) { // TODO this is a special case and this is probably not the best place to handle this. // Ideally, this should be done in such a way as to reduce any extra DB queries - // perhaps by doing a join with the parent. if (syncMap.isFlagSet(SyncMap.FLAG_PARENT_MUST_SYNC_FIRST)) { if (DEBUG) { Log.d(TAG, "skipping " + toSync + " whose parent hasn't been sync'd first"); } syncResult.stats.numSkippedEntries++; return false; } // if it's an item, we can handle it. if (isDir) { throw e; } } if (pubPath == null) { // this should have been updated already by the initial // upload, so something must be wrong throw new SyncException("never got a public path for " + toSync); } if (DEBUG) { Log.d(TAG, "sync(toSync=" + toSync + ", account=" + account + ", extras=" + extras + ", manualSync=" + manualSync + ",...)"); Log.d(TAG, "pubPath: " + pubPath); } final long request_time = System.currentTimeMillis(); HttpResponse hr = mNetworkClient.get(pubPath); final long response_time = System.currentTimeMillis(); // the time compensation below allows a time-based synchronization to function even if the // local clock is entirely wrong. The server's time is extracted using the Date header and // all are compared relative to the respective clock reference. Any data that's stored on // the mobile should be stored relative to the local clock and the server will respect the // same. long serverTime; try { serverTime = getServerTime(hr); } catch (final DateParseException e) { Log.w(TAG, "could not retrieve date from server. Using local time, which may be incorrect.", e); serverTime = System.currentTimeMillis(); } // TODO check out // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html final long response_delay = response_time - request_time; if (DEBUG) { Log.d(TAG, "request took " + response_delay + "ms"); } final long localTime = request_time; // add this to the server time to get the local time final long localOffset = (localTime - serverTime); if (Math.abs(localOffset) > 30 * 60 * 1000) { Log.w(TAG, "local clock is off by " + localOffset + "ms"); } if (Thread.interrupted()) { throw new InterruptedException(); } final HttpEntity ent = hr.getEntity(); String selection; String selectionInverse; String[] selectionArgs; if (isDir) { final JSONArray ja = new JSONArray(StreamUtils.inputStreamToString(ent.getContent())); ent.consumeContent(); final int len = ja.length(); selectionArgs = new String[len]; // build the query to see which items are already in the // database final StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 0; i < len; i++) { if (Thread.interrupted()) { throw new InterruptedException(); } final SyncStatus syncStatus = loadItemFromJsonObject(ja.getJSONObject(i), syncMap, serverTime); syncStatuses.put(syncStatus.remote, syncStatus); selectionArgs[i] = syncStatus.remote; // add in a placeholder for the query sb.append('?'); if (i != (len - 1)) { sb.append(','); } } sb.append(")"); final String placeholders = sb.toString(); selection = JsonSyncableItem._PUBLIC_URI + " IN " + placeholders; selectionInverse = JsonSyncableItem._PUBLIC_URI + " NOT IN " + placeholders; } else { final JSONObject jo = new JSONObject(StreamUtils.inputStreamToString(ent.getContent())); ent.consumeContent(); final SyncStatus syncStatus = loadItemFromJsonObject(jo, syncMap, serverTime); syncStatuses.put(syncStatus.remote, syncStatus); selection = JsonSyncableItem._PUBLIC_URI + "=?"; selectionInverse = JsonSyncableItem._PUBLIC_URI + "!=?"; selectionArgs = new String[] { syncStatus.remote }; } // first check without the querystring. This will ensure that we // properly mark things that we already have in the database. final Cursor check = provider.query(toSyncWithoutQuerystring, SYNC_PROJECTION, selection, selectionArgs, null); // these items are on both sides try { final int pubUriCol = check.getColumnIndex(JsonSyncableItem._PUBLIC_URI); final int idCol = check.getColumnIndex(JsonSyncableItem._ID); // All the items in this cursor should be found on both // the client and the server. for (check.moveToFirst(); !check.isAfterLast(); check.moveToNext()) { if (Thread.interrupted()) { throw new InterruptedException(); } final long id = check.getLong(idCol); final Uri localUri = ContentUris.withAppendedId(toSync, id); final String pubUri = check.getString(pubUriCol); final SyncStatus itemStatus = syncStatuses.get(pubUri); itemStatus.state = SyncState.BOTH_UNKNOWN; itemStatus.local = localUri; // make the status searchable by both remote and // local uri syncStatuses.put(localUri.toString(), itemStatus); } } finally { check.close(); } Cursor c = provider.query(toSync, SYNC_PROJECTION, selection, selectionArgs, null); // these items are on both sides try { final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI); final int localModifiedCol = c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE); final int serverModifiedCol = c.getColumnIndex(JsonSyncableItem._SERVER_MODIFIED_DATE); final int idCol = c.getColumnIndex(JsonSyncableItem._ID); // All the items in this cursor should be found on both // the client and the server. for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { if (Thread.interrupted()) { throw new InterruptedException(); } final long id = c.getLong(idCol); final Uri localUri = ContentUris.withAppendedId(toSync, id); final String pubUri = c.getString(pubUriCol); final SyncStatus itemStatus = syncStatuses.get(pubUri); if (itemStatus.state == SyncState.ALREADY_UP_TO_DATE || itemStatus.state == SyncState.NOW_UP_TO_DATE) { if (DEBUG) { Log.d(TAG, localUri + "(" + pubUri + ")" + " is already up to date."); } continue; } itemStatus.local = localUri; // make the status searchable by both remote and local uri syncStatuses.put(localUri.toString(), itemStatus); // last modified as stored in the DB, in phone time final long itemLocalModified = c.getLong(localModifiedCol); // last modified as stored in the DB, in server time final long itemServerModified = c.getLong(serverModifiedCol); final long localAge = localTime - itemLocalModified; final long remoteAge = serverTime - itemStatus.remoteModifiedTime; final long ageDifference = Math.abs(localAge - remoteAge); // up to date, as far remote -> local goes if (itemServerModified == itemStatus.remoteModifiedTime) { itemStatus.state = SyncState.ALREADY_UP_TO_DATE; if (DEBUG) { Log.d(TAG, pubUri + " is up to date."); } // need to download } else if (localAge > remoteAge) { if (DEBUG) { final long serverModified = itemStatus.remoteModifiedTime; Log.d(TAG, pubUri + " : local is " + ageDifference + "ms older (" + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified, FORMAT_ARGS_DEBUG) + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext, serverModified, FORMAT_ARGS_DEBUG) + "); updating local copy..."); } itemStatus.state = SyncState.REMOTE_DIRTY; final ContentProviderOperation.Builder b = ContentProviderOperation.newUpdate(localUri); // update this so it's in the local timescale correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._CREATED_DATE, JsonSyncableItem._CREATED_DATE, localOffset); correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE, JsonSyncableItem._MODIFIED_DATE, localOffset); b.withValues(itemStatus.remoteCVs); b.withExpectedCount(1); cpo.add(b.build()); cpoPubUris.add(pubUri); syncResult.stats.numUpdates++; // need to upload } else if (localAge < remoteAge) { if (DEBUG) { final long serverModified = itemStatus.remoteModifiedTime; Log.d(TAG, pubUri + " : local is " + ageDifference + "ms newer (" + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified, FORMAT_ARGS_DEBUG) + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext, serverModified, FORMAT_ARGS_DEBUG) + "); publishing to server..."); } itemStatus.state = SyncState.LOCAL_DIRTY; mNetworkClient.putJson(pubPath, JsonSyncableItem.toJSON(mContext, localUri, c, syncMap)); } mLastUpdated.markUpdated(localUri); syncResult.stats.numEntries++; } // end for } finally { c.close(); } /* * Apply updates in bulk */ if (cpo.size() > 0) { if (DEBUG) { Log.d(TAG, "applying " + cpo.size() + " bulk updates..."); } final ContentProviderResult[] r = provider.applyBatch(cpo); if (DEBUG) { Log.d(TAG, "Done applying updates. Running postSync handler..."); } for (int i = 0; i < r.length; i++) { final ContentProviderResult res = r[i]; final SyncStatus ss = syncStatuses.get(cpoPubUris.get(i)); if (ss == null) { Log.e(TAG, "can't get sync status for " + res.uri); continue; } syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson, res.count != null ? res.count == 1 : true); ss.state = SyncState.NOW_UP_TO_DATE; } if (DEBUG) { Log.d(TAG, "done running postSync handler."); } cpo.clear(); cpoPubUris.clear(); } if (Thread.interrupted()) { throw new InterruptedException(); } /* * Look through the SyncState.state values and find ones that need to be stored. */ for (final Map.Entry<String, SyncStatus> entry : syncStatuses.entrySet()) { if (Thread.interrupted()) { throw new InterruptedException(); } final String pubUri = entry.getKey(); final SyncStatus status = entry.getValue(); if (status.state == SyncState.REMOTE_ONLY) { if (DEBUG) { Log.d(TAG, pubUri + " is not yet stored locally, adding..."); } // update this so it's in the local timescale correctServerOffset(status.remoteCVs, JsonSyncableItem._CREATED_DATE, JsonSyncableItem._CREATED_DATE, localOffset); correctServerOffset(status.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE, JsonSyncableItem._MODIFIED_DATE, localOffset); final ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(toSync); b.withValues(status.remoteCVs); cpo.add(b.build()); cpoPubUris.add(pubUri); syncResult.stats.numInserts++; } } /* * Execute the content provider operations in bulk. */ if (cpo.size() > 0) { if (DEBUG) { Log.d(TAG, "bulk inserting " + cpo.size() + " items..."); } final ContentProviderResult[] r = provider.applyBatch(cpo); if (DEBUG) { Log.d(TAG, "applyBatch completed. Processing results..."); } int successful = 0; for (int i = 0; i < r.length; i++) { final ContentProviderResult res = r[i]; if (res.uri == null) { syncResult.stats.numSkippedEntries++; Log.e(TAG, "result from content provider bulk operation returned null"); continue; } final String pubUri = cpoPubUris.get(i); final SyncStatus ss = syncStatuses.get(pubUri); if (ss == null) { syncResult.stats.numSkippedEntries++; Log.e(TAG, "could not find sync status for " + cpoPubUris.get(i)); continue; } ss.local = res.uri; if (DEBUG) { Log.d(TAG, "onPostSyncItem(" + res.uri + ", ...); pubUri: " + pubUri); } syncMap.onPostSyncItem(mContext, account, res.uri, ss.remoteJson, res.count != null ? res.count == 1 : true); ss.state = SyncState.NOW_UP_TO_DATE; successful++; } if (DEBUG) { Log.d(TAG, successful + " batch inserts successfully applied."); } } else { if (DEBUG) { Log.d(TAG, "no updates to perform."); } } /** * Look through all the items that we didn't already find on the server side, but which * still have a public uri. They should be checked to make sure they're not deleted. */ c = provider.query(toSync, SYNC_PROJECTION, ProviderUtils.addExtraWhere(selectionInverse, JsonSyncableItem._PUBLIC_URI + " NOT NULL"), selectionArgs, null); try { final int idCol = c.getColumnIndex(JsonSyncableItem._ID); final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI); cpo.clear(); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { final String pubUri = c.getString(pubUriCol); SyncStatus ss = syncStatuses.get(pubUri); final Uri item = isDir ? ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol)) : toSync; if (ss == null) { ss = syncStatuses.get(item.toString()); } if (DEBUG) { Log.d(TAG, item + " was not found in the main list of items on the server (" + pubPath + "), but appears to be a child of " + toSync); if (ss != null) { Log.d(TAG, "found sync status for " + item + ": " + ss); } } if (ss != null) { switch (ss.state) { case ALREADY_UP_TO_DATE: case NOW_UP_TO_DATE: if (DEBUG) { Log.d(TAG, item + " is already up to date. No need to see if it was deleted."); } continue; case BOTH_UNKNOWN: if (DEBUG) { Log.d(TAG, item + " was found on both sides, but has an unknown sync status. Skipping..."); } continue; default: Log.w(TAG, "got an unexpected state for " + item + ": " + ss); } } else { ss = new SyncStatus(pubUri, SyncState.LOCAL_ONLY); ss.local = item; hr = mNetworkClient.head(pubUri); switch (hr.getStatusLine().getStatusCode()) { case 200: if (DEBUG) { Log.d(TAG, "HEAD " + pubUri + " returned 200"); } ss.state = SyncState.BOTH_UNKNOWN; break; case 404: if (DEBUG) { Log.d(TAG, "HEAD " + pubUri + " returned 404. Deleting locally..."); } ss.state = SyncState.DELETED_REMOTELY; final ContentProviderOperation deleteOp = ContentProviderOperation .newDelete(ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol))) .build(); cpo.add(deleteOp); break; default: syncResult.stats.numIoExceptions++; Log.w(TAG, "HEAD " + pubUri + " got unhandled result: " + hr.getStatusLine()); } } syncStatuses.put(pubUri, ss); } // for cursor if (cpo.size() > 0) { final ContentProviderResult[] results = provider.applyBatch(cpo); for (final ContentProviderResult result : results) { if (result.count != 1) { throw new SyncException("Error deleting item"); } } } } finally { c.close(); } syncStatuses.clear(); mLastUpdated.markUpdated(toSync); return true; }
From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragmentOverzicht.java
/** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader//from ww w . j a v a 2s .com * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image).into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer String erkenningsnummer = data .getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(erkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data .getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data .getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout .findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString( data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout .findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText .setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor(getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } } }
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
public Set<Long> getPublicKeyPrints() { HashSet<Long> key_ss = new HashSet<Long>(); Cursor c = getReadableDatabase().query(Contact.TABLE, new String[] { Contact.PUBLIC_KEY_HASH_64 }, null, null, null, null, null);// w ww . j a v a 2s . c o m c.moveToFirst(); while (!c.isAfterLast()) { key_ss.add(c.getLong(0)); c.moveToNext(); } c.close(); return key_ss; }