List of usage examples for android.database Cursor isNull
boolean isNull(int columnIndex);
true
if the value in the indicated column is null. From source file:edu.mit.mobile.android.locast.sync.MediaSync.java
/** * Synchronize the media of the given castMedia. It will download or upload as needed. * * Blocks until the sync is complete./*ww w.j a va2 s . c o m*/ * * @param castMediaUri * a {@link CastMedia} item uri * @throws SyncException */ public void syncItemMedia(Uri castMediaUri) throws SyncException { final Cursor castMedia = mCr.query(castMediaUri, CASTMEDIA_PROJECTION, null, null, null); final Uri castUri = CastMedia.getCast(castMediaUri); final Cursor cast = mCr.query(castUri, CAST_PROJECTION, null, null, null); try { if (!castMedia.moveToFirst()) { throw new IllegalArgumentException("uri " + castMediaUri + " has no content"); } if (!cast.moveToFirst()) { throw new IllegalArgumentException(castMediaUri + " cast " + castUri + " has no content"); } // cache the column numbers final int mediaUrlCol = castMedia.getColumnIndex(CastMedia._MEDIA_URL); final int localUriCol = castMedia.getColumnIndex(CastMedia._LOCAL_URI); final boolean isFavorite = cast.getInt(cast.getColumnIndex(Cast._FAVORITED)) != 0; final boolean keepOffline = castMedia.getInt(castMedia.getColumnIndex(CastMedia._KEEP_OFFLINE)) != 0; final String mimeType = castMedia.getString(castMedia.getColumnIndex(CastMedia._MIME_TYPE)); final boolean isImage = (mimeType != null) && mimeType.startsWith("image/"); // we don't need to sync this if ("text/html".equals(mimeType)) { return; } final Uri locMedia = castMedia.isNull(localUriCol) ? null : Uri.parse(castMedia.getString(localUriCol)); final String pubMedia = castMedia.getString(mediaUrlCol); final boolean hasLocMedia = locMedia != null && new File(locMedia.getPath()).exists(); final boolean hasPubMedia = pubMedia != null && pubMedia.length() > 0; final String localThumb = castMedia.getString(castMedia.getColumnIndex(CastMedia._THUMB_LOCAL)); if (hasLocMedia && !hasPubMedia) { final String uploadPath = castMedia.getString(castMedia.getColumnIndex(CastMedia._PUBLIC_URI)); if (uploadPath == null) { Log.w(TAG, "attempted to sync " + castMediaUri + " which has a null uploadPath"); return; } uploadMedia(uploadPath, castMediaUri, mimeType, locMedia); } else if (!hasLocMedia && hasPubMedia) { // only have a public copy, so download it and store locally. final Uri pubMediaUri = Uri.parse(pubMedia); final File destfile = getFilePath(pubMediaUri); // the following conditions indicate that the cast media should be downloaded. if (keepOffline || isFavorite) { final boolean anythingChanged = downloadMediaFile(pubMedia, destfile, castMediaUri); // the below is inverted from what seems logical, because downloadMediaFile() // will actually update the castmedia if it downloads anything. We'll only be // getting here if we don't have any local record of the file, so we should make // the association by ourselves. if (!anythingChanged) { File thumb = null; if (isImage && localThumb == null) { thumb = destfile; } updateLocalFile(castMediaUri, destfile, thumb); // disabled to avoid spamming the user with downloaded // items. // checkForMediaEntry(castMediaUri, pubMediaUri, mimeType); } } } } finally { cast.close(); castMedia.close(); } }
From source file:fr.eoit.activity.fragment.blueprint.InventionFragment.java
@Override public void onLoadFinished(Cursor data) { if (DbUtil.hasAtLeastOneRow(data)) { parentTypeId = data.getInt(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_PARENT_TYPE_ID)); int maxProdLimit = data.getInt(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_MAX_PRODUCTION_LIMIT)); metaLevel = data.getShort(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_INVENTION_ITEM_META_LEVEL)); decryptorId = data.getInt(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_DECRYPTOR_ID)); double cost = data.getDouble(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_RESEARCH_PRICE)); if (decryptorId != 0) { currentDecryptorBonuses = DecryptorUtil.getDecryptorBonusesOrDefault(decryptorId); }/*from www . ja v a 2 s. c o m*/ requiredSkillInventionFragment.setParentFragment(this); requiredSkillInventionFragment.setParentTypeId(parentTypeId); requiredItemsInventionFragment.setParentFragment(this); requiredItemsInventionFragment.setDecryptorId(decryptorId); requiredItemsInventionFragment.setParentTypeId(parentTypeId); requiredItemsInventionFragment.setMaxProdLimit(maxProdLimit); requiredDecryptorFragment.setParentFragment(this); requiredDecryptorFragment.setBlueprintId(blueprintId); requiredDecryptorFragment.setProducedItemId(producedItemId); int metaGroupId = getArguments().getInt("metaGroupId", -1); Bundle blueprintBundle = BlueprintUtil.getBlueprintBundle(data, metaGroupId, true, false); int numberOfRuns = blueprintBundle.getInt("numberOfRuns", 0); int unitPerBatch = blueprintBundle.getInt("unitPerBatch", 0); double sellPrice = getArguments().getDouble("sellPrice", 0); producePrice = getArguments().getDouble("producePrice", 0); double profitOnSingleItem = sellPrice - producePrice; double blueprintProfit = profitOnSingleItem * unitPerBatch * numberOfRuns; if (!data.isNull(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_RESEARCH_PRICE))) { BlueprintUtil.setBlueprintCost(costTextView, cost, getResources()); profitTextView.setText(PricesUtils.formatPrice(blueprintProfit, getActivity(), true)); } else { costTextView.setVisibility(View.GONE); profitTextView.setVisibility(View.GONE); } } }
From source file:org.runnerup.view.DetailActivity.java
private void loadRoute() { final GraphProducer graphData = new GraphProducer(); final String[] from = new String[] { DB.LOCATION.LATITUDE, DB.LOCATION.LONGITUDE, DB.LOCATION.TYPE, DB.LOCATION.TIME, DB.LOCATION.LAP, DB.LOCATION.HR }; loadRouteTask = new AsyncTask<String, String, Route>() { @Override//from www . j av a 2 s . co m protected Route doInBackground(String... params) { int cnt = 0; Route route = null; Cursor c = mDB.query(DB.LOCATION.TABLE, from, "activity_id == " + mID, null, null, null, "_id", null); if (c.moveToFirst()) { route = new Route(); double acc_distance = 0; double tot_distance = 0; int cnt_distance = 0; LatLng lastLocation = null; long lastTime = 0; int lastLap = -1; int hr = 0; do { cnt++; LatLng point = new LatLng(c.getDouble(0), c.getDouble(1)); route.path.add(point); route.bounds.include(point); int type = c.getInt(2); long time = c.getLong(3); int lap = c.getInt(4); if (!c.isNull(5)) hr = c.getInt(5); MarkerOptions m; switch (type) { case DB.LOCATION.TYPE_START: case DB.LOCATION.TYPE_END: case DB.LOCATION.TYPE_PAUSE: case DB.LOCATION.TYPE_RESUME: if (type == DB.LOCATION.TYPE_PAUSE) { if (lap != lastLap) { graphData.clear(tot_distance); } else if (lastTime != 0 && lastLocation != null) { float res[] = { 0 }; Location.distanceBetween(lastLocation.latitude, lastLocation.longitude, point.latitude, point.longitude, res); graphData.addObservation(time - lastTime, res[0], tot_distance, hr); // hrList.clear(); graphData.clear(tot_distance); } lastLap = lap; lastTime = 0; } else if (type == DB.LOCATION.TYPE_RESUME) { lastLap = lap; lastTime = time; } m = new MarkerOptions(); m.position((lastLocation = point)); m.title(type == DB.LOCATION.TYPE_START ? "Start" : type == DB.LOCATION.TYPE_END ? "Stop" : type == DB.LOCATION.TYPE_PAUSE ? "Pause" : type == DB.LOCATION.TYPE_RESUME ? "Resume" : "<Unknown>"); m.snippet(null); m.draggable(false); route.markers.add(m); break; case DB.LOCATION.TYPE_GPS: float res[] = { 0 }; Location.distanceBetween(lastLocation.latitude, lastLocation.longitude, point.latitude, point.longitude, res); acc_distance += res[0]; tot_distance += res[0]; if (lap != lastLap) { graphData.clear(tot_distance); } else if (lastTime != 0) { graphData.addObservation(time - lastTime, res[0], tot_distance, hr); } lastLap = lap; lastTime = time; if (acc_distance >= formatter.getUnitMeters()) { cnt_distance++; acc_distance = 0; m = new MarkerOptions(); m.position(point); m.title("" + cnt_distance + " " + formatter.getUnitString()); m.snippet(null); m.draggable(false); route.markers.add(m); } lastLocation = point; break; } } while (c.moveToNext()); System.err.println("Finished loading " + cnt + " points"); } c.close(); return route; } @Override protected void onPostExecute(Route route) { if (route != null) { graphData.complete(graphView); if (!graphData.HasHRInfo()) { graphTab.addView(graphView); } else { graphTab.addView(graphView, new LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.5f)); graphTab.addView(graphView2, new LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.5f)); } if (graphData.HasHRZHist()) { hrzonesBarLayout.setVisibility(View.VISIBLE); hrzonesBarLayout.addView(hrzonesBar); } else { hrzonesBarLayout.setVisibility(View.GONE); } if (map != null) { map.addPolyline(route.path); mapBounds = route.bounds.build(); System.err.println("Added polyline"); int cnt = 0; for (MarkerOptions m : route.markers) { cnt++; map.addMarker(m); } System.err.println("Added " + cnt + " markers"); route = new Route(); // release mem for old... } } } }.execute("kalle"); }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Return the data stored in the cursor at the given index and given position * (ie the given row which the cursor is currently on) as null OR a String. * <p>//from w w w .j av a 2 s. c o m * NB: Currently only checks for Strings, long, int, and double. * * @param c * @param i * @return */ @SuppressLint("NewApi") public String getIndexAsString(Cursor c, int i) { // If you add additional return types here be sure to modify the javadoc. if (i == -1) return null; if (c.isNull(i)) { return null; } switch (c.getType(i)) { case Cursor.FIELD_TYPE_STRING: return c.getString(i); case Cursor.FIELD_TYPE_FLOAT: return Double.toString(c.getDouble(i)); case Cursor.FIELD_TYPE_INTEGER: return Long.toString(c.getLong(i)); case Cursor.FIELD_TYPE_NULL: return c.getString(i); default: case Cursor.FIELD_TYPE_BLOB: throw new IllegalStateException("Unexpected data type in SQLite table"); } }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Return the data stored in the cursor at the given index and given position * (ie the given row which the cursor is currently on) as null OR whatever * data type it is./*from w ww.java2s .co m*/ * <p> * This does not actually convert data types from one type to the other. * Instead, it safely preserves null values and returns boxed data values. If * you specify ArrayList or HashMap, it JSON deserializes the value into one * of those. * * @param c * @param clazz * @param i * @return */ @SuppressLint("NewApi") public final <T> T getIndexAsType(Cursor c, Class<T> clazz, int i) { // If you add additional return types here be sure to modify the javadoc. try { if (i == -1) return null; if (c.isNull(i)) { return null; } if (clazz == Long.class) { Long l = c.getLong(i); return (T) l; } else if (clazz == Integer.class) { Integer l = c.getInt(i); return (T) l; } else if (clazz == Double.class) { Double d = c.getDouble(i); return (T) d; } else if (clazz == String.class) { String str = c.getString(i); return (T) str; } else if (clazz == Boolean.class) { // stored as integers Integer l = c.getInt(i); return (T) Boolean.valueOf(l != 0); } else if (clazz == ArrayList.class) { // json deserialization of an array String str = c.getString(i); return (T) ODKFileUtils.mapper.readValue(str, ArrayList.class); } else if (clazz == HashMap.class) { // json deserialization of an object String str = c.getString(i); return (T) ODKFileUtils.mapper.readValue(str, HashMap.class); } else { throw new IllegalStateException("Unexpected data type in SQLite table"); } } catch (ClassCastException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " in SQLite table "); } catch (JsonParseException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } catch (JsonMappingException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } }
From source file:com.android.contacts.common.model.ContactLoader.java
private Contact loadContactEntity(ContentResolver resolver, Uri contactUri) { Uri entityUri = Uri.withAppendedPath(contactUri, Contacts.Entity.CONTENT_DIRECTORY); Cursor cursor = resolver.query(entityUri, ContactQuery.COLUMNS, null, null, Contacts.Entity.RAW_CONTACT_ID); if (cursor == null) { Log.e(TAG, "No cursor returned in loadContactEntity"); return Contact.forNotFound(mRequestedUri); }/*from ww w . j a v a 2s .c o m*/ try { if (!cursor.moveToFirst()) { cursor.close(); return Contact.forNotFound(mRequestedUri); } // Create the loaded contact starting with the header data. Contact contact = loadContactHeaderData(cursor, contactUri); // Fill in the raw contacts, which is wrapped in an Entity and any // status data. Initially, result has empty entities and statuses. long currentRawContactId = -1; RawContact rawContact = null; ImmutableList.Builder<RawContact> rawContactsBuilder = new ImmutableList.Builder<RawContact>(); ImmutableMap.Builder<Long, DataStatus> statusesBuilder = new ImmutableMap.Builder<Long, DataStatus>(); do { long rawContactId = cursor.getLong(ContactQuery.RAW_CONTACT_ID); if (rawContactId != currentRawContactId) { // First time to see this raw contact id, so create a new entity, and // add it to the result's entities. currentRawContactId = rawContactId; rawContact = new RawContact(loadRawContactValues(cursor)); rawContactsBuilder.add(rawContact); } if (!cursor.isNull(ContactQuery.DATA_ID)) { ContentValues data = loadDataValues(cursor); rawContact.addDataItemValues(data); if (!cursor.isNull(ContactQuery.PRESENCE) || !cursor.isNull(ContactQuery.STATUS)) { final DataStatus status = new DataStatus(cursor); final long dataId = cursor.getLong(ContactQuery.DATA_ID); statusesBuilder.put(dataId, status); } } } while (cursor.moveToNext()); contact.setRawContacts(rawContactsBuilder.build()); contact.setStatuses(statusesBuilder.build()); return contact; } finally { cursor.close(); } }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * /* w w w . ja va 2s .c o m*/ * @param db * @param appName * @param tableId * @param rowId * @return the sync state of the row (see {@link SyncState}), or null if the * row does not exist. */ public SyncState getSyncState(SQLiteDatabase db, String appName, String tableId, String rowId) { Cursor c = null; try { c = db.query(tableId, new String[] { DataTableColumns.SYNC_STATE }, DataTableColumns.ID + " = ?", new String[] { rowId }, null, null, null); if (c.moveToFirst()) { int syncStateIndex = c.getColumnIndex(DataTableColumns.SYNC_STATE); if (!c.isNull(syncStateIndex)) { String val = getIndexAsString(c, syncStateIndex); return SyncState.valueOf(val); } } return null; } finally { if (c != null && !c.isClosed()) { c.close(); } } }
From source file:mobisocial.socialkit.musubi.Musubi.java
public DbObj objForCursor(Cursor cursor) { try {/*w w w. ja v a 2 s.c o m*/ long localId = -1; String appId = null; String type = null; String name = null; JSONObject json = null; long senderId = -1; byte[] hash = null; long feedId = -1; Integer intKey = null; long timestamp = -1; Long parentId = null; try { localId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID)); } catch (IllegalArgumentException e) { } try { appId = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_APP_ID)); } catch (IllegalArgumentException e) { } try { type = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_TYPE)); } catch (IllegalArgumentException e) { } try { name = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_STRING_KEY)); } catch (IllegalArgumentException e) { } try { json = new JSONObject(cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_JSON))); } catch (IllegalArgumentException e) { } try { senderId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_IDENTITY_ID)); } catch (IllegalArgumentException e) { } try { hash = cursor.getBlob(cursor.getColumnIndexOrThrow(DbObj.COL_UNIVERSAL_HASH)); } catch (IllegalArgumentException e) { } try { feedId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_FEED_ID)); } catch (IllegalArgumentException e) { } try { intKey = cursor.getInt(cursor.getColumnIndexOrThrow(DbObj.COL_INT_KEY)); } catch (IllegalArgumentException e) { } try { timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP)); } catch (IllegalArgumentException e) { } try { int pIndex = cursor.getColumnIndexOrThrow(DbObj.COL_PARENT_ID); if (!cursor.isNull(pIndex)) { parentId = cursor.getLong(pIndex); } } catch (IllegalArgumentException e) { } // Don't require raw field. final byte[] raw; int rawIndex = cursor.getColumnIndex(DbObj.COL_RAW); if (rawIndex == -1 || cursor.isNull(rawIndex)) { raw = null; } else { raw = cursor.getBlob(cursor.getColumnIndexOrThrow(DbObj.COL_RAW)); } return new DbObj(this, appId, feedId, parentId, senderId, localId, type, json, raw, intKey, name, timestamp, hash); } catch (JSONException e) { Log.e(TAG, "Couldn't parse obj.", e); return null; } }
From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java
/** * Creates a JSON Object from a Tweet TODO: Move this where it belongs! * /*from w w w.j ava 2 s.c o m*/ * @param c * @return * @throws JSONException */ protected JSONObject getJSON(Cursor c) throws JSONException { JSONObject o = new JSONObject(); if (c.getColumnIndex(Tweets.COL_USER_TID) < 0 || c.getColumnIndex(TwitterUsers.COL_SCREEN_NAME) < 0) { Log.i(TAG, "missing user data"); return null; } else { o.put(Tweets.COL_USER_TID, c.getLong(c.getColumnIndex(Tweets.COL_USER_TID))); o.put(TYPE, MESSAGE_TYPE_TWEET); o.put(TwitterUsers.COL_SCREEN_NAME, c.getString(c.getColumnIndex(TwitterUsers.COL_SCREEN_NAME))); if (c.getColumnIndex(Tweets.COL_CREATED_AT) >= 0) o.put(Tweets.COL_CREATED_AT, c.getLong(c.getColumnIndex(Tweets.COL_CREATED_AT))); if (c.getColumnIndex(Tweets.COL_CERTIFICATE) >= 0) o.put(Tweets.COL_CERTIFICATE, c.getString(c.getColumnIndex(Tweets.COL_CERTIFICATE))); if (c.getColumnIndex(Tweets.COL_SIGNATURE) >= 0) o.put(Tweets.COL_SIGNATURE, c.getString(c.getColumnIndex(Tweets.COL_SIGNATURE))); if (c.getColumnIndex(Tweets.COL_TEXT) >= 0) o.put(Tweets.COL_TEXT, c.getString(c.getColumnIndex(Tweets.COL_TEXT))); if (c.getColumnIndex(Tweets.COL_REPLY_TO_TWEET_TID) >= 0) o.put(Tweets.COL_REPLY_TO_TWEET_TID, c.getLong(c.getColumnIndex(Tweets.COL_REPLY_TO_TWEET_TID))); if (c.getColumnIndex(Tweets.COL_LAT) >= 0) o.put(Tweets.COL_LAT, c.getDouble(c.getColumnIndex(Tweets.COL_LAT))); if (c.getColumnIndex(Tweets.COL_LNG) >= 0) o.put(Tweets.COL_LNG, c.getDouble(c.getColumnIndex(Tweets.COL_LNG))); if (!c.isNull(c.getColumnIndex(Tweets.COL_MEDIA_URIS))) { String photoUri = c.getString(c.getColumnIndex(Tweets.COL_MEDIA_URIS)); Uri uri = Uri.parse(photoUri); o.put(Tweets.COL_MEDIA_URIS, uri.getLastPathSegment()); } if (c.getColumnIndex(Tweets.COL_HTML_PAGES) >= 0) o.put(Tweets.COL_HTML_PAGES, c.getString(c.getColumnIndex(Tweets.COL_HTML_PAGES))); if (c.getColumnIndex(Tweets.COL_SOURCE) >= 0) o.put(Tweets.COL_SOURCE, c.getString(c.getColumnIndex(Tweets.COL_SOURCE))); if (c.getColumnIndex(Tweets.COL_TID) >= 0 && !c.isNull(c.getColumnIndex(Tweets.COL_TID))) o.put(Tweets.COL_TID, c.getLong(c.getColumnIndex(Tweets.COL_TID))); if (c.getColumnIndex(TwitterUsers.COL_PROFILE_IMAGE_URI) >= 0 && c.getColumnIndex(TweetsContentProvider.COL_USER_ROW_ID) >= 0) { String imageUri = c.getString(c.getColumnIndex(TwitterUsers.COL_PROFILE_IMAGE_URI)); Bitmap profileImage = ImageLoader.getInstance().loadImageSync(imageUri); if (profileImage != null) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); profileImage.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); String profileImageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT); o.put(TwitterUsers.JSON_FIELD_PROFILE_IMAGE, profileImageBase64); } } return o; } }