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:com.triarc.sync.SyncAdapter.java
@SuppressLint("UseValueOf") private Object getModelValueFor(Cursor query, String fieldName, FieldType fieldType) throws JSONException { int columnIndex = query.getColumnIndex(fieldName); if (query.isNull(columnIndex)) { return null; }/*from ww w . j a va 2 s .c om*/ switch (fieldType) { case Boolean: return new Boolean(query.getInt(columnIndex) != 0); case Date: return format.format(new Date(query.getLong(columnIndex))); case Numeric: return new Long(query.getLong(columnIndex)); case Text: return query.getString(columnIndex); case JsonObject: String json = query.getString(columnIndex); return new JSONObject(json); case JsonArray: json = query.getString(columnIndex); return new JSONArray(json); default: return null; } }
From source file:net.news.inrss.fragment.EntryFragment.java
private void refreshUI(Cursor entryCursor) { if (entryCursor != null) { Log.d(TAG, "refreshUI() called with: " + "entryCursor = [" + entryCursor + "]"); String feedTitle = entryCursor.isNull(mFeedNamePos) ? entryCursor.getString(mFeedUrlPos) : entryCursor.getString(mFeedNamePos); BaseActivity activity = (BaseActivity) getActivity(); activity.setTitle(feedTitle);//ww w. j a v a2 s. co m byte[] iconBytes = entryCursor.getBlob(mFeedIconPos); Bitmap bitmap = UiUtils.getScaledBitmap(iconBytes, 24); if (bitmap != null) { activity.getSupportActionBar().setIcon(new BitmapDrawable(getResources(), bitmap)); } else { activity.getSupportActionBar().setIcon(null); } mFavorite = entryCursor.getInt(mIsFavoritePos) == 1; activity.invalidateOptionsMenu(); // Listen the mobilizing task if (FetcherService.hasMobilizationTask(mEntriesIds[mCurrentPagerPos])) { // If the service is not started, start it here to avoid an infinite loading if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) { MainApplication.getContext() .startService(new Intent(MainApplication.getContext(), FetcherService.class) .setAction(FetcherService.ACTION_MOBILIZE_FEEDS)); } } // Mark the article as read if (entryCursor.getInt(mIsReadPos) != 1) { final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]); new Thread(new Runnable() { @Override public void run() { ContentResolver cr = MainApplication.getContext().getContentResolver(); cr.update(uri, FeedData.getReadContentValues(), null, null); // Update the cursor Cursor updatedCursor = cr.query(uri, null, null, null, null); updatedCursor.moveToFirst(); mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor); } }).start(); } } }
From source file:org.runnerup.export.format.RunKeeper.java
private void exportPath(String name, long activityId, long startTime, JsonWriter w) throws IOException { String[] pColumns = { DB.LOCATION.TIME, DB.LOCATION.LATITUDE, DB.LOCATION.LONGITUDE, DB.LOCATION.ALTITUDE, DB.LOCATION.TYPE };/*w w w. j a v a 2 s .c o m*/ Cursor cursor = mDB.query(DB.LOCATION.TABLE, pColumns, DB.LOCATION.ACTIVITY + " = " + activityId, null, null, null, null); if (cursor.moveToFirst()) { w.name(name); w.beginArray(); startTime = cursor.getLong(0); do { w.beginObject(); w.name("timestamp").value((cursor.getLong(0) - startTime) / 1000); w.name("latitude").value(cursor.getDouble(1)); w.name("longitude").value(cursor.getDouble(2)); if (!cursor.isNull(3)) { w.name("altitude").value(cursor.getDouble(3)); } if (cursor.getLong(4) == DB.LOCATION.TYPE_START) { w.name("type").value("start"); } else if (cursor.getLong(4) == DB.LOCATION.TYPE_END) { w.name("type").value("end"); } else if (cursor.getLong(4) == DB.LOCATION.TYPE_PAUSE) { w.name("type").value("pause"); } else if (cursor.getLong(4) == DB.LOCATION.TYPE_RESUME) { w.name("type").value("resume"); } else if (cursor.getLong(4) == DB.LOCATION.TYPE_GPS) { w.name("type").value("gps"); } else { w.name("type").value("manual"); } w.endObject(); } while (cursor.moveToNext()); w.endArray(); } cursor.close(); }
From source file:com.granita.contacticloudsync.resource.LocalCalendar.java
@SuppressWarnings("Recycle") public void processDirtyExceptions() throws CalendarStorageException { // process deleted exceptions Constants.log.info("Processing deleted exceptions"); try {/*from w w w .ja va 2 s . c o m*/ @Cleanup Cursor cursor = provider.query(syncAdapterURI(Events.CONTENT_URI), new String[] { Events._ID, Events.ORIGINAL_ID, LocalEvent.COLUMN_SEQUENCE }, Events.DELETED + "!=0 AND " + Events.ORIGINAL_ID + " IS NOT NULL", null, null); while (cursor != null && cursor.moveToNext()) { Constants.log.debug("Found deleted exception, removing; then re-schuling original event"); long id = cursor.getLong(0), // can't be null (by definition) originalID = cursor.getLong(1); // can't be null (by query) int sequence = cursor.isNull(2) ? 0 : cursor.getInt(2); // get original event's SEQUENCE @Cleanup Cursor cursor2 = provider.query( syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)), new String[] { LocalEvent.COLUMN_SEQUENCE }, null, null, null); int originalSequence = cursor.isNull(0) ? 0 : cursor.getInt(0); BatchOperation batch = new BatchOperation(provider); // re-schedule original event and set it to DIRTY batch.enqueue(ContentProviderOperation .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID))) .withValue(LocalEvent.COLUMN_SEQUENCE, originalSequence) .withValue(Events.DIRTY, DIRTY_INCREASE_SEQUENCE).build()); // remove exception batch.enqueue(ContentProviderOperation .newDelete(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id))).build()); batch.commit(); } } catch (RemoteException e) { throw new CalendarStorageException("Couldn't process locally modified exception", e); } // process dirty exceptions Constants.log.info("Processing dirty exceptions"); try { @Cleanup Cursor cursor = provider.query(syncAdapterURI(Events.CONTENT_URI), new String[] { Events._ID, Events.ORIGINAL_ID, LocalEvent.COLUMN_SEQUENCE }, Events.DIRTY + "!=0 AND " + Events.ORIGINAL_ID + " IS NOT NULL", null, null); while (cursor != null && cursor.moveToNext()) { Constants.log.debug("Found dirty exception, increasing SEQUENCE to re-schedule"); long id = cursor.getLong(0), // can't be null (by definition) originalID = cursor.getLong(1); // can't be null (by query) int sequence = cursor.isNull(2) ? 0 : cursor.getInt(2); BatchOperation batch = new BatchOperation(provider); // original event to DIRTY batch.enqueue(ContentProviderOperation .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID))) .withValue(Events.DIRTY, DIRTY_DONT_INCREASE_SEQUENCE).build()); // increase SEQUENCE and set DIRTY to 0 batch.enqueue(ContentProviderOperation .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id))) .withValue(LocalEvent.COLUMN_SEQUENCE, sequence + 1).withValue(Events.DIRTY, 0).build()); batch.commit(); } } catch (RemoteException e) { throw new CalendarStorageException("Couldn't process locally modified exception", e); } }
From source file:net.fabiszewski.ulogger.GpxExportService.java
/** * Write <trkseg> tag/*from w ww .j av a 2 s . com*/ * * @param serializer XmlSerializer * @throws IOException IO exception * @throws IllegalArgumentException Xml illegal argument * @throws IllegalStateException Xml illegal state */ private void writePositions(@NonNull XmlSerializer serializer) throws IOException, IllegalArgumentException, IllegalStateException { Cursor cursor = db.getPositions(); // suppress as it requires target api 19 //noinspection TryFinallyCanBeTryWithResources try { serializer.startTag(null, "trkseg"); while (cursor.moveToNext()) { serializer.startTag(null, "trkpt"); serializer.attribute(null, "lat", cursor.getString(cursor.getColumnIndex(DbContract.Positions.COLUMN_LATITUDE))); serializer.attribute(null, "lon", cursor.getString(cursor.getColumnIndex(DbContract.Positions.COLUMN_LONGITUDE))); if (!cursor.isNull(cursor.getColumnIndex(DbContract.Positions.COLUMN_ALTITUDE))) { writeTag(serializer, "ele", cursor.getString(cursor.getColumnIndex(DbContract.Positions.COLUMN_ALTITUDE))); } long timestamp = cursor.getLong(cursor.getColumnIndex(DbContract.Positions.COLUMN_TIME)); String time = DateFormat.format("yyyy-MM-ddThh:mm:ss", timestamp * 1000).toString(); writeTag(serializer, "time", time); writeTag(serializer, "name", cursor.getString(cursor.getColumnIndex(DbContract.Positions._ID))); serializer.endTag(null, "trkpt"); } serializer.endTag(null, "trkseg"); } finally { cursor.close(); } }
From source file:com.lambdasoup.quickfit.alarm.AlarmService.java
/** * Replaces the notification for alarms with a notification about a single workout. * <p>//from ww w. j a va 2s . co m * Relies on the caller to position the cursor on the desired row and to close the cursor. * * @param cursor Cursor to read the workout data from * @param cancelIntent Pending intent to pass on to the content intent, allowing its receiver to * execute it (update notification state in db to the fact that the notification * is now cancelled) */ @WorkerThread private @NonNull NotificationCompat.Builder notifySingleEvent(@NonNull Cursor cursor, PendingIntent cancelIntent) { NotificationCompat.Builder notification = new NotificationCompat.Builder(this); FitActivity fitActivity = FitActivity .fromKey(cursor.getString(cursor.getColumnIndex(WorkoutEntry.ACTIVITY_TYPE)), getResources()); String label = ""; if (!cursor.isNull(cursor.getColumnIndex(WorkoutEntry.LABEL))) { label = cursor.getString(cursor.getColumnIndex(WorkoutEntry.LABEL)); } int durationMinutes = cursor.getInt(cursor.getColumnIndex(WorkoutEntry.DURATION_MINUTES)); String title = getString(R.string.notification_alarm_title_single, fitActivity.displayName); String formattedMinutes = String.format( getResources().getQuantityString(R.plurals.duration_mins_format, durationMinutes), durationMinutes); String content = getString(R.string.notification_alarm_content_single, formattedMinutes, label); notification.setContentTitle(title); notification.setContentText(content); long workoutId = cursor.getLong(cursor.getColumnIndex(WorkoutEntry.WORKOUT_ID)); Intent workoutIntent = new Intent(getApplicationContext(), WorkoutListActivity.class); workoutIntent.putExtra(WorkoutListActivity.EXTRA_SHOW_WORKOUT_ID, workoutId); workoutIntent.putExtra(WorkoutListActivity.EXTRA_NOTIFICATIONS_CANCEL_INTENT, cancelIntent); PendingIntent activityIntent = TaskStackBuilder.create(this).addNextIntentWithParentStack(workoutIntent) .getPendingIntent(Constants.PENDING_INTENT_WORKOUT_LIST, PendingIntent.FLAG_UPDATE_CURRENT); notification.setContentIntent(activityIntent);// open workout list, scroll to workout long scheduleId = cursor.getLong(cursor.getColumnIndex(WorkoutEntry.SCHEDULE_ID)); PendingIntent didItIntent = PendingIntent.getService(getApplicationContext(), Constants.PENDING_INTENT_DID_IT, getIntentOnDidIt(getApplicationContext(), scheduleId, workoutId), PendingIntent.FLAG_UPDATE_CURRENT); notification.addAction(R.drawable.ic_done_white_24dp, getString(R.string.notification_action_did_it), didItIntent); PendingIntent snoozeIntent = PendingIntent.getService(getApplicationContext(), Constants.PENDING_INTENT_SNOOZE, AlarmService.getIntentOnSnooze(this, scheduleId), PendingIntent.FLAG_UPDATE_CURRENT); notification.addAction(R.drawable.ic_alarm_white_24dp, getString(R.string.notification_action_remind_me_later), snoozeIntent); return notification; }
From source file:net.niyonkuru.koodroid.ui.OverviewFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (!data.moveToFirst()) return;//from w w w . ja va2 s . c o m int id = loader.getId(); switch (id) { case SUBSCRIBER_TOKEN: { mSubscriberName.setText(data.getString(SubscribersQuery.FULL_NAME)); break; } case BILL_TOKEN: { mBillTotal.setText(formatMoney(data.getString(BillsQuery.TOTAL))); mBillPastDueBalance.setText(formatMoney(data.getString(BillsQuery.PAST_DUE_BALANCE))); mBillCurrentBalance.setText(formatMoney(data.getString(BillsQuery.CURRENT_CHARGES))); if (!data.isNull(BillsQuery.DUE_DATE)) { mBillDueDate.setTag(Date.valueOf(data.getString(BillsQuery.DUE_DATE))); } mBillUpdateTime.setTag(Timestamp.valueOf(data.getString(BillsQuery.UPDATED))); break; } case TAB_TOKEN: { mTabBalance.setText(formatMoney(data.getString(TabsQuery.BALANCE))); mTabUpdateTime.setTag(Timestamp.valueOf(data.getString(TabsQuery.UPDATED))); break; } } updateTimestamps(); }
From source file:co.nerdart.ourss.adapter.FeedsCursorAdapter.java
@Override protected void bindChildView(View view, Context context, Cursor cursor) { view.findViewById(R.id.indicator).setVisibility(View.INVISIBLE); TextView textView = ((TextView) view.findViewById(android.R.id.text1)); long feedId = cursor.getLong(idPosition); if (feedId == mSelectedFeedId) { view.setBackgroundResource(android.R.color.holo_blue_dark); } else {//from w w w . j a v a 2s. c o m view.setBackgroundResource(android.R.color.transparent); } TextView updateTextView = ((TextView) view.findViewById(android.R.id.text2)); updateTextView.setVisibility(View.VISIBLE); if (cursor.isNull(errorPosition)) { long timestamp = cursor.getLong(lastUpdateColumn); // Date formatting is expensive, look at the cache String formattedDate = mFormattedDateCache.get(timestamp); if (formattedDate == null) { Date date = new Date(timestamp); formattedDate = context.getString(R.string.update) + COLON + (timestamp == 0 ? context.getString(R.string.never) : new StringBuilder(Constants.DATE_FORMAT.format(date)).append(' ') .append(Constants.TIME_FORMAT.format(date))); mFormattedDateCache.put(timestamp, formattedDate); } updateTextView.setText(formattedDate); } else { updateTextView.setText(new StringBuilder(context.getString(R.string.error)).append(COLON) .append(cursor.getString(errorPosition))); } byte[] iconBytes = cursor.getBlob(iconPosition); if (iconBytes != null && iconBytes.length > 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length); if (bitmap != null && bitmap.getHeight() > 0 && bitmap.getWidth() > 0) { int bitmapSizeInDip = UiUtils.dpToPixel(18); if (bitmap.getHeight() != bitmapSizeInDip) { bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false); } textView.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(context.getResources(), bitmap), null, null, null); } else { textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } } else { view.setTag(null); textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } int unreadCount; synchronized (mUnreadItemsByFeed) { unreadCount = mUnreadItemsByFeed.get(feedId); } if (unreadCount > 0) { textView.setEnabled(true); updateTextView.setEnabled(true); } else { textView.setEnabled(false); updateTextView.setEnabled(false); } textView.setText( (cursor.isNull(namePosition) ? cursor.getString(linkPosition) : cursor.getString(namePosition)) + (unreadCount > 0 ? " (" + unreadCount + ")" : "")); View sortView = view.findViewById(R.id.sortitem); if (!sortViews.contains(sortView)) { // as we are reusing views, this is fine sortViews.add(sortView); } sortView.setVisibility(feedSort ? View.VISIBLE : View.GONE); }
From source file:de.uni_koblenz_landau.apow.db.SyncDBHelper.java
/** * Gets modified rows of a table./*from ww w. ja v a 2s . c o m*/ * @param table Table * @return List of rows as JSONObject * @throws JSONException */ public List<JSONObject> getDirtyRows(String table) throws JSONException { String query = null; switch (table) { case "patient": query = "SELECT pa.tribe, pa.creator, pa.date_created, pa.changed_by, pa.date_changed," + " pa.voided, pa.voided_by, pa.date_voided, pa.void_reason, pe.uuid FROM patient" + " pa INNER JOIN person pe ON pe.person_id = pa.patient_id " + " WHERE pa.dirty = 1"; break; case "person": query = "SELECT pe.gender, pe.birthdate, pe.birthdate_estimated, pe.dead, pe.death_date," + " pe.cause_of_death, pe.creator, pe.date_created, pe.changed_by, pe.date_changed," + " pe.voided, pe.voided_by, pe.date_voided, pe.void_reason, pe.uuid FROM person pe" + " WHERE pe.dirty = 1"; break; case "patient_identifier": query = "SELECT pe.uuid AS patient_id, pi.identifier, pi.identifier_type, pi.preferred," + " pi.location_id, pi.creator, pi.date_created, pi.date_changed, pi.changed_by, pi.voided," + " pi.voided_by, pi.date_voided, pi.void_reason, pi.uuid FROM patient_identifier pi" + " INNER JOIN person pe ON pi.patient_id = pe.person_id" + " WHERE pi.dirty = 1"; break; case "person_address": query = "SELECT pe.uuid AS person_id, pa.preferred, pa.address1, pa.address2, pa.city_village," + " pa.state_province, pa.postal_code, pa.country, pa.latitude, pa.longitude, pa.start_date," + " pa.end_date, pa.creator, pa.date_created, pa.voided, pa.voided_by, pa.date_voided," + " pa.void_reason, pa.county_district, pa.address3, pa.address4, pa.address5, pa.address6," + " pa.date_changed, pa.changed_by, pa.uuid FROM person_address pa" + " INNER JOIN person pe ON pa.person_id = pe.person_id" + " WHERE pa.dirty = 1"; break; case "person_name": query = "SELECT pn.preferred, pe.uuid AS person_id, pn.prefix, pn.given_name, pn.middle_name," + " pn.family_name_prefix, pn.family_name, pn.family_name2, pn.family_name_suffix, pn.degree," + " pn.creator, pn.date_created, pn.voided, pn.voided_by, pn.date_voided, pn.void_reason," + " pn.changed_by, pn.date_changed, pn.uuid FROM person_name pn" + " INNER JOIN person pe ON pn.person_id = pe.person_id" + " WHERE pn.dirty = 1"; break; case "encounter": query = "SELECT en.encounter_type, pe.uuid AS patient_id, en.location_id, en.form_id," + " en.encounter_datetime, en.creator, en.date_created, en.voided, en.voided_by," + " en.date_voided, en.void_reason, en.changed_by, en.date_changed, en.visit_id," + " en.uuid FROM encounter en INNER JOIN person pe ON en.patient_id = pe.person_id" + " WHERE en.dirty = 1"; break; case "obs": query = "SELECT pe.uuid AS person_id, o.concept_id, en.uuid AS encounter_id, o.order_id," + " o.obs_datetime, o.location_id, o2.uuid AS obs_group_id, o.accession_number," + " o.value_group_id, o.value_boolean, o.value_coded, o.value_coded_name_id, o.value_drug," + " o.value_datetime, o.value_numeric, o.value_modifier, o.value_text, o.value_complex," + " o.comments, o.creator, o.date_created, o.voided, o.voided_by, o.date_voided, o.void_reason," + " o.uuid, o.previous_version FROM obs o INNER JOIN person pe ON o.person_id = pe.person_id" + " INNER JOIN encounter en ON en.encounter_id = o.encounter_id" + " LEFT JOIN obs o2 ON o2.obs_id = o.obs_group_id" + " WHERE o.dirty = 1 ORDER BY o.obs_group_id"; break; } Cursor cursor = mDatabase.rawQuery(query, new String[] {}); cursor.moveToFirst(); List<JSONObject> items = new ArrayList<>(); JSONObject root; JSONObject obj; // For every row while (!cursor.isAfterLast()) { root = new JSONObject(); obj = new JSONObject(); // For every column for (int i = 0; i < cursor.getColumnCount(); i++) { String key = cursor.getColumnName(i); // Convert value to JSON type if (cursor.isNull(i)) { obj.put(key, JSONObject.NULL); } else { obj.put(key, cursor.getString(i)); } } root.put("table", table); root.put("values", obj); items.add(root); cursor.moveToNext(); } cursor.close(); return items; }
From source file:org.sufficientlysecure.keychain.provider.ProviderHelper.java
public HashMap<String, Object> getGenericData(Uri uri, String[] proj, int[] types) throws NotFoundException { Cursor cursor = mContentResolver.query(uri, proj, null, null, null); try {/*from ww w . j ava 2 s .co m*/ HashMap<String, Object> result = new HashMap<String, Object>(proj.length); if (cursor != null && cursor.moveToFirst()) { int pos = 0; for (String p : proj) { switch (types[pos]) { case FIELD_TYPE_NULL: result.put(p, cursor.isNull(pos)); break; case FIELD_TYPE_INTEGER: result.put(p, cursor.getLong(pos)); break; case FIELD_TYPE_FLOAT: result.put(p, cursor.getFloat(pos)); break; case FIELD_TYPE_STRING: result.put(p, cursor.getString(pos)); break; case FIELD_TYPE_BLOB: result.put(p, cursor.getBlob(pos)); break; } pos += 1; } } return result; } finally { if (cursor != null) { cursor.close(); } } }