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:org.droidparts.persist.sql.EntityManager.java

protected Object readFromCursor(Cursor cursor, int columnIndex, Class<?> valType, Class<?> arrCollItemType)
        throws IllegalArgumentException {
    if (cursor.isNull(columnIndex)) {
        return null;
    } else if (isBoolean(valType)) {
        return cursor.getInt(columnIndex) == 1;
    } else if (isByte(valType)) {
        return Byte.valueOf(cursor.getString(columnIndex));
    } else if (isByteArray(valType)) {
        return cursor.getBlob(columnIndex);
    } else if (isDouble(valType)) {
        return cursor.getDouble(columnIndex);
    } else if (isFloat(valType)) {
        return cursor.getFloat(columnIndex);
    } else if (isInteger(valType)) {
        return cursor.getInt(columnIndex);
    } else if (isLong(valType)) {
        return cursor.getLong(columnIndex);
    } else if (isShort(valType)) {
        return cursor.getShort(columnIndex);
    } else if (isString(valType)) {
        return cursor.getString(columnIndex);
    } else if (isUUID(valType)) {
        return UUID.fromString(cursor.getString(columnIndex));
    } else if (isDate(valType)) {
        return new Date(cursor.getLong(columnIndex));
    } else if (isBitmap(valType)) {
        byte[] arr = cursor.getBlob(columnIndex);
        return BitmapFactory.decodeByteArray(arr, 0, arr.length);
    } else if (isJsonObject(valType) || isJsonArray(valType)) {
        String str = cursor.getString(columnIndex);
        try {/*from w  ww . j a v  a 2s.  c o  m*/
            return isJsonObject(valType) ? new JSONObject(str) : new JSONArray(str);
        } catch (JSONException e) {
            throw new IllegalArgumentException(e);
        }
    } else if (isEnum(valType)) {
        return instantiateEnum(valType, cursor.getString(columnIndex));
    } else if (isEntity(valType)) {
        long id = cursor.getLong(columnIndex);
        @SuppressWarnings("unchecked")
        Entity entity = instantiate((Class<Entity>) valType);
        entity.id = id;
        return entity;
    } else if (isArray(valType) || isCollection(valType)) {
        String str = cursor.getString(columnIndex);
        String[] parts = (str.length() > 0) ? str.split("\\" + SEP) : new String[0];
        if (isArray(valType)) {
            return toTypeArr(arrCollItemType, parts);
        } else {
            @SuppressWarnings("unchecked")
            Collection<Object> coll = (Collection<Object>) instantiate(valType);
            coll.addAll(toTypeColl(arrCollItemType, parts));
            return coll;
        }
    } else {
        throw new IllegalArgumentException("Need to manually read " + valType.getName() + " from cursor.");
    }
}

From source file:eu.faircode.netguard.LogAdapter.java

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    // Get values
    long time = cursor.getLong(colTime);
    int version = (cursor.isNull(colVersion) ? -1 : cursor.getInt(colVersion));
    int protocol = (cursor.isNull(colProtocol) ? -1 : cursor.getInt(colProtocol));
    //String flags = cursor.getString(colFlags);
    String saddr = cursor.getString(colSAddr);
    int sport = (cursor.isNull(colSPort) ? -1 : cursor.getInt(colSPort));
    String daddr = cursor.getString(colDaddr);
    int dport = (cursor.isNull(colDPort) ? -1 : cursor.getInt(colDPort));
    String dname = (cursor.isNull(colDName) ? null : cursor.getString(colDName));
    int uid = (cursor.isNull(colUid) ? -1 : cursor.getInt(colUid));
    String data = cursor.getString(colData);
    int allowed = (cursor.isNull(colAllowed) ? -1 : cursor.getInt(colAllowed));
    int connection = (cursor.isNull(colConnection) ? -1 : cursor.getInt(colConnection));
    int interactive = (cursor.isNull(colInteractive) ? -1 : cursor.getInt(colInteractive));

    // Get views/*  www.  j  a  va  2  s  .  c  o  m*/
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    TextView tvProtocol = (TextView) view.findViewById(R.id.tvProtocol);
    //TextView tvFlags = (TextView) view.findViewById(R.id.tvFlags);
    TextView tvSAddr = (TextView) view.findViewById(R.id.tvSAddr);
    TextView tvSPort = (TextView) view.findViewById(R.id.tvSPort);
    final TextView tvDaddr = (TextView) view.findViewById(R.id.tvDAddr);
    TextView tvDPort = (TextView) view.findViewById(R.id.tvDPort);
    ImageView ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
    TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
    TextView tvData = (TextView) view.findViewById(R.id.tvData);
    //ImageView ivConnection = (ImageView) view.findViewById(R.id.ivConnection);
    //ImageView ivInteractive = (ImageView) view.findViewById(R.id.ivInteractive);

    // Set values
    tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(time));

    /*if (connection <= 0)
    ivConnection.setImageDrawable(null);
    else {
    if (allowed > 0)
        ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_on : R.drawable.other_on);
    else
        ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_off : R.drawable.other_off);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(ivConnection.getDrawable());
        DrawableCompat.setTint(wrap, allowed > 0 ? colorOn : colorOff);
    }
    }*/

    /*if (interactive <= 0)
    ivInteractive.setImageDrawable(null);
    else {
    ivInteractive.setImageResource(R.drawable.screen_on);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(ivInteractive.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }
    }*/

    tvProtocol.setText(Util.getProtocolName(protocol, version, false));

    //tvFlags.setText(flags);

    if (protocol == 6 || protocol == 17) {
        tvSPort.setText(sport < 0 ? "" : getKnownPort(sport));
        tvDPort.setText(dport < 0 ? "" : getKnownPort(dport));
    } else {
        tvSPort.setText(sport < 0 ? "" : Integer.toString(sport));
        tvDPort.setText(dport < 0 ? "" : Integer.toString(dport));
    }

    // Application icon
    ApplicationInfo info = null;
    PackageManager pm = context.getPackageManager();
    String[] pkg = pm.getPackagesForUid(uid);
    if (pkg != null && pkg.length > 0)
        try {
            info = pm.getApplicationInfo(pkg[0], 0);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    if (info == null || info.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(ivIcon);
    else {
        Uri uri = Uri.parse("android.resource://" + info.packageName + "/" + info.icon);
        Picasso.with(context).load(uri).into(ivIcon);
    }

    // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
    uid = uid % 100000; // strip off user ID
    if (uid == -1)
        tvUid.setText("");
    else if (uid == 0)
        tvUid.setText(context.getString(R.string.title_root));
    else if (uid == 9999)
        tvUid.setText("-"); // nobody
    else
        tvUid.setText(Integer.toString(uid));

    // TODO resolve source when inbound
    tvSAddr.setText(getKnownAddress(saddr));

    if (resolve && !isKnownAddress(daddr))
        if (dname == null) {
            tvDaddr.setText(daddr);
            new AsyncTask<String, Object, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return InetAddress.getByName(args[0]).getHostName();
                    } catch (UnknownHostException ignored) {
                        return args[0];
                    }
                }

                @Override
                protected void onPostExecute(String name) {
                    tvDaddr.setText(name);
                }
            }.execute(daddr);
        } else
            tvDaddr.setText(dname);
    else
        tvDaddr.setText(getKnownAddress(daddr));

    if (TextUtils.isEmpty(data)) {
        tvData.setText("");
        tvData.setVisibility(View.GONE);
    } else {
        tvData.setText(data);
        tvData.setVisibility(View.VISIBLE);
    }
}

From source file:net.niyonkuru.koodroid.ui.UsageFragment.java

private void saveUsageTimestamps(Cursor cursor) {
    if (!cursor.isNull(UsagesQuery.UPDATED)) {
        Timestamp new_timestamp = Timestamp.valueOf(cursor.getString(UsagesQuery.UPDATED));
        Object old_timestamp = mDataUpdatedTime.getTag();

        if (old_timestamp == null || new_timestamp.after((Timestamp) old_timestamp)) {
            mDataUpdatedTime.setTag(new_timestamp);
        }//from ww w  . ja va 2s. c o  m
    }
}

From source file:org.sufficientlysecure.keychain.ui.keyview.loader.KeyserverStatusLoader.java

@Override
public KeyserverStatus loadInBackground() {
    Cursor cursor = contentResolver.query(UpdatedKeys.CONTENT_URI, PROJECTION,
            UpdatedKeys.MASTER_KEY_ID + " = ?", new String[] { Long.toString(masterKeyId) }, null);
    if (cursor == null) {
        Log.e(Constants.TAG, "Error loading key items!");
        return null;
    }//  w  w w. j a  va 2 s .  com

    try {
        if (cursor.moveToFirst()) {
            if (cursor.isNull(INDEX_SEEN_ON_KEYSERVERS) || cursor.isNull(INDEX_LAST_UPDATED)) {
                return new KeyserverStatus(masterKeyId);
            }

            boolean isPublished = cursor.getInt(INDEX_SEEN_ON_KEYSERVERS) != 0;
            Date lastUpdated = new Date(cursor.getLong(INDEX_LAST_UPDATED) * 1000);

            return new KeyserverStatus(masterKeyId, isPublished, lastUpdated);
        }

        return new KeyserverStatus(masterKeyId);
    } finally {
        cursor.close();
    }
}

From source file:org.opendatakit.common.android.database.DataModelDatabaseHelper.java

/**
 * Return a map of (elementKey -> ColumnDefinition)
 *
 * @param db/*from ww  w. j a  v a  2 s  .  co  m*/
 * @param tableId
 * @return
 * @throws JsonParseException
 * @throws JsonMappingException
 * @throws IOException
 */
public static Map<String, ColumnDefinition> getColumnDefinitions(SQLiteDatabase db, String tableId)
        throws JsonParseException, JsonMappingException, IOException {
    Map<String, ColumnDefinition> defn = new HashMap<String, ColumnDefinition>();

    Cursor c = null;
    try {
        c = db.query(COLUMN_DEFINITIONS_TABLE_NAME, null, ColumnDefinitionsColumns.TABLE_ID + "=?",
                new String[] { tableId }, null, null, null);

        if (c.moveToFirst()) {
            int idxEK = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_KEY);
            int idxEN = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_NAME);
            int idxET = c.getColumnIndex(ColumnDefinitionsColumns.ELEMENT_TYPE);
            int idxIP = c.getColumnIndex(ColumnDefinitionsColumns.IS_UNIT_OF_RETENTION);
            int idxLIST = c.getColumnIndex(ColumnDefinitionsColumns.LIST_CHILD_ELEMENT_KEYS);
            HashMap<String, ColumnContainer> ref = new HashMap<String, ColumnContainer>();

            do {
                String elementKey = c.getString(idxEK);
                String elementName = c.getString(idxEN);
                String elementType = c.getString(idxET);
                boolean isUnitOfRetention = (c.getInt(idxIP) != 0);
                String childrenString = c.isNull(idxLIST) ? null : c.getString(idxLIST);
                ColumnContainer ctn = new ColumnContainer();
                ctn.defn = new ColumnDefinition(elementKey, elementName, elementType, isUnitOfRetention);

                if (childrenString != null) {
                    @SuppressWarnings("unchecked")
                    ArrayList<String> l = ODKFileUtils.mapper.readValue(childrenString, ArrayList.class);
                    ctn.children = l;
                }

                ref.put(elementKey, ctn);
            } while (c.moveToNext());

            // OK now connect all the children...

            for (ColumnContainer ctn : ref.values()) {
                if (ctn.children != null) {
                    for (String ek : ctn.children) {
                        ColumnContainer child = ref.get(ek);
                        if (child == null) {
                            throw new IllegalArgumentException("Unexpected missing child element: " + ek);
                        }
                        ctn.defn.addChild(child.defn);
                    }
                }
            }

            // and construct the list of entries...
            for (ColumnContainer ctn : ref.values()) {
                defn.put(ctn.defn.elementKey, ctn.defn);
            }
            return defn;
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return null;
}

From source file:org.akvo.flow.ui.fragment.SurveyListFragment.java

public void refresh() {
    // Calculate if this record is not registered yet
    mRegistered = false;//from w  w  w  . j  a  v a2  s . com
    Cursor cursor = mDatabase.getSurveyInstances(mRecord.getId());
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            final int col = cursor.getColumnIndexOrThrow(SurveyInstanceColumns.SUBMITTED_DATE);
            do {
                if (!cursor.isNull(col)) {
                    mRegistered = true;
                }
            } while (cursor.moveToNext() && !mRegistered);
        }
        cursor.close();
    }

    getLoaderManager().restartLoader(0, null, this);
}

From source file:export.format.FacebookCourse.java

public JSONObject export(long activityId, boolean showTrail, JSONObject runObj)
        throws IOException, JSONException {

    final String[] aColumns = { DB.ACTIVITY.NAME, DB.ACTIVITY.COMMENT, DB.ACTIVITY.START_TIME,
            DB.ACTIVITY.DISTANCE, DB.ACTIVITY.TIME, DB.ACTIVITY.SPORT };
    Cursor cursor = mDB.query(DB.ACTIVITY.TABLE, aColumns, "_id = " + activityId, null, null, null, null);
    cursor.moveToFirst();/*from  w  w w .j a va2  s. c  o m*/

    if (runObj != null) {
        runObj.put("sport", cursor.getInt(5));
        runObj.put("startTime", cursor.getLong(2));
        runObj.put("endTime", cursor.getLong(2) + cursor.getLong(4));
        if (!cursor.isNull(1))
            runObj.put("comment", cursor.getString(1));
    }

    JSONObject obj = new JSONObject();
    double distance = cursor.getDouble(3);
    long duration = cursor.getLong(4);
    cursor.close();

    double unitMeters = formatter.getUnitMeters();
    if (distance < unitMeters) {
        obj.put("distance", new JSONObject().put("value", distance).put("units", "m"));
    } else {
        final int decimals = 1;
        double base = distance / unitMeters;
        double val = Formatter.round(base, decimals);
        obj.put("distance", new JSONObject().put("value", val).put("units", formatter.getUnitString()));
    }

    obj.put("duration", new JSONObject().put("value", duration).put("units", "s"));
    if (distance != 0) {
        obj.put("pace", pace(distance, duration));
    }

    if (showTrail) {
        JSONArray trail = trail(activityId);
        if (trail != null)
            obj.put("metrics", trail);
    }

    return obj;
}

From source file:net.bible.service.db.mynote.MyNoteDBAdapter.java

/** return Dto from current cursor position or null
 * @param c/*w w w .ja v a 2s . co  m*/
 * @return
 * @throws NoSuchKeyException
 */
private MyNoteDto getMyNoteDto(Cursor c) {
    MyNoteDto dto = new MyNoteDto();
    try {
        //Id
        Long id = c.getLong(MyNoteQuery.ID);
        dto.setId(id);

        //Verse
        String key = c.getString(MyNoteQuery.KEY);
        Versification v11n = null;
        if (!c.isNull(MyNoteQuery.VERSIFICATION)) {
            String v11nString = c.getString(MyNoteQuery.VERSIFICATION);
            if (!StringUtils.isEmpty(v11nString)) {
                v11n = Versifications.instance().getVersification(v11nString);
            }
        }
        if (v11n == null) {
            Log.d(TAG, "Using default Versification");
            // use default v11n
            v11n = Versifications.instance().getVersification(Versifications.DEFAULT_V11N);
        }
        Log.d(TAG, "Versification found:" + v11n);
        try {
            dto.setVerse(VerseFactory.fromString(v11n, key));
        } catch (Exception e) {
            Log.e(TAG, "Note saved with incorrect versification", e);
            // fix problem where KJV was always the v11n even for dc books
            // NRSVA should contain most dc books and allow verse to be fetched
            Versification v11nWithDC = Versifications.instance().getVersification("NRSVA");
            dto.setVerse(VerseFactory.fromString(v11nWithDC, key));
        }

        //Note
        String mynote = c.getString(MyNoteQuery.MYNOTE);
        dto.setNoteText(mynote);

        //Update date
        long updated = c.getLong(MyNoteQuery.LAST_UPDATED_ON);
        dto.setLastUpdatedOn(new Date(updated));

        //Create date
        long created = c.getLong(MyNoteQuery.CREATED_ON);
        dto.setCreatedOn(new Date(created));

    } catch (NoSuchKeyException nke) {
        Log.e(TAG, "Key error", nke);
    }

    return dto;
}

From source file:com.bellman.bible.service.db.mynote.MyNoteDBAdapter.java

/**
 * return Dto from current cursor position or null
 *
 * @param c//  w w  w  .ja  v a2  s . co m
 * @return
 * @throws NoSuchKeyException
 */
private MyNoteDto getMyNoteDto(Cursor c) {
    MyNoteDto dto = new MyNoteDto();
    try {
        //Id
        Long id = c.getLong(MyNoteQuery.ID);
        dto.setId(id);

        //Verse
        String key = c.getString(MyNoteQuery.KEY);
        Versification v11n = null;
        if (!c.isNull(MyNoteQuery.VERSIFICATION)) {
            String v11nString = c.getString(MyNoteQuery.VERSIFICATION);
            if (!StringUtils.isEmpty(v11nString)) {
                v11n = Versifications.instance().getVersification(v11nString);
            }
        }
        if (v11n == null) {
            Log.d(TAG, "Using default Versification");
            // use default v11n
            v11n = Versifications.instance().getVersification(Versifications.DEFAULT_V11N);
        }
        Log.d(TAG, "Versification found:" + v11n);
        try {
            dto.setVerseRange(VerseRangeFactory.fromString(v11n, key));
        } catch (Exception e) {
            Log.e(TAG, "Note saved with incorrect versification", e);
            // fix problem where KJV was always the v11n even for dc books
            // NRSVA should contain most dc books and allow verse to be fetched
            Versification v11nWithDC = Versifications.instance().getVersification("NRSVA");
            dto.setVerseRange(VerseRangeFactory.fromString(v11nWithDC, key));
        }

        //Note
        String mynote = c.getString(MyNoteQuery.MYNOTE);
        dto.setNoteText(mynote);

        //Update date
        long updated = c.getLong(MyNoteQuery.LAST_UPDATED_ON);
        dto.setLastUpdatedOn(new Date(updated));

        //Create date
        long created = c.getLong(MyNoteQuery.CREATED_ON);
        dto.setCreatedOn(new Date(created));

    } catch (NoSuchKeyException nke) {
        Log.e(TAG, "Key error", nke);
    }

    return dto;
}

From source file:org.runnerup.export.format.RunKeeper.java

private void exportHeartRate(long activityId, long startTime, JsonWriter w) throws IOException {
    String[] pColumns = { DB.LOCATION.TIME, DB.LOCATION.HR };
    Cursor cursor = mDB.query(DB.LOCATION.TABLE, pColumns, DB.LOCATION.ACTIVITY + " = " + activityId, null,
            null, null, null);/*from www . j  a va 2s. co m*/
    if (cursor.moveToFirst()) {
        startTime = cursor.getLong(0);
        do {
            if (!cursor.isNull(1)) {
                w.beginObject();
                w.name("timestamp").value((cursor.getLong(0) - startTime) / 1000);
                w.name("heart_rate").value(Integer.toString(cursor.getInt(1)));
                w.endObject();
            }
        } while (cursor.moveToNext());
    }
    cursor.close();
}