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:edu.stanford.mobisocial.dungbeetle.model.DbObject.java

/**
 * Use SocialKit Obj implementations.//from w w w  .  ja  va 2  s .c o m
 */
@Deprecated
private DbObject(Cursor c) {
    mType = c.getString(c.getColumnIndexOrThrow(DbObject.TYPE));
    String jsonStr = c.getString(c.getColumnIndexOrThrow(DbObject.JSON));
    try {
        mRaw = c.getBlob(c.getColumnIndexOrThrow(DbObject.RAW));
    } catch (IllegalArgumentException e) {
        mRaw = null;
    }
    try {
        mJson = new JSONObject(jsonStr);
    } catch (JSONException e) {
        Log.wtf("DB", "Bad json from database.");
    }
    //mTimestamp = c.getLong(c.getColumnIndexOrThrow(DbObject.TIMESTAMP));
}

From source file:com.germainz.identiconizer.services.IdenticonRemovalService.java

private void processPhotos() {
    Cursor cursor = getIdenticonPhotos();
    final int totalPhotos = cursor.getCount();
    int currentPhoto = 1;
    while (cursor.moveToNext()) {
        final long contactId = cursor.getLong(0);
        updateNotification(getString(R.string.identicons_remove_service_running_title), String.format(
                getString(R.string.identicons_remove_service_contact_summary), currentPhoto++, totalPhotos));
        byte[] data = cursor.getBlob(1);
        if (IdenticonUtils.isIdenticon(data))
            removeIdenticon(contactId);/*from ww  w . j av  a2 s. c  om*/
    }
    cursor.close();

    if (!mOps.isEmpty()) {
        updateNotification(getString(R.string.identicons_remove_service_running_title),
                getString(R.string.identicons_remove_service_contact_summary_finishing));
        try {
            // Perform operations in batches of 100, to avoid TransactionTooLargeExceptions
            for (int i = 0, j = mOps.size(); i < j; i += 100)
                getContentResolver().applyBatch(ContactsContract.AUTHORITY,
                        new ArrayList<ContentProviderOperation>(mOps.subList(i, i + Math.min(100, j - i))));
        } catch (RemoteException | OperationApplicationException e) {
            Log.e(TAG, "Unable to apply batch", e);
        }
    }
}

From source file:org.sufficientlysecure.keychain.ui.adapter.PhotoAttributesAdapter.java

/**
 * Warning: this method uses the unextended position of the cursor!
 * @param cursor A cursor, already moved to the correct position.
 * @return The array of photo attributes produced from the attribute data
 * at that cursor position./*from ww  w  .ja  va2  s  .  c  o m*/
 */
public PhotoAttribute[] getItemArrayAtUnextendedPosition(Cursor cursor) {
    int rank = cursor.getInt(INDEX_RANK);

    PhotoAttribute[] attributes = mPhotoAttributeCache.get(rank);
    if (attributes != null) {
        Log.d(Constants.TAG, "The requested photo attribute array is cached!");
        return attributes;
    }
    Log.d(Constants.TAG, "The requested photo attribute array is not cached!");

    try {
        byte[] data = cursor.getBlob(INDEX_ATTRIBUTE_DATA);
        int status = getStatus(cursor);
        attributes = PhotoAttribute.fromAttributeData(data, status, mContext);
        if (!mShowRevokedItems) {
            attributes = filterArray(attributes);
        }
        mPhotoAttributeCache.put(rank, attributes);
        return attributes;
    } catch (IOException e) {
        Log.e(Constants.TAG, "Could not read photo attribute subpacket data", e);
        return null;
    }
}

From source file:com.ferid.app.frequentcontacts.selectnumber.SelectNumberActivity.java

/**
 * Retrieve photo of the given contact with contact ID
 * @param contactId//ww  w.  ja  va  2s.  c o  m
 * @return
 */
private String retrievePhoto(int contactId) {
    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
    Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

    Cursor cursor = getContentResolver().query(photoUri, new String[] { ContactsContract.Contacts.Photo.PHOTO },
            null, null, null);

    if (cursor == null) {
        return "";
    }

    try {
        if (cursor.moveToFirst()) {
            byte[] data = cursor.getBlob(0);
            if (data != null) {
                //byte[] to String convertion
                return Base64.encodeToString(data, Base64.DEFAULT);
            }
        }
    } finally {
        cursor.close();
    }

    return "";
}

From source file:com.luorrak.ouroboros.thread.ThreadFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_refresh: {
        getThread(resto, boardName);/*from   w w  w  .j a  va  2  s .c  o m*/
        break;
    }
    case R.id.action_scroll_bottom: {
        recyclerView.scrollToPosition(threadAdapter.getItemCount() - 1);
        break;
    }
    case R.id.action_scroll_top: {
        recyclerView.scrollToPosition(0);
        break;
    }
    case R.id.action_reply: {
        Intent intent = new Intent(getActivity(), ReplyCommentActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Util.INTENT_THREAD_NO, resto);
        intent.putExtra(Util.INTENT_BOARD_NAME, boardName);
        getActivity().startActivity(intent);
        break;
    }
    case R.id.action_gallery: {
        GalleryFragment galleryFragment = new GalleryFragment().newInstance(boardName, resto);
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.placeholder_card, galleryFragment).addToBackStack("galleryfragment")
                .commit();
        break;
    }
    case R.id.action_save_all_images: {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat
                    .requestPermissions(getActivity(),
                            new String[] { Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            Util.REQUEST_STORAGE_PERMISSION);
        } else {
            showDownloadAllDialog();
        }
        break;
    }
    case R.id.action_external_browser: {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                Uri.parse(ChanUrls.getThreadUrlExternal(boardName, resto)));
        startActivity(browserIntent);
        break;
    }
    case R.id.menu_item_share: {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        String shareBody = ChanUrls.getThreadUrlExternal(boardName, resto);
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(shareIntent, "Share via"));
        break;
    }
    case R.id.action_add_watchlist: {
        Cursor cursor = infiniteDbHelper.getWatchlistCursor();
        int count = cursor.getCount();
        byte[] serializedMediaList;
        cursor.close();

        Cursor threadcursor = infiniteDbHelper.getThreadCursor(resto);
        serializedMediaList = (threadcursor.getCount() > 0) ? threadcursor
                .getBlob(threadcursor.getColumnIndex(DbContract.ThreadEntry.COLUMN_THREAD_MEDIA_FILES)) : null;

        infiniteDbHelper.insertWatchlistEntry(String.valueOf(getActivity().getTitle()), boardName, resto,
                serializedMediaList, count);
        ((ThreadActivity) getActivity()).updateWatchlist();
        Snackbar.make(getView(), "Thread Added To Watchlist", Snackbar.LENGTH_LONG).show();
        threadcursor.close();

        break;
    }
    case R.id.action_layout_vertical: {
        SettingsHelper.setThreadView(getActivity(), Util.THREAD_LAYOUT_VERTICAL);
        ThreadFragment threadFragment = new ThreadFragment().newInstance(resto, boardName);
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.placeholder_card, threadFragment).commit();
        break;
    }
    case R.id.action_layout_horizontal: {
        SettingsHelper.setThreadView(getActivity(), Util.THREAD_LAYOUT_HORIZONTAL);
        ThreadFragment threadFragment = new ThreadFragment().newInstance(resto, boardName);
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.placeholder_card, threadFragment).commit();
        break;
    }
    }
    return true;
}

From source file:com.nextgis.maplib.map.VectorLayer.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    super.fromJSON(jsonObject);
    mGeometryType = jsonObject.getInt(JSON_GEOMETRY_TYPE_KEY);
    mIsInitialized = jsonObject.getBoolean(JSON_IS_INITIALIZED_KEY);
    if (jsonObject.has(JSON_RENDERERPROPS_KEY)) {
        setDefaultRenderer();//from w ww.j av  a2  s.  co m

        if (null != mRenderer && mRenderer instanceof IJSONStore) {
            IJSONStore jsonStore = (IJSONStore) mRenderer;
            jsonStore.fromJSON(jsonObject.getJSONObject(JSON_RENDERERPROPS_KEY));
        }
    }

    if (mIsInitialized) {
        mExtents = new GeoEnvelope();

        //load vector cache
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(false);
        String[] columns = new String[] { "_ID", "GEOM" };
        Cursor cursor = db.query(mPath.getName(), columns, null, null, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            mVectorCacheItems = new ArrayList<>();
            do {
                try {
                    GeoGeometry geoGeometry = GeoGeometry.fromBlob(cursor.getBlob(1));
                    int nId = cursor.getInt(0);
                    mExtents.merge(geoGeometry.getEnvelope());
                    mVectorCacheItems.add(new VectorCacheItem(geoGeometry, nId));
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } while (cursor.moveToNext());
        }
    }
}

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

private void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri) {
    final AsyncTask<Void, Void, Void> photoLoadTask = new AsyncTask<Void, Void, Void>() {

        @Override/*  w  ww  . j a  v  a2 s. c  o  m*/
        protected Void doInBackground(Void... params) {
            final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null,
                    null, null);
            if (photoCursor != null) {
                try {
                    if (photoCursor.moveToFirst()) {
                        final byte[] photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO);
                        entry.setPhotoBytes(photoBytes);

                        mHandler.post(new Runnable() {

                            @Override
                            public void run() {
                                mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
                                notifyDataSetChanged();
                            }
                        });
                    }
                } finally {
                    photoCursor.close();
                }
            }
            return null;
        }
    };
    executePhotoLoadTask(photoLoadTask);
}

From source file:com.quuzz.tbg.recyclerview.CustomAdapter.java

private TbModel[] initDataset() {
    // init DB/*ww w . ja v a 2s  .  c o  m*/
    // Gets the data repository in write mode
    //        String[] mDataset = new String[DATASET_COUNT];
    TbDbHelper tbDbHelper = new TbDbHelper(context);
    SQLiteDatabase db = tbDbHelper.getReadableDatabase();
    Cursor cursor = db.query("tbdata", null, null, null, null, null, null);
    int count = cursor.getCount();
    cursor.moveToFirst();
    TbModel[] mDataset = new TbModel[count];
    for (int i = 0; i < count; i++) {
        mDataset[i] = new TbModel();
        mDataset[i].setName(cursor.getString(cursor.getColumnIndex("name")));
        mDataset[i].setTbId(cursor.getString(cursor.getColumnIndex("tb_id")));
        mDataset[i].setImageData(cursor.getBlob(cursor.getColumnIndex("image_data")));
        mDataset[i].setDescription(cursor.getString(cursor.getColumnIndex("description")));
        cursor.moveToNext();
    }
    cursor.close();
    db.close();
    return mDataset;
}

From source file:mobisocial.bento.anyshare.util.DBHelper.java

public byte[] getThumbForHash(long hash) {

    byte[] thumb = null;

    String[] projection = { ItemObject.RAW };
    String selection = ItemObject.OBJHASH + " = ?";
    String[] selectionArgs = { String.valueOf(hash) };
    String tables = ItemObject.TABLE;
    String sortOrder = null;//from  w  w w  . ja  v a  2 s  .  co m
    String limits = "0,1";

    Cursor c = getReadableDatabase().query(tables, projection, selection, selectionArgs, null, null, sortOrder,
            limits);
    if (c != null && c.moveToFirst()) {
        thumb = c.getBlob(0);
    }
    c.close();
    return thumb;
}

From source file:br.com.anteros.android.persistence.backup.DatabaseMaintenanceFragment.java

private Object getObjectValue(Cursor cursor, int columnIndex) throws SQLException {
    switch (SQLiteResultSet.getDataType((SQLiteCursor) cursor, columnIndex)) {
    case SQLiteResultSet.FIELD_TYPE_INTEGER:
        long val = cursor.getLong(columnIndex);
        if (val > Integer.MAX_VALUE || val < Integer.MIN_VALUE) {
            return new Long(val);
        } else {/* www.  ja va 2s .com*/
            return new Integer((int) val);
        }
    case SQLiteResultSet.FIELD_TYPE_FLOAT:
        return new Double(cursor.getDouble(columnIndex));
    case SQLiteResultSet.FIELD_TYPE_BLOB:
        return cursor.getBlob(columnIndex);
    case SQLiteResultSet.FIELD_TYPE_NULL:
        return null;
    case SQLiteResultSet.FIELD_TYPE_STRING:
    default:
        return cursor.getString(columnIndex);
    }
}