SQLite图像blob到字符串

时间:2017-08-02 11:24:39

标签: android sqlite android-sqlite blob

我试图从sqlite到字符串获取blob,请参阅下文:

ArrayList<Sudentdb> list;

GridView gridView;

final String[] from = new String[] { SQLiteHelper._ID,
        SQLiteHelper.NAME, SQLiteHelper.AGE, SQLiteHelper.PROFILE };

final int[] to = new int[] { R.id.rowid, R.id.txtName, R.id.studentage, R.id.profileimageV };

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.studentfragment, null);

    gridView = (GridView) v.findViewById(R.id.gridView);

    DBManager dbManager = new DBManager(getActivity());
    dbManager.open();

    Cursor cursor = dbManager.fetch();

    list = new ArrayList<>();
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.single_item, cursor, from, to, 0);

    gridView.setAdapter(adapter);

我测试过只返回文本并且它正确返回,但是对于图像我收到错误:

android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string

我认为我首先必须从数据库中获取图像?有什么帮助吗?

修改

我理解为什么你会认为这个问题是SimpleCursorAdapter how to show an image?的副本,但是在那个问题中,图像存储在drawable文件夹中,他正在保存并将该图像的名称作为字符串调用到sqlite中。在我的情况下,图像在库中,我将它作为blob保存到SQLite中(在另一个活动中),现在我试图从数据库中恢复blob并将其显示在GridView中。

所以在答案中,以下内容对我不起作用:

int resID = getApplicationContext().getResources().getIdentifier(cursor.getString(columnIndex), "drawable",  getApplicationContext().getPackageName());
IV.setImageDrawable(getApplicationContext().getResources().getDrawable(resID));

1 个答案:

答案 0 :(得分:0)

您可以使用它来从SQLITE

获取blob作为byte []
byte[] img = cursor.getBlob(cursor.getColumnIndex(IMG_SRC));

然后使用下面的Util方法将byte []转换为位图...

public static Bitmap getbitmap(byte[] img) {
        return BitmapFactory.decodeByteArray(img, 0, img.length);
    }