如何从sqlite db访问图像并使用游标适配器在android中的库中显示这些图像?

时间:2012-06-06 07:04:49

标签: android sqlite

我已经在代码中实现了这个,但它给出的错误无法将BLOB转换为long。在这里,我有一段代码,我已经实现但是我收到了一个错误:

Cursor cur = myDbHelper.getImages();  //images has been recieved in cursor

ImageAdapter adapter = new ImageAdapter(this, cur);

lst.setAdapter(adapter);



/* ImageAdapter Class*/
public ImageAdapter(Context context, Cursor cursor) {
        super(context, cursor);
        this.context = context;
        this.cursor = cursor;
    }

public View newView(Context context, Cursor cursor, ViewGroup arg2) {

                LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.residentgallery, null);
        ImageView iv = (ImageView) view.findViewById(R.id.iv1);
        if(cursor.moveToFirst())  
        {  
           do  
           {  
               System.out.println("byte array");
               byte[] data = cursor.getBlob(cursor.getColumnIndex("images"));  
               ByteArrayInputStream imageStream = new ByteArrayInputStream(data);  
               Bitmap theImage = BitmapFactory.decodeStream(imageStream);  
               iv.setImageBitmap(theImage);
               System.out.println("Imageview");
           }  
           while(cursor.moveToNext());  
        }

        return view;
    }

运行此代码后,我收到此错误:

android.database.sqlite.SQLiteException: unknown error: Unable to convert BLOB to long

我已在BLOB数据类型的sqlite中保存图像。 伙计们,请帮帮我。

1 个答案:

答案 0 :(得分:0)

如果您想从标准图库中获取图片/照片

String[] selectFields = new String[] {
    MediaStore.Images.Media._ID,
    MediaStore.Images.Media.DISPLAY_NAME,
    // other fields you interested in
    };

Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selectFields ,where,null,orderBy);
if(cursor!=null && cursor.moveToFirst()){
    int col_id = cursor.getColumnIndex(MediaStore.Images.Media._ID);
    while (!cursor.isAfterLast()) {
        int imageID = cursor.getInt(col_id);
        Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageID));
        InputStream istr = contentResolver.openInputStream(uri);
        Bitmap bitmap= BitmapFactory.decodeStream(istr);
        cursor.moveToNext();
    }
    cursor.close();
}

如果您想稍后存储和获取您应用的私有图片

将图像存储为单独的文件并将数据库和其他与此图像相关的元数据插入数据库是一种很好的做法。您始终可以从db中选择文件名,然后从文件中读取图像。

此外,将许多大文件存储在内部存储器中并不好。可能你可以使用SD卡吗?