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:com.android.messaging.mmslib.pdu.PduPersister.java

private byte[] getByteArrayFromPartColumn(final Cursor c, final int columnIndex) {
    if (!c.isNull(columnIndex)) {
        return getBytes(c.getString(columnIndex));
    }/* www  . j  a v  a2 s . c  o m*/
    return null;
}

From source file:org.mozilla.gecko.home.TopSitesPanel.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    mEditPinnedSiteListener = new EditPinnedSiteListener();

    mList.setTag(HomePager.LIST_TAG_TOP_SITES);
    mList.setHeaderDividersEnabled(false);

    mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override/*from   ww  w.j a v  a 2  s .  c o  m*/
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final ListView list = (ListView) parent;
            final int headerCount = list.getHeaderViewsCount();
            if (position < headerCount) {
                // The click is on a header, don't do anything.
                return;
            }

            // Absolute position for the adapter.
            position += (mGridAdapter.getCount() - headerCount);

            final Cursor c = mListAdapter.getCursor();
            if (c == null || !c.moveToPosition(position)) {
                return;
            }

            final String url = c.getString(c.getColumnIndexOrThrow(TopSites.URL));

            Telemetry.sendUIEvent(TelemetryContract.Event.LOAD_URL, TelemetryContract.Method.LIST_ITEM);

            // This item is a TwoLinePageRow, so we allow switch-to-tab.
            mUrlOpenListener.onUrlOpen(url, EnumSet.of(OnUrlOpenListener.Flags.ALLOW_SWITCH_TO_TAB));
        }
    });

    mList.setContextMenuInfoFactory(new HomeContextMenuInfo.Factory() {
        @Override
        public HomeContextMenuInfo makeInfoForCursor(View view, int position, long id, Cursor cursor) {
            final HomeContextMenuInfo info = new HomeContextMenuInfo(view, position, id);
            info.url = cursor.getString(cursor.getColumnIndexOrThrow(TopSites.URL));
            info.title = cursor.getString(cursor.getColumnIndexOrThrow(TopSites.TITLE));
            info.historyId = cursor.getInt(cursor.getColumnIndexOrThrow(TopSites.HISTORY_ID));
            info.itemType = RemoveItemType.HISTORY;
            final int bookmarkIdCol = cursor.getColumnIndexOrThrow(TopSites.BOOKMARK_ID);
            if (cursor.isNull(bookmarkIdCol)) {
                // If this is a combined cursor, we may get a history item without a
                // bookmark, in which case the bookmarks ID column value will be null.
                info.bookmarkId = -1;
            } else {
                info.bookmarkId = cursor.getInt(bookmarkIdCol);
            }
            return info;
        }
    });

    mGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TopSitesGridItemView item = (TopSitesGridItemView) view;

            // Decode "user-entered" URLs before loading them.
            String url = StringUtils.decodeUserEnteredUrl(item.getUrl());
            int type = item.getType();

            // If the url is empty, the user can pin a site.
            // If not, navigate to the page given by the url.
            if (type != TopSites.TYPE_BLANK) {
                if (mUrlOpenListener != null) {
                    final TelemetryContract.Method method;
                    if (type == TopSites.TYPE_SUGGESTED) {
                        method = TelemetryContract.Method.SUGGESTION;
                    } else {
                        method = TelemetryContract.Method.GRID_ITEM;
                    }
                    Telemetry.sendUIEvent(TelemetryContract.Event.LOAD_URL, method, Integer.toString(position));

                    // Record tile click events on non-private tabs.
                    final Tab tab = Tabs.getInstance().getSelectedTab();
                    if (!tab.isPrivate()) {
                        final Locale locale = Locale.getDefault();
                        final String localeTag = Locales.getLanguageTag(locale);
                        TilesRecorder.recordAction(tab, TilesRecorder.ACTION_CLICK, position,
                                getTilesSnapshot(), localeTag);
                    }

                    mUrlOpenListener.onUrlOpen(url, EnumSet.noneOf(OnUrlOpenListener.Flags.class));
                }
            } else {
                if (mEditPinnedSiteListener != null) {
                    mEditPinnedSiteListener.onEditPinnedSite(position, "");
                }
            }
        }
    });

    mGrid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Cursor cursor = (Cursor) parent.getItemAtPosition(position);

            TopSitesGridItemView item = (TopSitesGridItemView) view;
            if (cursor == null || item.getType() == TopSites.TYPE_BLANK) {
                mGrid.setContextMenuInfo(null);
                return false;
            }

            TopSitesGridContextMenuInfo contextMenuInfo = new TopSitesGridContextMenuInfo(view, position, id);
            updateContextMenuFromCursor(contextMenuInfo, cursor);
            mGrid.setContextMenuInfo(contextMenuInfo);
            return mGrid.showContextMenuForChild(mGrid);
        }

        /*
         * Update the fields of a TopSitesGridContextMenuInfo object
         * from a cursor.
         *
         * @param  info    context menu info object to be updated
         * @param  cursor  used to update the context menu info object
         */
        private void updateContextMenuFromCursor(TopSitesGridContextMenuInfo info, Cursor cursor) {
            info.url = cursor.getString(cursor.getColumnIndexOrThrow(TopSites.URL));
            info.title = cursor.getString(cursor.getColumnIndexOrThrow(TopSites.TITLE));
            info.type = cursor.getInt(cursor.getColumnIndexOrThrow(TopSites.TYPE));
            info.historyId = cursor.getInt(cursor.getColumnIndexOrThrow(TopSites.HISTORY_ID));
        }
    });

    registerForContextMenu(mList);
    registerForContextMenu(mGrid);
}

From source file:com.geniusgithub.contact.contact.model.ContactLoader.java

/**
 * Loads groups meta-data for all groups associated with all constituent raw contacts'
 * accounts./*  w w  w .  j  a v a2s .c o m*/
 */
private void loadGroupMetaData(Contact result) {
    StringBuilder selection = new StringBuilder();
    ArrayList<String> selectionArgs = new ArrayList<String>();
    for (RawContact rawContact : result.getRawContacts()) {
        final String accountName = rawContact.getAccountName();
        final String accountType = rawContact.getAccountTypeString();
        final String dataSet = rawContact.getDataSet();
        if (accountName != null && accountType != null) {
            if (selection.length() != 0) {
                selection.append(" OR ");
            }
            selection.append("(" + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=?");
            selectionArgs.add(accountName);
            selectionArgs.add(accountType);

            if (dataSet != null) {
                selection.append(" AND " + Groups.DATA_SET + "=?");
                selectionArgs.add(dataSet);
            } else {
                selection.append(" AND " + Groups.DATA_SET + " IS NULL");
            }
            selection.append(")");
        }
    }
    final ImmutableList.Builder<GroupMetaData> groupListBuilder = new ImmutableList.Builder<GroupMetaData>();
    final Cursor cursor = getContext().getContentResolver().query(Groups.CONTENT_URI, GroupQuery.COLUMNS,
            selection.toString(), selectionArgs.toArray(new String[0]), null);
    if (cursor != null) {
        try {
            while (cursor.moveToNext()) {
                final String accountName = cursor.getString(GroupQuery.ACCOUNT_NAME);
                final String accountType = cursor.getString(GroupQuery.ACCOUNT_TYPE);
                final String dataSet = cursor.getString(GroupQuery.DATA_SET);
                final long groupId = cursor.getLong(GroupQuery.ID);
                final String title = cursor.getString(GroupQuery.TITLE);
                final boolean defaultGroup = cursor.isNull(GroupQuery.AUTO_ADD) ? false
                        : cursor.getInt(GroupQuery.AUTO_ADD) != 0;
                final boolean favorites = cursor.isNull(GroupQuery.FAVORITES) ? false
                        : cursor.getInt(GroupQuery.FAVORITES) != 0;

                groupListBuilder.add(new GroupMetaData(accountName, accountType, dataSet, groupId, title,
                        defaultGroup, favorites));
            }
        } finally {
            cursor.close();
        }
    }
    result.setGroupMetaData(groupListBuilder.build());
}

From source file:cz.maresmar.sfm.view.menu.MenuViewAdapter.java

@Override
public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {
    viewHolder.mLabel.setText(cursor.getString(2));

    int rawCredit = cursor.getInt(3);
    viewHolder.mPrice.setText(MenuUtils.getPriceStr(viewHolder.mPrice.getContext(), rawCredit));
    viewHolder.mText.setText(cursor.getString(4));
    // Remaining orders
    int remainingToOrder = cursor.getInt(5);
    int remainingToTake = cursor.getInt(6);
    if (remainingToTake >= 0) {
        viewHolder.mRemaining.setText(String.valueOf(remainingToTake));
    } else {/*from  w ww  . j a va  2s .  c o  m*/
        if (remainingToOrder > 0) {
            viewHolder.mRemaining.setText(String.valueOf(remainingToOrder));
        } else {
            viewHolder.mRemaining.setText("");
        }
    }

    // Status icon
    int menuStatus = cursor.getInt(7);
    int syncedTakenAmount = cursor.getInt(8);
    int syncedReservedAmount = cursor.getInt(9);
    int syncedOfferedAmount = cursor.getInt(10);

    @ProviderContract.ActionSyncStatus
    int lowestSyncStatus;
    int lowestReserved;
    int lowestOffered;
    if (!cursor.isNull(13)) {
        lowestSyncStatus = ProviderContract.ACTION_SYNC_STATUS_EDIT;
        lowestReserved = cursor.getInt(13);
        lowestOffered = cursor.getInt(14);
    } else if (!cursor.isNull(11)) {
        lowestSyncStatus = ProviderContract.ACTION_SYNC_STATUS_LOCAL;
        lowestReserved = cursor.getInt(11);
        lowestOffered = cursor.getInt(12);
    } else {
        lowestSyncStatus = ProviderContract.ACTION_SYNC_STATUS_SYNCED;
        lowestReserved = cursor.getInt(9);
        lowestOffered = cursor.getInt(10);
    }

    @Action
    int onClickAction = getAction(lowestSyncStatus, lowestReserved, lowestOffered, syncedReservedAmount,
            syncedOfferedAmount, syncedTakenAmount, menuStatus, remainingToOrder);

    long date = cursor.getLong(DATE_COLUMN_INDEX);
    if (date < MenuUtils.getTodayDate()) {
        onClickAction = ACTION_DISABLED;
    }

    showIcon(viewHolder, onClickAction != ACTION_DISABLED, lowestSyncStatus, lowestReserved, lowestOffered,
            syncedTakenAmount);

    // OnClick listener
    long relativeId = cursor.getLong(15);
    long portalId = cursor.getLong(PORTAL_COLUMN_INDEX);
    MenuEntryInfo menuInfo = new MenuEntryInfo(relativeId, portalId, onClickAction, syncedReservedAmount,
            syncedOfferedAmount);
    viewHolder.itemView.setTag(menuInfo);

    viewHolder.itemView.setOnClickListener(mOnClickListener);
    viewHolder.itemView.setOnLongClickListener(mOnLongClickListener);
}

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

private void setLongToHeaders(final Cursor c, final int columnIndex, final PduHeaders headers,
        final int mapColumn) {
    if (!c.isNull(columnIndex)) {
        final long l = c.getLong(columnIndex);
        headers.setLongInteger(l, mapColumn);
    }/*from  w w  w  .  j av  a  2  s  .  c o  m*/
}

From source file:com.android.contacts.common.model.ContactLoader.java

/**
 * Loads groups meta-data for all groups associated with all constituent raw contacts'
 * accounts.//  w  ww .ja  v  a2s . com
 */
private void loadGroupMetaData(Contact result) {
    StringBuilder selection = new StringBuilder();
    ArrayList<String> selectionArgs = new ArrayList<String>();
    final HashSet<AccountKey> accountsSeen = new HashSet<>();
    for (RawContact rawContact : result.getRawContacts()) {
        final String accountName = rawContact.getAccountName();
        final String accountType = rawContact.getAccountTypeString();
        final String dataSet = rawContact.getDataSet();
        final AccountKey accountKey = new AccountKey(accountName, accountType, dataSet);
        if (accountName != null && accountType != null && !accountsSeen.contains(accountKey)) {
            accountsSeen.add(accountKey);
            if (selection.length() != 0) {
                selection.append(" OR ");
            }
            selection.append("(" + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=?");
            selectionArgs.add(accountName);
            selectionArgs.add(accountType);

            if (dataSet != null) {
                selection.append(" AND " + Groups.DATA_SET + "=?");
                selectionArgs.add(dataSet);
            } else {
                selection.append(" AND " + Groups.DATA_SET + " IS NULL");
            }
            selection.append(")");
        }
    }
    final ImmutableList.Builder<GroupMetaData> groupListBuilder = new ImmutableList.Builder<GroupMetaData>();
    final Cursor cursor = getContext().getContentResolver().query(Groups.CONTENT_URI, GroupQuery.COLUMNS,
            selection.toString(), selectionArgs.toArray(new String[0]), null);
    if (cursor != null) {
        try {
            while (cursor.moveToNext()) {
                final String accountName = cursor.getString(GroupQuery.ACCOUNT_NAME);
                final String accountType = cursor.getString(GroupQuery.ACCOUNT_TYPE);
                final String dataSet = cursor.getString(GroupQuery.DATA_SET);
                final long groupId = cursor.getLong(GroupQuery.ID);
                final String title = cursor.getString(GroupQuery.TITLE);
                final boolean defaultGroup = cursor.isNull(GroupQuery.AUTO_ADD) ? false
                        : cursor.getInt(GroupQuery.AUTO_ADD) != 0;
                final boolean favorites = cursor.isNull(GroupQuery.FAVORITES) ? false
                        : cursor.getInt(GroupQuery.FAVORITES) != 0;

                groupListBuilder.add(new GroupMetaData(accountName, accountType, dataSet, groupId, title,
                        defaultGroup, favorites));
            }
        } finally {
            cursor.close();
        }
    }
    result.setGroupMetaData(groupListBuilder.build());
}

From source file:org.mozilla.mozstumbler.service.sync.UploadReports.java

private BatchRequestStats getRequestBody(Cursor cursor) {
    int wifiCount = 0;
    int cellCount = 0;
    JSONArray items = new JSONArray();

    int columnId = cursor.getColumnIndex(DatabaseContract.Reports._ID);
    int columnTime = cursor.getColumnIndex(DatabaseContract.Reports.TIME);
    int columnLat = cursor.getColumnIndex(DatabaseContract.Reports.LAT);
    int columnLon = cursor.getColumnIndex(DatabaseContract.Reports.LON);
    int columnAltitude = cursor.getColumnIndex(DatabaseContract.Reports.ALTITUDE);
    int columnAccuracy = cursor.getColumnIndex(DatabaseContract.Reports.ACCURACY);
    int columnRadio = cursor.getColumnIndex(DatabaseContract.Reports.RADIO);
    int columnCell = cursor.getColumnIndex(DatabaseContract.Reports.CELL);
    int columnWifi = cursor.getColumnIndex(DatabaseContract.Reports.WIFI);
    int columnCellCount = cursor.getColumnIndex(DatabaseContract.Reports.CELL_COUNT);
    int columnWifiCount = cursor.getColumnIndex(DatabaseContract.Reports.WIFI_COUNT);

    cursor.moveToPosition(-1);/*from ww w  .j a va  2  s .c o  m*/
    try {
        while (cursor.moveToNext()) {
            JSONObject item = new JSONObject();
            item.put("time", DateTimeUtils.formatTime(DateTimeUtils.removeDay(cursor.getLong(columnTime))));
            item.put("lat", cursor.getDouble(columnLat));
            item.put("lon", cursor.getDouble(columnLon));
            if (!cursor.isNull(columnAltitude)) {
                item.put("altitude", cursor.getInt(columnAltitude));
            }
            if (!cursor.isNull(columnAccuracy)) {
                item.put("accuracy", cursor.getInt(columnAccuracy));
            }
            item.put("radio", cursor.getString(columnRadio));
            item.put("cell", new JSONArray(cursor.getString(columnCell)));
            item.put("wifi", new JSONArray(cursor.getString(columnWifi)));
            items.put(item);

            cellCount += cursor.getInt(columnCellCount);
            wifiCount += cursor.getInt(columnWifiCount);
        }
    } catch (JSONException jsonex) {
        Log.e(LOGTAG, "JSONException", jsonex);
    }

    if (items.length() == 0) {
        return null;
    }

    long minId, maxId;
    cursor.moveToFirst();
    minId = cursor.getLong(columnId);
    cursor.moveToLast();
    maxId = cursor.getLong(columnId);

    JSONObject wrapper = new JSONObject(Collections.singletonMap("items", items));
    return new BatchRequestStats(wrapper.toString().getBytes(), wifiCount, cellCount, items.length(), minId,
            maxId);
}

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

private void setOctetToHeaders(final Cursor c, final int columnIndex, final PduHeaders headers,
        final int mapColumn) throws InvalidHeaderValueException {
    if (!c.isNull(columnIndex)) {
        final int b = c.getInt(columnIndex);
        headers.setOctet(b, mapColumn);/*from w w w  .j av  a  2  s  . c om*/
    }
}

From source file:com.safecell.HomeScreenActivity.java

private void recentTripLog() {
    TripJourneysRepository tripJourneysRepository = new TripJourneysRepository(HomeScreenActivity.this);
    TripRepository tripRepository = new TripRepository(HomeScreenActivity.this);

    Cursor cursorTripJounery = tripJourneysRepository.SelectTrip_journeys();
    startManagingCursor(cursorTripJounery);
    tripJourneysRepository.SelectTrip_journeys().close();

    float totalPositivePoints = tripJourneysRepository.getPointsSum();
    // Log.v("totalPositivePoints", ""+totalPositivePoints);
    float totalSafeMilePoints = tripJourneysRepository.getSafeMilePointsSum();
    // Log.v("totalSafeMilePoints", ""+totalSafeMilePoints);

    float grade = 0;

    if (totalPositivePoints > 0) {
        grade = totalSafeMilePoints / totalPositivePoints;

    }//w w  w . j  a  v a2s. c o  m
    grade = grade * 100;
    // Log.v("grade", "" + grade);
    int ratioInt = Math.round(grade);
    if (ratioInt < 0) {
        ratioInt = 0;
    }

    Cursor cursorTotalPointsMiles = tripJourneysRepository.sumOfPointsMiles();
    startManagingCursor(cursorTotalPointsMiles);
    tripJourneysRepository.sumOfPointsMiles().close();
    cursorTotalPointsMiles.moveToFirst();

    ProfilesRepository profileRepository = new ProfilesRepository(HomeScreenActivity.this);
    tvUserName.setText(profileRepository.getName() + "");

    if (cursorTotalPointsMiles.getCount() > 0 && !cursorTotalPointsMiles.isNull(0)) {
        cursorTotalPointsMiles.moveToFirst();

        overallTotalPoints = cursorTotalPointsMiles.getString(0);

        totalTrips = tripRepository.getTripCount();
        tvTotalMiles.setText("" + (int) totalSafeMilePoints);
        tvTotalTrips.setText("" + totalTrips);
        tvGrade.setText("" + ratioInt + "%");
    }
    cursorTotalPointsMiles.close();

    pointsArray = new int[cursorTripJounery.getCount()];
    milesArray = new String[cursorTripJounery.getCount()];
    tripRecordedDateArray = new String[cursorTripJounery.getCount()];
    tripIdArray = new int[cursorTripJounery.getCount()];

    if (cursorTripJounery.getCount() > 0) {
        noTripsSavedTextView.setVisibility(View.INVISIBLE);
        cursorTripJounery.moveToFirst();
        do {
            int tripIdIndex = cursorTripJounery.getColumnIndex("trip_journey_id");
            int milesIndex = cursorTripJounery.getColumnIndex("miles");
            int pointsIndex = cursorTripJounery.getColumnIndex("points");
            int trip_dateIndex = cursorTripJounery.getColumnIndex("trip_date");

            int tripId = cursorTripJounery.getInt(tripIdIndex);
            String miles = "" + Math.round(Double.valueOf(cursorTripJounery.getString(milesIndex)));
            int points = cursorTripJounery.getInt(pointsIndex);
            long tripDate = cursorTripJounery.getLong(trip_dateIndex);

            String formatTripDate = DateUtils.dateInString(tripDate);
            Log.e(TAG, "(Milli)tripDate: " + tripDate + " formatedTripDate: " + formatTripDate);
            pointsArray[arrayIndex] = points;
            milesArray[arrayIndex] = miles + " Total Miles";
            tripRecordedDateArray[arrayIndex] = formatTripDate;
            tripIdArray[arrayIndex] = tripId;
            arrayIndex = arrayIndex + 1;

        } while (cursorTripJounery.moveToNext());

        cursorTripJounery.close();

        tripNameArray = tripRepository.SelectTripName();

    }

}

From source file:org.thialfihar.android.apg.ui.ViewKeyMainFragment.java

public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Swap the new cursor in. (The framework will take care of closing the
    // old cursor once we return.)
    switch (loader.getId()) {
    case LOADER_ID_KEYRING:
        if (data.moveToFirst()) {
            // get name, email, and comment from USER_ID
            String[] mainUserId = PgpKeyHelper.splitUserId(data.getString(KEYRING_INDEX_USER_ID));
            if (mainUserId[0] != null) {
                getActivity().setTitle(mainUserId[0]);
                mName.setText(mainUserId[0]);
            } else {
                getActivity().setTitle(R.string.user_id_no_name);
                mName.setText(R.string.user_id_no_name);
            }//from  ww w .  j  a va  2 s. c  o m
            mEmail.setText(mainUserId[1]);
            mComment.setText(mainUserId[2]);
        }

        break;
    case LOADER_ID_USER_IDS:
        mUserIdsAdapter.swapCursor(data);
        break;
    case LOADER_ID_KEYS:
        // the first key here is our master key
        if (data.moveToFirst()) {
            // get key id from MASTER_KEY_ID
            long keyId = data.getLong(KEYS_INDEX_KEY_ID);
            String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId);
            mKeyId.setText(keyIdStr);

            // get creation date from CREATION
            if (data.isNull(KEYS_INDEX_CREATION)) {
                mCreation.setText(R.string.none);
            } else {
                Date creationDate = new Date(data.getLong(KEYS_INDEX_CREATION) * 1000);

                mCreation.setText(
                        DateFormat.getDateFormat(getActivity().getApplicationContext()).format(creationDate));
            }

            // get expiry date from EXPIRY
            if (data.isNull(KEYS_INDEX_EXPIRY)) {
                mExpiry.setText(R.string.none);
            } else {
                Date expiryDate = new Date(data.getLong(KEYS_INDEX_EXPIRY) * 1000);

                mExpiry.setText(
                        DateFormat.getDateFormat(getActivity().getApplicationContext()).format(expiryDate));
            }

            String algorithmStr = PgpKeyHelper.getAlgorithmInfo(data.getInt(KEYS_INDEX_ALGORITHM),
                    data.getInt(KEYS_INDEX_KEY_SIZE));
            mAlgorithm.setText(algorithmStr);

            byte[] fingerprintBlob = data.getBlob(KEYS_INDEX_FINGERPRINT);
            if (fingerprintBlob == null) {
                // FALLBACK for old database entries
                fingerprintBlob = ProviderHelper.getFingerprint(getActivity(), mDataUri);
            }
            String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob);

            mFingerprint.setText(PgpKeyHelper.colorizeFingerprint(fingerprint));
        }

        mKeysAdapter.swapCursor(data);
        break;

    default:
        break;
    }
}