Example usage for android.database Cursor getBlob

List of usage examples for android.database Cursor getBlob

Introduction

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

Prototype

byte[] getBlob(int columnIndex);

Source Link

Document

Returns the value of the requested column as a byte array.

Usage

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 * Get issue picture from SQlite according to issue id
 * // w  w  w  .  j av  a 2s .  co  m
 * @param IssueID
 * @return
 */
public IssuePic getIssuePic(int IssueID) {
    SQLiteDatabase db = this.getReadableDatabase();
    IssuePic mIssuePic;

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cr = db.query(TABLE_IssuesPics, new String[] { KEY_IssueID, KEY_IssuePicData }, KEY_IssueID + "=?",
            new String[] { Integer.toString(IssueID) }, null, null, null, null);

    boolean ExistsRes = cr.moveToFirst();

    if (!ExistsRes) {
        mIssuePic = new IssuePic(-1, null);
    } else {

        mIssuePic = new IssuePic(cr.getInt(0), cr.getBlob(1));
    }
    cr.close();
    if (db.isOpen())
        db.close();

    return mIssuePic;
}

From source file:com.android.launcher3.Utilities.java

public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
    byte[] data = c.getBlob(iconIndex);
    try {/* w  w w .  j a v a  2  s .co  m*/
        return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
    } catch (Exception e) {
        return null;
    }
}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 *  Get Issue Thumb from SQLite table according to issue id.
 * //  w  w w .j  ava  2s  . com
 * @param IssueID
 * @return
 */
public IssuePic getIssueThumb(int IssueID) {
    SQLiteDatabase db = this.getReadableDatabase();
    IssuePic mIssueThumb;

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cr = db.query(TABLE_IssuesThumbs, new String[] { KEY_IssueID, KEY_IssueThumbData },
            KEY_IssueID + "=?", new String[] { Integer.toString(IssueID) }, null, null, null, null);

    boolean ExistsRes = cr.moveToFirst();

    if (!ExistsRes) {
        mIssueThumb = new IssuePic(-1, null);
    } else {
        mIssueThumb = new IssuePic(cr.getInt(0), cr.getBlob(1));
    }
    cr.close();

    if (db.isOpen())
        db.close();

    return mIssueThumb;
}

From source file:org.sufficientlysecure.keychain.ui.ViewCertActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data.moveToFirst()) {
        String signeeKey = PgpKeyHelper.convertKeyIdToHex(data.getLong(INDEX_MASTER_KEY_ID));
        mSigneeKey.setText(signeeKey);//from w w  w.  j a v  a  2s.co m

        String signeeUid = data.getString(INDEX_USER_ID);
        mSigneeUid.setText(signeeUid);

        Date creationDate = new Date(data.getLong(INDEX_CREATION) * 1000);
        mCreation.setText(DateFormat.getDateFormat(getApplicationContext()).format(creationDate));

        mCertifierKeyId = data.getLong(INDEX_KEY_ID_CERTIFIER);
        String certifierKey = PgpKeyHelper.convertKeyIdToHex(mCertifierKeyId);
        mCertifierKey.setText(certifierKey);

        String certifierUid = data.getString(INDEX_SIGNER_UID);
        if (certifierUid != null) {
            mCertifierUid.setText(certifierUid);
        } else {
            mCertifierUid.setText(R.string.unknown_uid);
        }

        WrappedSignature sig = WrappedSignature.fromBytes(data.getBlob(INDEX_DATA));
        try {
            ProviderHelper providerHelper = new ProviderHelper(this);

            WrappedPublicKeyRing signeeRing = providerHelper
                    .getWrappedPublicKeyRing(data.getLong(INDEX_MASTER_KEY_ID));
            WrappedPublicKeyRing signerRing = providerHelper.getWrappedPublicKeyRing(sig.getKeyId());

            try {
                sig.init(signerRing.getSubkey());
                if (sig.verifySignature(signeeRing.getSubkey(), signeeUid)) {
                    mStatus.setText(R.string.cert_verify_ok);
                    mStatus.setTextColor(getResources().getColor(R.color.bbutton_success));
                } else {
                    mStatus.setText(R.string.cert_verify_failed);
                    mStatus.setTextColor(getResources().getColor(R.color.alert));
                }
            } catch (PgpGeneralException e) {
                mStatus.setText(R.string.cert_verify_error);
                mStatus.setTextColor(getResources().getColor(R.color.alert));
            }
        } catch (ProviderHelper.NotFoundException e) {
            mStatus.setText(R.string.cert_verify_unavailable);
            mStatus.setTextColor(getResources().getColor(R.color.black));
        }

        String algorithmStr = PgpKeyHelper.getAlgorithmInfo(this, sig.getKeyAlgorithm(), 0);
        mAlgorithm.setText(algorithmStr);

        mRowReason.setVisibility(View.GONE);
        switch (data.getInt(INDEX_TYPE)) {
        case WrappedSignature.DEFAULT_CERTIFICATION:
            mType.setText(R.string.cert_default);
            break;
        case WrappedSignature.NO_CERTIFICATION:
            mType.setText(R.string.cert_none);
            break;
        case WrappedSignature.CASUAL_CERTIFICATION:
            mType.setText(R.string.cert_casual);
            break;
        case WrappedSignature.POSITIVE_CERTIFICATION:
            mType.setText(R.string.cert_positive);
            break;
        case WrappedSignature.CERTIFICATION_REVOCATION: {
            mType.setText(R.string.cert_revoke);
            if (sig.isRevocation()) {
                try {
                    mReason.setText(sig.getRevocationReason());
                } catch (PgpGeneralException e) {
                    mReason.setText(R.string.none);
                }
                mRowReason.setVisibility(View.VISIBLE);
            }
            break;
        }
        }
    }

    // can't do this before the data is initialized
    mViewCertifierButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent viewIntent = new Intent(ViewCertActivity.this, ViewKeyActivity.class);

            try {
                ProviderHelper providerHelper = new ProviderHelper(ViewCertActivity.this);
                long signerMasterKeyId = providerHelper
                        .getCachedPublicKeyRing(KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(mCertifierKeyId))
                        .getMasterKeyId();
                viewIntent.setData(KeyRings.buildGenericKeyRingUri(signerMasterKeyId));
                startActivity(viewIntent);
            } catch (PgpGeneralException e) {
                // TODO notify user of this, maybe offer download?
                Log.e(Constants.TAG, "key not found!", e);
            }
        }
    });
}

From source file:com.android.ex.chips.BaseRecipientAdapter.java

private void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri) {
    final AsyncTask<Void, Void, byte[]> photoLoadTask = new AsyncTask<Void, Void, byte[]>() {
        @Override/*from w  ww.java  2 s.  c o  m*/
        protected byte[] doInBackground(Void... params) {
            // First try running a query. Images for local contacts are
            // loaded by sending a query to the ContactsProvider.
            final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null,
                    null, null);
            if (photoCursor != null) {
                try {
                    if (photoCursor.moveToFirst()) {
                        return photoCursor.getBlob(PhotoQuery.PHOTO);
                    }
                } finally {
                    photoCursor.close();
                }
            } else {
                // If the query fails, try streaming the URI directly.
                // For remote directory images, this URI resolves to the
                // directory provider and the images are loaded by sending
                // an openFile call to the provider.
                try {
                    InputStream is = mContentResolver.openInputStream(photoThumbnailUri);
                    if (is != null) {
                        byte[] buffer = new byte[BUFFER_SIZE];
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        try {
                            int size;
                            while ((size = is.read(buffer)) != -1) {
                                baos.write(buffer, 0, size);
                            }
                        } finally {
                            is.close();
                        }
                        return baos.toByteArray();
                    }
                } catch (IOException ex) {
                    // ignore
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(final byte[] photoBytes) {
            entry.setPhotoBytes(photoBytes);
            if (photoBytes != null) {
                mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
                notifyDataSetChanged();
            }
        }
    };
    photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}

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

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data.moveToFirst()) {
        String signeeKey = PgpKeyHelper.convertKeyIdToHex(data.getLong(INDEX_MASTER_KEY_ID));
        mSigneeKey.setText(signeeKey);/*  w ww .jav a2s .com*/

        String signeeUid = data.getString(INDEX_USER_ID);
        mSigneeUid.setText(signeeUid);

        Date creationDate = new Date(data.getLong(INDEX_CREATION) * 1000);
        mCreation.setText(DateFormat.getDateFormat(getApplicationContext()).format(creationDate));

        mCertifierKeyId = data.getLong(INDEX_KEY_ID_CERTIFIER);
        String certifierKey = PgpKeyHelper.convertKeyIdToHex(mCertifierKeyId);
        mCertifierKey.setText(certifierKey);

        String certifierUid = data.getString(INDEX_SIGNER_UID);
        if (certifierUid != null) {
            mCertifierUid.setText(certifierUid);
        } else {
            mCertifierUid.setText(R.string.unknown_uid);
        }

        PGPSignature sig = PgpConversionHelper.BytesToPGPSignature(data.getBlob(INDEX_DATA));
        try {
            ProviderHelper providerHelper = new ProviderHelper(this);
            PGPKeyRing signeeRing = providerHelper.getPGPKeyRing(ApgContract.KeyRingData
                    .buildPublicKeyRingUri(Long.toString(data.getLong(INDEX_MASTER_KEY_ID))));
            PGPKeyRing signerRing = providerHelper.getPGPKeyRing(
                    ApgContract.KeyRingData.buildPublicKeyRingUri(Long.toString(sig.getKeyID())));

            try {
                sig.init(new JcaPGPContentVerifierBuilderProvider()
                        .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME), signerRing.getPublicKey());
                if (sig.verifyCertification(signeeUid, signeeRing.getPublicKey())) {
                    mStatus.setText(R.string.cert_verify_ok);
                    mStatus.setTextColor(getResources().getColor(R.color.bbutton_success));
                } else {
                    mStatus.setText(R.string.cert_verify_failed);
                    mStatus.setTextColor(getResources().getColor(R.color.alert));
                }
            } catch (SignatureException e) {
                mStatus.setText(R.string.cert_verify_error);
                mStatus.setTextColor(getResources().getColor(R.color.alert));
            } catch (PGPException e) {
                mStatus.setText(R.string.cert_verify_error);
                mStatus.setTextColor(getResources().getColor(R.color.alert));
            }
        } catch (ProviderHelper.NotFoundException e) {
            mStatus.setText(R.string.cert_verify_unavailable);
            mStatus.setTextColor(getResources().getColor(R.color.black));
        }

        String algorithmStr = PgpKeyHelper.getAlgorithmInfo(this, sig.getKeyAlgorithm(), 0);
        mAlgorithm.setText(algorithmStr);

        mRowReason.setVisibility(View.GONE);
        switch (data.getInt(INDEX_TYPE)) {
        case PGPSignature.DEFAULT_CERTIFICATION:
            mType.setText(R.string.cert_default);
            break;
        case PGPSignature.NO_CERTIFICATION:
            mType.setText(R.string.cert_none);
            break;
        case PGPSignature.CASUAL_CERTIFICATION:
            mType.setText(R.string.cert_casual);
            break;
        case PGPSignature.POSITIVE_CERTIFICATION:
            mType.setText(R.string.cert_positive);
            break;
        case PGPSignature.CERTIFICATION_REVOCATION: {
            mType.setText(R.string.cert_revoke);
            if (sig.getHashedSubPackets().hasSubpacket(SignatureSubpacketTags.REVOCATION_REASON)) {
                SignatureSubpacket p = sig.getHashedSubPackets()
                        .getSubpacket(SignatureSubpacketTags.REVOCATION_REASON);
                // For some reason, this is missing in SignatureSubpacketInputStream:146
                if (!(p instanceof RevocationReason)) {
                    p = new RevocationReason(false, p.getData());
                }
                String reason = ((RevocationReason) p).getRevocationDescription();
                mReason.setText(reason);
                mRowReason.setVisibility(View.VISIBLE);
            }
            break;
        }
        }
    }

    // can't do this before the data is initialized
    mViewCertifierButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent viewIntent = new Intent(ViewCertActivity.this, ViewKeyActivity.class);

            try {
                ProviderHelper providerHelper = new ProviderHelper(ViewCertActivity.this);
                long signerMasterKeyId = providerHelper.getMasterKeyId(
                        KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(mCertifierKeyId)));
                viewIntent.setData(KeyRings.buildGenericKeyRingUri(Long.toString(signerMasterKeyId)));
                startActivity(viewIntent);
            } catch (ProviderHelper.NotFoundException e) {
                // TODO notify user of this, maybe offer download?
                Log.e(Constants.TAG, "key not found!", e);
            }
        }
    });
}

From source file:com.rjfun.cordova.sms.SMSPlugin.java

private JSONObject getJsonFromCursor(Cursor cur) {
    JSONObject json = new JSONObject();

    int nCol = cur.getColumnCount();
    String keys[] = cur.getColumnNames();

    try {//from   w w w  . j a v  a  2  s  . c  o m
        for (int j = 0; j < nCol; j++) {
            switch (cur.getType(j)) {
            case Cursor.FIELD_TYPE_NULL:
                json.put(keys[j], null);
                break;
            case Cursor.FIELD_TYPE_INTEGER:
                json.put(keys[j], cur.getLong(j));
                break;
            case Cursor.FIELD_TYPE_FLOAT:
                json.put(keys[j], cur.getFloat(j));
                break;
            case Cursor.FIELD_TYPE_STRING:
                json.put(keys[j], cur.getString(j));
                break;
            case Cursor.FIELD_TYPE_BLOB:
                json.put(keys[j], cur.getBlob(j));
                break;
            }
        }
    } catch (Exception e) {
        return null;
    }

    return json;
}

From source file:com.nextgis.mobile.fragment.AttributesFragment.java

private String parseAttributes(String data) throws RuntimeException {
    String selection = Constants.FIELD_ID + " = ?";
    Cursor attributes = mLayer.query(null, selection, new String[] { mItemId + "" }, null, null);
    if (null == attributes || attributes.getCount() == 0)
        return data;

    if (attributes.moveToFirst()) {
        for (int i = 0; i < attributes.getColumnCount(); i++) {
            String column = attributes.getColumnName(i);
            String text, alias;/*from  w  w  w  . j  ava2 s  .co m*/

            if (column.startsWith(Constants.FIELD_GEOM_))
                continue;

            if (column.equals(Constants.FIELD_GEOM)) {
                switch (mLayer.getGeometryType()) {
                case GTPoint:
                    try {
                        GeoPoint pt = (GeoPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.coordinates), formatCoordinates(pt));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiPoint:
                    try {
                        GeoMultiPoint mpt = (GeoMultiPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.center),
                                formatCoordinates(mpt.getEnvelope().getCenter()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTLineString:
                    try {
                        GeoLineString line = (GeoLineString) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.length),
                                LocationUtil.formatLength(getContext(), line.getLength(), 3));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiLineString:
                    try {
                        GeoMultiLineString multiline = (GeoMultiLineString) GeoGeometryFactory
                                .fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.length),
                                LocationUtil.formatLength(getContext(), multiline.getLength(), 3));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTPolygon:
                    try {
                        GeoPolygon polygon = (GeoPolygon) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.perimeter),
                                LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3));
                        data += getRow(getString(R.string.area),
                                LocationUtil.formatArea(getContext(), polygon.getArea()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiPolygon:
                    try {
                        GeoMultiPolygon polygon = (GeoMultiPolygon) GeoGeometryFactory
                                .fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.perimeter),
                                LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3));
                        data += getRow(getString(R.string.area),
                                LocationUtil.formatArea(getContext(), polygon.getArea()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                default:
                    continue;
                }
            }

            Field field = mLayer.getFieldByName(column);
            int fieldType = field != null ? field.getType() : Constants.NOT_FOUND;
            switch (fieldType) {
            case GeoConstants.FTInteger:
                text = attributes.getInt(i) + "";
                break;
            case GeoConstants.FTReal:
                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(4);
                nf.setGroupingUsed(false);
                text = nf.format(attributes.getDouble(i));
                break;
            case GeoConstants.FTDate:
            case GeoConstants.FTTime:
            case GeoConstants.FTDateTime:
                text = formatDateTime(attributes.getLong(i), fieldType);
                break;
            default:
                text = toString(attributes.getString(i));
                Pattern pattern = Pattern.compile(URL_PATTERN);
                Matcher match = pattern.matcher(text);
                while (match.matches()) {
                    String url = text.substring(match.start(), match.end());
                    text = text.replaceFirst(URL_PATTERN, "<a href = '" + url + "'>" + url + "</a>");
                    match = pattern.matcher(text.substring(match.start() + url.length() * 2 + 17));
                }
                break;
            }

            if (field != null)
                alias = field.getAlias();
            else if (column.equals(Constants.FIELD_ID))
                alias = Constants.FIELD_ID;
            else
                alias = "";

            data += getRow(alias, text);
        }
    }

    attributes.close();
    return data;
}

From source file:org.mitre.svmp.common.DatabaseHandler.java

private AppInfo makeAppInfo(Cursor cursor) {
    try {//from  w w  w.ja  v a2 s. c  o  m
        // get values from query
        int connectionID = cursor.getInt(0);
        String packageName = cursor.getString(1);
        String appName = cursor.getString(2);
        int favoriteInt = cursor.getInt(3); // sqlite can't store booleans, only numbers
        boolean favorite = favoriteInt == 1;

        // if the AppInfo has an icon, get it
        byte[] icon = null;
        if (!cursor.isNull(4))
            icon = cursor.getBlob(4);
        byte[] iconHash = null;
        if (!cursor.isNull(5))
            iconHash = cursor.getBlob(5);

        int isInstalled = cursor.getInt(6);

        return new AppInfo(connectionID, packageName, appName, favorite, icon, iconHash, isInstalled);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

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

private void cursorColumnToContentValues(Cursor cursor, ContentValues values, int index) {
    switch (cursor.getType(index)) {
    case Cursor.FIELD_TYPE_NULL:
        // don't put anything in the content values
        break;//from  w w w  .j a va2 s .co  m
    case Cursor.FIELD_TYPE_INTEGER:
        values.put(ContactQuery.COLUMNS[index], cursor.getLong(index));
        break;
    case Cursor.FIELD_TYPE_STRING:
        values.put(ContactQuery.COLUMNS[index], cursor.getString(index));
        break;
    case Cursor.FIELD_TYPE_BLOB:
        values.put(ContactQuery.COLUMNS[index], cursor.getBlob(index));
        break;
    default:
        throw new IllegalStateException("Invalid or unhandled data type");
    }
}