Example usage for android.database Cursor isNull

List of usage examples for android.database Cursor isNull

Introduction

In this page you can find the example usage for android.database Cursor isNull.

Prototype

boolean isNull(int columnIndex);

Source Link

Document

Returns true if the value in the indicated column is null.

Usage

From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java

private void downloadAllImages() {
    ContentResolver cr = MainApplication.getContext().getContentResolver();
    Cursor cursor = cr.query(TaskColumns.CONTENT_URI,
            new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.IMG_URL_TO_DL,
                    TaskColumns.NUMBER_ATTEMPT },
            TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NOT_NULL, null, null);

    ArrayList<ContentProviderOperation> operations = new ArrayList<>();

    while (cursor != null && cursor.moveToNext()) {
        long taskId = cursor.getLong(0);
        long entryId = cursor.getLong(1);
        String imgPath = cursor.getString(2);
        int nbAttempt = 0;
        if (!cursor.isNull(3)) {
            nbAttempt = cursor.getInt(3);
        }/*w w  w.  jav  a 2  s. com*/

        try {
            NetworkUtils.downloadImage(entryId, imgPath);

            // If we are here, everything is OK
            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
        } catch (Exception e) {
            if (nbAttempt + 1 > MAX_TASK_ATTEMPT) {
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            } else {
                ContentValues values = new ContentValues();
                values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1);
                operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId))
                        .withValues(values).build());
            }
        }
    }

    if (cursor != null)
        cursor.close();

    if (!operations.isEmpty()) {
        try {
            cr.applyBatch(FeedData.AUTHORITY, operations);
        } catch (Throwable ignored) {
        }
    }
}

From source file:mobisocial.socialkit.musubi.Musubi.java

public DbObj objForId(long localId) {
    Cursor cursor = mContext.getContentResolver().query(DbObj.OBJ_URI,
            new String[] { DbObj.COL_APP_ID, DbObj.COL_TYPE, DbObj.COL_STRING_KEY, DbObj.COL_JSON,
                    DbObj.COL_RAW, DbObj.COL_IDENTITY_ID, DbObj.COL_UNIVERSAL_HASH, DbObj.COL_FEED_ID,
                    DbObj.COL_INT_KEY, DbObj.COL_TIMESTAMP, DbObj.COL_PARENT_ID },
            DbObj.COL_ID + " = ?", new String[] { String.valueOf(localId) }, null);
    try {/*  w w w .  j  a  v a2s.c  o  m*/
        if (cursor == null || !cursor.moveToFirst()) {
            Log.w(TAG, "Obj " + localId + " not found.");
            return null;
        }

        final String appId = cursor.getString(0);
        final String type = cursor.getString(1);
        final String name = cursor.getString(2);
        final JSONObject json = new JSONObject(cursor.getString(3));
        final byte[] raw = cursor.isNull(4) ? null : cursor.getBlob(4);
        final long senderId = cursor.getLong(5);
        final byte[] hash = cursor.getBlob(6);
        final long feedId = cursor.getLong(7);
        final Integer intKey = cursor.isNull(8) ? null : cursor.getInt(8);
        final long timestamp = cursor.getLong(9);
        Long parentId = cursor.isNull(10) ? null : cursor.getLong(10);

        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;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:org.pixmob.freemobile.netstat.ui.ExportTask.java

private void export() throws IOException {
    final File outputFile = new File(Environment.getExternalStorageDirectory(), "freemobilenetstat.csv");
    Log.i(TAG, "Exporting database to " + outputFile.getPath());

    final DateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT);

    final BufferedWriter out = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));

    Cursor c = null;
    try {//from   w ww  . ja  va2  s.  c om
        c = context.getContentResolver().query(Events.CONTENT_URI,
                new String[] { Events.TIMESTAMP, Events.MOBILE_OPERATOR, Events.MOBILE_NETWORK_TYPE,
                        Events.MOBILE_CONNECTED, Events.WIFI_CONNECTED, Events.BATTERY_LEVEL, Events.SCREEN_ON,
                        Events.POWER_ON, Events.FEMTOCELL, Events.FIRST_INSERT },
                null, null, null);
        final int rowCount = c.getCount();
        int currentRow = 0;

        final StringBuilder buf = new StringBuilder(1024);
        buf.append("Timestamp").append(COL_SEP).append("Mobile Operator").append(COL_SEP)
                .append("Mobile Network Type").append(COL_SEP).append("Mobile Connected").append(COL_SEP)
                .append("Femtocell").append(COL_SEP).append("Wi-Fi Connected").append(COL_SEP)
                .append("Screen On").append(COL_SEP).append("Battery").append(COL_SEP).append("Power On")
                .append(COL_SEP).append("First Insert").append(LINE_SEP);
        out.write(buf.toString());

        while (c.moveToNext()) {
            final long t = c.getLong(0);
            final String mobOp = c.isNull(1) ? "" : c.getString(1);
            final int mobNetworkType = c.getInt(2);
            final int mobConn = c.getInt(3) == 1 ? 1 : 0;
            final int wifiOn = c.getInt(4) == 1 ? 1 : 0;
            final int bat = c.getInt(5);
            final int screenOn = c.getInt(6) == 1 ? 1 : 0;
            final int powerOn = c.getInt(7) == 1 ? 1 : 0;
            final int femtocell = c.getInt(8) == 1 ? 1 : 0;
            final int firstInsert = c.getInt(9) == 1 ? 1 : 0;

            buf.delete(0, buf.length());
            buf.append(dateFormatter.format(t)).append(COL_SEP).append(mobOp).append(COL_SEP)
                    .append(mobNetworkType).append(COL_SEP).append(mobConn).append(COL_SEP).append(femtocell)
                    .append(COL_SEP).append(wifiOn).append(COL_SEP).append(screenOn).append(COL_SEP).append(bat)
                    .append(COL_SEP).append(powerOn).append(COL_SEP).append(firstInsert).append(LINE_SEP);
            out.write(buf.toString());

            publishProgress(++currentRow, rowCount);
        }
    } finally {
        try {
            if (c != null)
                c.close();
        } catch (Exception ignore) {
        }

        IOUtils.close(out);

    }
}

From source file:com.android.email.activity.zx.MessageView.java

/**
 * Launch a thread (because of cross-process DB lookup) to check presence of the sender of the
 * message.  When that thread completes, update the UI.
 * //from  w  w  w.j av a  2s  .  co  m
 * This must only be called when mMessage is null (it will hide presence indications) or when
 * mMessage has already seen its headers loaded.
 * 
 * Note:  This is just a polling operation.  A more advanced solution would be to keep the
 * cursor open and respond to presence status updates (in the form of content change
 * notifications).  However, because presence changes fairly slowly compared to the duration
 * of viewing a single message, a simple poll at message load (and onResume) should be
 * sufficient.
 */
private void startPresenceCheck() {
    String email = null;
    try {
        if (mMessage != null) {
            Address sender = mMessage.getFrom()[0];
            email = sender.getAddress();
        }
    } catch (MessagingException me) {
    }
    if (email == null) {
        mHandler.setSenderPresence(0);
        return;
    }
    final String senderEmail = email;

    new Thread() {
        @Override
        public void run() {
            Cursor methodsCursor = getContentResolver().query(
                    Uri.withAppendedPath(Contacts.ContactMethods.CONTENT_URI, "with_presence"),
                    METHODS_WITH_PRESENCE_PROJECTION, Contacts.ContactMethods.DATA + "=?",
                    new String[] { senderEmail }, null);

            int presenceIcon = 0;

            if (methodsCursor != null) {
                if (methodsCursor.moveToFirst() && !methodsCursor.isNull(METHODS_STATUS_COLUMN)) {
                }
                methodsCursor.close();
            }

            mHandler.setSenderPresence(presenceIcon);
        }
    }.start();
}

From source file:com.lambdasoup.quickfit.alarm.AlarmService.java

/**
 * Replaces the notification for alarms with a notification about multiple workouts.
 * <p>//from w w  w .  j a  v  a2 s  . c om
 * Relies on the caller to position the cursor before the first 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 notifyMultipleEvents(@NonNull Cursor cursor,
        PendingIntent cancelIntent) {
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this);

    Intent workoutIntent = new Intent(getApplicationContext(), WorkoutListActivity.class);
    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);

    InboxStyle inboxStyle = new InboxStyle();
    while (cursor.moveToNext()) {
        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 formattedMinutes = String.format(
                getResources().getQuantityString(R.plurals.duration_mins_format, durationMinutes),
                durationMinutes);
        String line = getString(R.string.notification_alarm_content_line_multi, fitActivity.displayName,
                formattedMinutes, label);
        inboxStyle.addLine(line);
    }

    notification.setContentTitle(getString(R.string.notification_alarm_title_multi));
    notification
            .setContentText(getString(R.string.notification_alarm_content_summary_multi, cursor.getCount()));

    notification.setStyle(inboxStyle);

    return notification;
}

From source file:com.granita.icloudcalsync.resource.LocalTaskList.java

@Override
public void populate(Resource record) throws LocalStorageException {
    try {//from w  w w .ja va2 s  .co m
        @Cleanup
        final Cursor cursor = providerClient.query(entriesURI(), new String[] { /*  0 */ entryColumnUID(),
                TaskContract.Tasks.TITLE, TaskContract.Tasks.LOCATION, TaskContract.Tasks.DESCRIPTION,
                TaskContract.Tasks.URL, /*  5 */ TaskContract.Tasks.CLASSIFICATION, TaskContract.Tasks.STATUS,
                TaskContract.Tasks.PERCENT_COMPLETE, /*  8 */ TaskContract.Tasks.TZ, TaskContract.Tasks.DTSTART,
                TaskContract.Tasks.IS_ALLDAY, /* 11 */ TaskContract.Tasks.DUE, TaskContract.Tasks.DURATION,
                TaskContract.Tasks.COMPLETED, /* 14 */ TaskContract.Tasks.CREATED,
                TaskContract.Tasks.LAST_MODIFIED, TaskContract.Tasks.PRIORITY }, entryColumnID() + "=?",
                new String[] { String.valueOf(record.getLocalID()) }, null);

        Task task = (Task) record;
        if (cursor != null && cursor.moveToFirst()) {
            task.setUid(cursor.getString(0));

            if (!cursor.isNull(14))
                task.setCreatedAt(new DateTime(cursor.getLong(14)));
            if (!cursor.isNull(15))
                task.setLastModified(new DateTime(cursor.getLong(15)));

            if (!StringUtils.isEmpty(cursor.getString(1)))
                task.setSummary(cursor.getString(1));

            if (!StringUtils.isEmpty(cursor.getString(2)))
                task.setLocation(cursor.getString(2));

            if (!StringUtils.isEmpty(cursor.getString(3)))
                task.setDescription(cursor.getString(3));

            if (!StringUtils.isEmpty(cursor.getString(4)))
                task.setUrl(cursor.getString(4));

            if (!cursor.isNull(16))
                task.setPriority(cursor.getInt(16));

            if (!cursor.isNull(5))
                switch (cursor.getInt(5)) {
                case TaskContract.Tasks.CLASSIFICATION_PUBLIC:
                    task.setClassification(Clazz.PUBLIC);
                    break;
                case TaskContract.Tasks.CLASSIFICATION_CONFIDENTIAL:
                    task.setClassification(Clazz.CONFIDENTIAL);
                    break;
                default:
                    task.setClassification(Clazz.PRIVATE);
                }

            if (!cursor.isNull(6))
                switch (cursor.getInt(6)) {
                case TaskContract.Tasks.STATUS_IN_PROCESS:
                    task.setStatus(Status.VTODO_IN_PROCESS);
                    break;
                case TaskContract.Tasks.STATUS_COMPLETED:
                    task.setStatus(Status.VTODO_COMPLETED);
                    break;
                case TaskContract.Tasks.STATUS_CANCELLED:
                    task.setStatus(Status.VTODO_CANCELLED);
                    break;
                default:
                    task.setStatus(Status.VTODO_NEEDS_ACTION);
                }
            if (!cursor.isNull(7))
                task.setPercentComplete(cursor.getInt(7));

            TimeZone tz = null;
            if (!cursor.isNull(8))
                tz = DateUtils.getTimeZone(cursor.getString(8));

            if (!cursor.isNull(9) && !cursor.isNull(10)) {
                long ts = cursor.getLong(9);
                boolean allDay = cursor.getInt(10) != 0;

                Date dt;
                if (allDay)
                    dt = new Date(ts);
                else {
                    dt = new DateTime(ts);
                    if (tz != null)
                        ((DateTime) dt).setTimeZone(tz);
                }
                task.setDtStart(new DtStart(dt));
            }

            if (!cursor.isNull(11)) {
                DateTime dt = new DateTime(cursor.getLong(11));
                if (tz != null)
                    dt.setTimeZone(tz);
                task.setDue(new Due(dt));
            }

            if (!cursor.isNull(12))
                task.setDuration(new Duration(new Dur(cursor.getString(12))));

            if (!cursor.isNull(13))
                task.setCompletedAt(new Completed(new DateTime(cursor.getLong(13))));
        }

    } catch (RemoteException e) {
        throw new LocalStorageException("Couldn't process locally stored task", e);
    }
}

From source file:at.bitfire.davdroid.resource.LocalTaskList.java

@Override
public void populate(Resource record) throws LocalStorageException {
    try {/* www.ja v  a2 s .  c  o m*/
        @Cleanup
        final Cursor cursor = providerClient.query(entriesURI(), new String[] { /*  0 */ entryColumnUID(),
                TaskContract.Tasks.TITLE, TaskContract.Tasks.LOCATION, TaskContract.Tasks.DESCRIPTION,
                TaskContract.Tasks.URL, /*  5 */ TaskContract.Tasks.CLASSIFICATION, TaskContract.Tasks.STATUS,
                TaskContract.Tasks.PERCENT_COMPLETE, /*  8 */ TaskContract.Tasks.TZ, TaskContract.Tasks.DTSTART,
                TaskContract.Tasks.IS_ALLDAY, /* 11 */ TaskContract.Tasks.DUE, TaskContract.Tasks.DURATION,
                TaskContract.Tasks.COMPLETED, /* 14 */ TaskContract.Tasks.CREATED,
                TaskContract.Tasks.LAST_MODIFIED, TaskContract.Tasks.PRIORITY }, entryColumnID() + "=?",
                new String[] { String.valueOf(record.getLocalID()) }, null);

        Task task = (Task) record;
        if (cursor != null && cursor.moveToFirst()) {
            task.setUid(cursor.getString(0));

            if (!cursor.isNull(14))
                task.setCreatedAt(new DateTime(cursor.getLong(14)));
            if (!cursor.isNull(15))
                task.setLastModified(new DateTime(cursor.getLong(15)));

            if (!StringUtils.isEmpty(cursor.getString(1)))
                task.setSummary(cursor.getString(1));

            if (!StringUtils.isEmpty(cursor.getString(2)))
                task.setLocation(cursor.getString(2));

            if (!StringUtils.isEmpty(cursor.getString(3)))
                task.setDescription(cursor.getString(3));

            if (!StringUtils.isEmpty(cursor.getString(4)))
                task.setUrl(cursor.getString(4));

            if (!cursor.isNull(16))
                task.setPriority(cursor.getInt(16));

            if (!cursor.isNull(5))
                switch (cursor.getInt(5)) {
                case TaskContract.Tasks.CLASSIFICATION_PUBLIC:
                    task.setClassification(Clazz.PUBLIC);
                    break;
                case TaskContract.Tasks.CLASSIFICATION_CONFIDENTIAL:
                    task.setClassification(Clazz.CONFIDENTIAL);
                    break;
                default:
                    task.setClassification(Clazz.PRIVATE);
                }

            if (!cursor.isNull(6))
                switch (cursor.getInt(6)) {
                case TaskContract.Tasks.STATUS_IN_PROCESS:
                    task.setStatus(Status.VTODO_IN_PROCESS);
                    break;
                case TaskContract.Tasks.STATUS_COMPLETED:
                    task.setStatus(Status.VTODO_COMPLETED);
                    break;
                case TaskContract.Tasks.STATUS_CANCELLED:
                    task.setStatus(Status.VTODO_CANCELLED);
                    break;
                default:
                    task.setStatus(Status.VTODO_NEEDS_ACTION);
                }
            if (!cursor.isNull(7))
                task.setPercentComplete(cursor.getInt(7));

            TimeZone tz = null;
            if (!cursor.isNull(8))
                tz = DateUtils.tzRegistry.getTimeZone(cursor.getString(8));

            if (!cursor.isNull(9) && !cursor.isNull(10)) {
                long ts = cursor.getLong(9);
                boolean allDay = cursor.getInt(10) != 0;

                Date dt;
                if (allDay)
                    dt = new Date(ts);
                else {
                    dt = new DateTime(ts);
                    if (tz != null)
                        ((DateTime) dt).setTimeZone(tz);
                }
                task.setDtStart(new DtStart(dt));
            }

            if (!cursor.isNull(11)) {
                DateTime dt = new DateTime(cursor.getLong(11));
                if (tz != null)
                    dt.setTimeZone(tz);
                task.setDue(new Due(dt));
            }

            if (!cursor.isNull(12))
                task.setDuration(new Duration(new Dur(cursor.getString(12))));

            if (!cursor.isNull(13))
                task.setCompletedAt(new Completed(new DateTime(cursor.getLong(13))));
        }

    } catch (RemoteException e) {
        throw new LocalStorageException("Couldn't process locally stored task", e);
    }
}

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 };/*  www .java  2 s  .c  o  m*/
    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:de.escoand.readdaily.AbstractContentFragment.java

@Override
public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) {
    View source = ((ViewGroup) view.getParent()).findViewById(R.id.daily_source);
    switch (cursor.getColumnName(columnIndex)) {

    // title//from   w w w.j a va2s. c  o  m
    case Database.COLUMN_TITLE:
        switch (cursor.getString(cursor.getColumnIndex(Database.COLUMN_TYPE))) {
        case Database.TYPE_YEAR:
            ((TextView) view).setText(getContext().getString(R.string.type_voty));
            return true;
        case Database.TYPE_MONTH:
            ((TextView) view).setText(getContext().getString(R.string.type_votm));
            return true;
        case Database.TYPE_WEEK:
            ((TextView) view).setText(getContext().getString(R.string.type_votw));
            return true;
        case Database.TYPE_DAY:
            ((TextView) view).setText(getContext().getString(R.string.type_votd));
            source.setVisibility(View.GONE);
            return true;
        default: // do nothing
            break;
        }
        break;

    // text
    case Database.COLUMN_TEXT:
        if (view instanceof TextView) {
            ((TextView) view).setText(Html.fromHtml(cursor.getString(columnIndex)));
            return true;
        }
        break;

    // source
    case Database.COLUMN_SOURCE:
        if (cursor.isNull(columnIndex)) {
            view.setVisibility(View.GONE);
            return true;
        }
        break;

    // do nothing
    default:
        break;
    }

    return false;
}

From source file:com.android.messaging.mmslib.pdu.PduPersister.java

private Integer getIntegerFromPartColumn(final Cursor c, final int columnIndex) {
    if (!c.isNull(columnIndex)) {
        return c.getInt(columnIndex);
    }//from ww  w.  j  a v a  2 s.co  m
    return null;
}