【问题标题】:SQLite image blob to stringSQLite 图像 blob 到字符串
【发布时间】:2018-01-09 14:26:20
【问题描述】:

我正在尝试从 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? 重复,但在那个问题中,图像存储在可绘制文件夹中,他正在保存并将该图像的名称作为字符串调用到 sqlite。在我的情况下,图像在图库中,我将它作为 blob 保存到 SQLite 中(在另一个活动中),现在我试图从数据库中取回 blob 并将其显示在 GridView 中。

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

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

【问题讨论】:

    标签: android sqlite android-sqlite blob


    【解决方案1】:

    您可以使用它从 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);
        }
    

    【讨论】:

    • 好的,我将如何在特定的视图中添加每个图像?目前我使用 SimpleCursorAdapter 设置每个视图中的文本
    • 请看我的代码final int[] to图片位置由SQLite中行的id决定
    • 好的,然后你从 sqlite 中检索 byte [] 数组和 id,使用 if/else 条件来设置 imageview,希望它有帮助,
    猜你喜欢
    • 2013-05-16
    • 2023-03-07
    • 2010-09-16
    • 2012-04-28
    • 2015-05-28
    • 2020-09-22
    • 2016-03-22
    • 2012-01-11
    • 1970-01-01
    相关资源
    最近更新 更多