Java Code Examples for android.database.Cursor.getBlob()

The following are Jave code examples for showing how to use getBlob() of the android.database.Cursor class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: SimpleUILauncher   File: Utilities.java   Source Code and License Vote up 6 votes
public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
    byte[] data = c.getBlob(iconIndex);
    try {
        return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
    } catch (Exception e) {
        return null;
    }
}
 
Example 2
Project: GitHub   File: TestEntityDao.java   Source Code and License Vote up 6 votes
@Override
public TestEntity readEntity(Cursor cursor, int offset) {
    TestEntity entity = new TestEntity( //
        cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
        cursor.getInt(offset + 1), // simpleInt
        cursor.isNull(offset + 2) ? null : cursor.getInt(offset + 2), // simpleInteger
        cursor.getString(offset + 3), // simpleStringNotNull
        cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // simpleString
        cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // indexedString
        cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // indexedStringAscUnique
        cursor.isNull(offset + 7) ? null : new java.util.Date(cursor.getLong(offset + 7)), // simpleDate
        cursor.isNull(offset + 8) ? null : cursor.getShort(offset + 8) != 0, // simpleBoolean
        cursor.isNull(offset + 9) ? null : cursor.getBlob(offset + 9) // simpleByteArray
    );
    return entity;
}
 
Example 3
Project: SQLite-Performance   File: RawQueryTestCase.java   Source Code and License Vote up 6 votes
@Override
public Metrics runCase() {
    mDbHelper = new DbHelper(App.getInstance(), getClass().getSimpleName(), mFileSize, mFiles);
    Metrics result = new Metrics(getClass().getSimpleName()+" ("+mFileSize+" blob size, "+mFiles+" blobs)", mTestSizeIndex);
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String[] fileNames = Arrays.copyOf(mDbHelper.getFileNames(), mDbHelper.getFileNames().length);
    List<String> fileList = Arrays.asList(fileNames);
    Collections.shuffle(fileList, new Random());
    fileNames = fileList.toArray(fileNames);

    result.started();
    String[] selectionArgs = new String[1];
    for (int i = 0; i < mFiles; i++) {
        selectionArgs[0] = fileNames[i];
        Cursor c = db.rawQuery("SELECT data FROM files WHERE filename = ?", selectionArgs);
        try {
            c.moveToNext();
            byte[] data = c.getBlob(0);
        } finally {
            c.close();
        }
    }
    result.finished();
    return result;
}
 
Example 4
Project: OftenPorter   File: TypeUtil.java   Source Code and License Vote up 6 votes
static Object getObject(Cursor cursor, int columnIndex) throws Exception
{
    int type = getType(cursor, columnIndex);
    Object value;
    switch (type)
    {
        case Cursor.FIELD_TYPE_BLOB:
            value = cursor.getBlob(columnIndex);
            break;
        case Cursor.FIELD_TYPE_FLOAT:
            value = cursor.getFloat(columnIndex);
            break;
        case Cursor.FIELD_TYPE_INTEGER:
            value = cursor.getLong(columnIndex);
            break;
        case Cursor.FIELD_TYPE_NULL:
            value = null;
            break;
        case Cursor.FIELD_TYPE_STRING:
            value = cursor.getString(columnIndex);
            break;
        default:
            value = cursor.getString(columnIndex);
    }
    return value;
}
 
Example 5
Project: fruit   File: FrameworkActivity.java   Source Code and License Vote up 6 votes
public void Query(){
    SQLiteDatabase db = myDatebaseHelper.getWritableDatabase();
    Cursor cursor = db.query("Photo", null, null, null, null, null, null);
    while (cursor.moveToNext()) {
        byte[] in = cursor.getBlob(cursor.getColumnIndex("fruitimage"));
        long did=cursor.getLong(cursor.getColumnIndex("_id"));
        String name = cursor.getString(cursor.getColumnIndex("fruitname"));
        String info = cursor.getString(cursor.getColumnIndex("fruitinfo"));
        Bitmap bmpout = BitmapFactory.decodeByteArray(in, 0, in.length);
        Drawable pic=chage_to_drawable(bmpout);
        Fruit Nfruit = new Fruit(name,in,did,info);
        fruitList.add(Nfruit);
    }
    cursor.close();
    db.close();
}
 
Example 6
Project: q-mail   File: LocalStore.java   Source Code and License Vote up 5 votes
private InputStream getRawAttachmentInputStream(String partId, int location, Cursor cursor)
        throws FileNotFoundException {
    switch (location) {
        case DataLocation.IN_DATABASE: {
            byte[] data = cursor.getBlob(ATTACH_DATA_INDEX);
            return new ByteArrayInputStream(data);
        }
        case DataLocation.ON_DISK: {
            File file = getAttachmentFile(partId);
            return new FileInputStream(file);
        }
        default:
            throw new IllegalStateException("unhandled case");
    }
}
 
Example 7
Project: simple-share-android   File: RecentsCreateFragment.java   Source Code and License Vote up 5 votes
@Override
public List<DocumentStack> loadInBackground(Uri uri, CancellationSignal signal) {
    final Collection<RootInfo> matchingRoots = mRoots.getMatchingRootsBlocking(mState);
    final ArrayList<DocumentStack> result = new ArrayList<>();

    final ContentResolver resolver = getContext().getContentResolver();
    final Cursor cursor = resolver.query(
            uri, null, null, null, RecentColumns.TIMESTAMP + " DESC");
    try {
        while (cursor != null && cursor.moveToNext()) {
            final byte[] rawStack = cursor.getBlob(
                    cursor.getColumnIndex(RecentColumns.STACK));
            try {
                final DocumentStack stack = new DocumentStack();
                DurableUtils.readFromArray(rawStack, stack);

                // Only update root here to avoid spinning up all
                // providers; we update the stack during the actual
                // restore. This also filters away roots that don't
                // match current filter.
                stack.updateRoot(matchingRoots);
                result.add(stack);
            } catch (IOException e) {
                Log.w(TAG, "Failed to resolve stack: " + e);
                CrashReportingManager.logException(e);
            }
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }

    return result;
}
 
Example 8
Project: FlickLauncher   File: Utilities.java   Source Code and License Vote up 5 votes
public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
    byte[] data = c.getBlob(iconIndex);
    try {
        return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
    } catch (Exception e) {
        return null;
    }
}
 
Example 9
Project: FireFiles   File: RecentsCreateFragment.java   Source Code and License Vote up 5 votes
@Override
public List<DocumentStack> loadInBackground(Uri uri, CancellationSignal signal) {
    final Collection<RootInfo> matchingRoots = mRoots.getMatchingRootsBlocking(mState);
    final ArrayList<DocumentStack> result = new ArrayList<>();

    final ContentResolver resolver = getContext().getContentResolver();
    final Cursor cursor = resolver.query(
            uri, null, null, null, RecentColumns.TIMESTAMP + " DESC");
    try {
        while (cursor != null && cursor.moveToNext()) {
            final byte[] rawStack = cursor.getBlob(
                    cursor.getColumnIndex(RecentColumns.STACK));
            try {
                final DocumentStack stack = new DocumentStack();
                DurableUtils.readFromArray(rawStack, stack);

                // Only update root here to avoid spinning up all
                // providers; we update the stack during the actual
                // restore. This also filters away roots that don't
                // match current filter.
                stack.updateRoot(matchingRoots);
                result.add(stack);
            } catch (IOException e) {
                Log.w(TAG, "Failed to resolve stack: " + e);
                CrashReportingManager.logException(e);
            }
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }

    return result;
}
 
Example 10
Project: XPrivacy   File: XContentResolver.java   Source Code and License Vote up 5 votes
private void copyColumns(Cursor cursor, MatrixCursor result, int count) {
	try {
		Object[] columns = new Object[count];
		for (int i = 0; i < count; i++)
			switch (cursor.getType(i)) {
			case Cursor.FIELD_TYPE_NULL:
				columns[i] = null;
				break;
			case Cursor.FIELD_TYPE_INTEGER:
				columns[i] = cursor.getInt(i);
				break;
			case Cursor.FIELD_TYPE_FLOAT:
				columns[i] = cursor.getFloat(i);
				break;
			case Cursor.FIELD_TYPE_STRING:
				columns[i] = cursor.getString(i);
				break;
			case Cursor.FIELD_TYPE_BLOB:
				columns[i] = cursor.getBlob(i);
				break;
			default:
				Util.log(this, Log.WARN, "Unknown cursor data type=" + cursor.getType(i));
			}
		result.addRow(columns);
	} catch (Throwable ex) {
		Util.bug(this, ex);
	}
}
 
Example 11
Project: CP-Tester   File: ContentProviderHelper.java   Source Code and License Vote up 5 votes
public static String getSQLResult(Context context, ProviderInfo provider, String query) {
    Bundle bundle = new Bundle();
    bundle.putString("provider_name", provider.packageName);
    bundle.putString("query", query);
    FirebaseAnalytics.getInstance(context).logEvent("sql_injection", bundle);
    StringBuilder s = new StringBuilder();
    try {
        Uri uri = Uri.parse("content://" + provider.authority);
        Cursor c = context.getContentResolver().query(uri, new String[]{ query }, null, null, null);
        int col_c = c != null ? c.getColumnCount() : 0;
        String[] Columns = new String[col_c];
        for (int i = 0; i < col_c; i++) {
            s.append(c.getColumnName(i));
            s.append(":");
            Columns[i] = c.getColumnName(i);
        }
        s.append("\n");
        if (c != null && c.moveToFirst()) {
            do {
                for (int i = 0; i < col_c; i++) {
                    if (Columns[i].toLowerCase().contains("image")) {
                        byte[] blob = c.getBlob(i);
                        s.append(bytesToHexString(blob));
                    } else {
                        s.append(c.getString(i));
                    }
                    s.append(";");
                }
                s.append("\n");
            } while (c.moveToNext());
        }
        if (c != null) {
            c.close();
        }
    } catch (Throwable e) {
        s.append(e.getMessage());
    }
    return s.toString();
}
 
Example 12
Project: SimpleUILauncher   File: IconCache.java   Source Code and License Vote up 5 votes
private static Bitmap loadIconNoResize(Cursor c, int iconIndex, BitmapFactory.Options options) {
    byte[] data = c.getBlob(iconIndex);
    try {
        return BitmapFactory.decodeByteArray(data, 0, data.length, options);
    } catch (Exception e) {
        return null;
    }
}
 
Example 13
Project: UnversityFinance   File: ApplyTableActivity.java   Source Code and License Vote up 5 votes
private void initData() {
    mCurrentProjectId = getIntent().getStringExtra("projectId");
    mCurrentProjectName = getIntent().getStringExtra("projectName");
    if (mCurrentProjectId.startsWith("jxj0")
            || mCurrentProjectId.startsWith("jxj1")
            || mCurrentProjectId.startsWith("jxj2")
            || mCurrentProjectId.startsWith("jxj3")) {
        mTitles = getResources().getStringArray(R.array.apply_table_scholarship);
    } else if (mCurrentProjectId.startsWith("jxj4")) {
        mTitles = getResources().getStringArray(R.array.apply_table_job);
    } else if (mCurrentProjectId.startsWith("jxj5")) {
        mTitles = getResources().getStringArray(R.array.apply_table_loan);
    } else if (mCurrentProjectId.startsWith("jxj6")) {
        mTitles = getResources().getStringArray(R.array.apply_table_assistance);
    } else if (mCurrentProjectId.startsWith("jxj7")) {
        mTitles = getResources().getStringArray(R.array.apply_table_assistance);
    } else {
        mTitles = getResources().getStringArray(R.array.apply_table_scholarship);
    }

    mContents = new String[mTitles.length];
    mCurrentUserId = Utils.getStringFromSharedPreferences(this, "account");
    Cursor cursor = mDB.rawQuery("select s_name,s_college,s_class,s_photo_bytes from " + ConfigUtils.TABLE_STUDENT +
            " where s_id=?", new String[]{mCurrentUserId});
    if (cursor.moveToFirst()) {
        mCurrentUserName = cursor.getString(cursor.getColumnIndex("s_name"));
        mCurrentUserCollege = cursor.getString(cursor.getColumnIndex("s_college"));
        mCurrentUserClass = cursor.getString(cursor.getColumnIndex("s_class"));
        byte[] data = cursor.getBlob(cursor.getColumnIndex("s_photo_bytes"));
        mPhotoBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
    }
    cursor.close();
}
 
Example 14
Project: UnversityFinance   File: MineFragment.java   Source Code and License Vote up 5 votes
private void initView(View parent) {
    mMyApplyTV = (TextView) parent.findViewById(R.id.my_apply_tv);
    mMyApplyTV.setOnClickListener(this);
    mMessageTV = (TextView) parent.findViewById(R.id.message_tv);
    mMessageTV.setOnClickListener(this);
    mHelpTV = (TextView) parent.findViewById(R.id.help_tv);
    mHelpTV.setOnClickListener(this);
    mSettingTV = (TextView) parent.findViewById(R.id.setting_tv);
    mSettingTV.setOnClickListener(this);
    mStudentInfo = (LinearLayout) parent.findViewById(R.id.student_info);
    mStudentInfo.setOnClickListener(this);
    mUserNameTV = (TextView) parent.findViewById(R.id.user_name);
    mUserIdTV = (TextView) parent.findViewById(R.id.user_id);
    mUserPhotoIv = (ImageView) parent.findViewById(R.id.user_photo);

    String userId = Utils.getStringFromSharedPreferences(mContext, "account");
    Cursor cursor = mDB.rawQuery("select s_name,s_photo,s_photo_bytes from student_info where s_id=?",
            new String[]{userId});
    if (cursor.moveToFirst()) {
        mUserIdTV.setText(userId);
        mUserNameTV.setText(cursor.getString(cursor.getColumnIndex("s_name")));
        byte[] bytes;
        if ((bytes = cursor.getBlob(cursor.getColumnIndex("s_photo_bytes"))) != null) {
            Log.d("wangjuncheng", "initView: set photo by DB");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            mUserPhotoIv.setImageBitmap(bitmap);
        } else {
            Glide.with(mContext).load(cursor.getString(cursor.getColumnIndex("s_photo"))).into(mUserPhotoIv);
        }
    }

    cursor.close();
}
 
Example 15
Project: LucaHome-AndroidApplication   File: Tools.java   Source Code and License Vote up 5 votes
/**
 * Solution from
 * https://stackoverflow.com/questions/3509178/getting-a-photo-from-a-contact
 *
 * @param context the context of an activity or service
 * @param name    is the name of the contact you are looking for
 * @param height  height of the bitmap to return
 * @param width   width of the bitmap to return
 * @param round   boolean which defines if the returned bitmap shall be round
 * @return returns a bitmap of a contact if found or a dummy bitmap
 */
public static Bitmap RetrieveContactPhoto(@NonNull Context context, @NonNull String name, int height, int width, boolean round) {
    String contactId = null;
    Bitmap photo = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_face_white_48dp);

    ContentResolver contentResolver = context.getContentResolver();
    String[] projection = new String[]{ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts._ID};

    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(name));

    Cursor cursor = contentResolver.query(uri, projection, null, null, null);
    if (cursor != null) {
        while (cursor.moveToNext() && contactId == null) {
            contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
        }
        cursor.close();
    }

    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(contactId));
    Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

    Cursor photoCursor = contentResolver.query(photoUri, new String[]{ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
    if (photoCursor != null) {
        try {
            if (photoCursor.moveToFirst()) {
                byte[] data = photoCursor.getBlob(0);
                if (data != null) {
                    photo = BitmapFactory.decodeStream(new ByteArrayInputStream(data));
                }
            }
        } finally {
            photoCursor.close();
        }
    }

    if (round) {
        return GetCircleBitmap(photo.copy(Bitmap.Config.ARGB_8888, true));
    }

    return photo;
}
 
Example 16
Project: q-mail   File: MigrationTo55.java   Source Code and License Vote up 4 votes
public void populateFromGetMessageCursor(Cursor cursor) throws MessagingException {
    final String subject = cursor.getString(MSG_INDEX_SUBJECT);
    this.setSubject(subject == null ? "" : subject);

    Address[] from = Address.unpack(cursor.getString(MSG_INDEX_SENDER_LIST));
    if (from.length > 0) {
        this.setFrom(from[0]);
    }
    this.setInternalSentDate(new Date(cursor.getLong(MSG_INDEX_DATE)));
    this.setUid(cursor.getString(MSG_INDEX_UID));
    String flagList = cursor.getString(MSG_INDEX_FLAGS);
    if (flagList != null && flagList.length() > 0) {
        String[] flags = flagList.split(",");

        for (String flag : flags) {
            try {
                this.setFlag(Flag.valueOf(flag), true);
            }

            catch (Exception e) {
                if (!"X_BAD_FLAG".equals(flag)) {
                    Timber.w("Unable to parse flag %s", flag);
                }
            }
        }
    }
    this.databaseId = cursor.getLong(MSG_INDEX_ID);
    this.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(MSG_INDEX_TO)));
    this.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(MSG_INDEX_CC)));
    this.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(MSG_INDEX_BCC)));
    this.setReplyTo(Address.unpack(cursor.getString(MSG_INDEX_REPLY_TO)));

    this.attachmentCount = cursor.getInt(MSG_INDEX_ATTACHMENT_COUNT);
    this.setInternalDate(new Date(cursor.getLong(MSG_INDEX_INTERNAL_DATE)));
    this.setMessageId(cursor.getString(MSG_INDEX_MESSAGE_ID_HEADER));

    String previewTypeString = cursor.getString(MSG_INDEX_PREVIEW_TYPE);
    DatabasePreviewType databasePreviewType = DatabasePreviewType.fromDatabaseValue(previewTypeString);
    previewType = databasePreviewType.getPreviewType();
    if (previewType == PreviewType.TEXT) {
        preview = cursor.getString(MSG_INDEX_PREVIEW);
    } else {
        preview = "";
    }

    threadId = (cursor.isNull(MSG_INDEX_THREAD_ID)) ? -1 : cursor.getLong(MSG_INDEX_THREAD_ID);
    rootId = (cursor.isNull(MSG_INDEX_THREAD_ROOT_ID)) ? -1 : cursor.getLong(MSG_INDEX_THREAD_ROOT_ID);

    boolean deleted = (cursor.getInt(MSG_INDEX_FLAG_DELETED) == 1);
    boolean read = (cursor.getInt(MSG_INDEX_FLAG_READ) == 1);
    boolean flagged = (cursor.getInt(MSG_INDEX_FLAG_FLAGGED) == 1);
    boolean answered = (cursor.getInt(MSG_INDEX_FLAG_ANSWERED) == 1);
    boolean forwarded = (cursor.getInt(MSG_INDEX_FLAG_FORWARDED) == 1);

    setFlag(Flag.DELETED, deleted);
    setFlag(Flag.SEEN, read);
    setFlag(Flag.FLAGGED, flagged);
    setFlag(Flag.ANSWERED, answered);
    setFlag(Flag.FORWARDED, forwarded);

    setMessagePartId(cursor.getLong(MSG_INDEX_MESSAGE_PART_ID));
    mimeType = cursor.getString(MSG_INDEX_MIME_TYPE);

    byte[] header = cursor.getBlob(MSG_INDEX_HEADER_DATA);
    if (header != null) {
        MessageHeaderParser.parse(this, new ByteArrayInputStream(header));
    } else {
        Timber.d("No headers available for this message!");
    }

    headerNeedsUpdating = false;
}
 
Example 17
Project: editor-sql   File: ExportTool.java   Source Code and License Vote up 4 votes
private static void exportSingleTableData(SQLiteDatabase db, String tableName, BufferedWriter writer) throws IOException {
    String sql = "SELECT * FROM '" + tableName + "'";
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor == null) return;

    String[] columnName = cursor.getColumnNames();
    while (cursor.moveToNext()) {

        String columnStr = "";
        String valueStr = "";
        String value;
        String name;
        for (int i = 0; i < columnName.length; i++) {
            name = columnName[i];

            if (TextUtils.isEmpty(columnStr)) {
                columnStr = SQLTools.processColumnName(name);
            } else {
                columnStr = columnStr + ", " + SQLTools.processColumnName(name);
            }

            try {
                value = SQLTools.processValueMark(cursor.getString(cursor.getColumnIndex(name)));
                if (TextUtils.isEmpty(value)) {
                    value = null;
                } else {
                    value = "'" + value + "'";
                }

            } catch (Exception e) {
                e.printStackTrace();

                byte[] bytes = cursor.getBlob(cursor.getColumnIndex(name));
                if (bytes != null) {
                    value = "X'" + SQLTools.byteArrayToHexString(bytes) + "'";
                } else {
                    value = null;
                }
            }

            if (i == 0) {
                valueStr = value;
            } else {
                valueStr = valueStr + ", " + value;
            }
        }
        writer.write("INSERT INTO [" + tableName + "] (" + columnStr + ") VALUES (" + valueStr + ");" + NL);
    }
    writer.write(NL);
    cursor.close();
}
 
Example 18
Project: GitHub   File: SerializableCookie.java   Source Code and License Vote up 4 votes
public static SerializableCookie parseCursorToBean(Cursor cursor) {
    String host = cursor.getString(cursor.getColumnIndex(HOST));
    byte[] cookieBytes = cursor.getBlob(cursor.getColumnIndex(COOKIE));
    Cookie cookie = bytesToCookie(cookieBytes);
    return new SerializableCookie(host, cookie);
}
 
Example 19
Project: SuperHttp   File: SerializableCookie.java   Source Code and License Vote up 4 votes
public static SerializableCookie parseCursorToBean(Cursor cursor) {
    String host = cursor.getString(cursor.getColumnIndex(HOST));
    byte[] cookieBytes = cursor.getBlob(cursor.getColumnIndex(COOKIE));
    Cookie cookie = bytesToCookie(cookieBytes);
    return new SerializableCookie(host, cookie);
}
 
Example 20
Project: TPlayer   File: SerializableCookie.java   Source Code and License Vote up 4 votes
public static SerializableCookie parseCursorToBean(Cursor cursor) {
    String host = cursor.getString(cursor.getColumnIndex(HOST));
    byte[] cookieBytes = cursor.getBlob(cursor.getColumnIndex(COOKIE));
    Cookie cookie = bytesToCookie(cookieBytes);
    return new SerializableCookie(host, cookie);
}