从Android中的数据库读取后无法在ImageView中显示图像

时间:2014-09-25 04:40:09

标签: android image sqlite imageview

我试图在从图库读入数据库后保存图像并将其显示在ImageView中。当我运行我的代码没有错误,但我无法在ImageView中看到我的图像。我会发布相关的代码。

我计划在点击ImageView时打开图库 -

imgProfile.setOnClickListener(new OnClickListener()  // imgProfile is object of Imageview
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Select Picture"),
                    SELECT_PICTURE);
        }
    });

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode == RESULT_OK)
    {
        if (requestCode == SELECT_PICTURE)
        {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);       // selectedImagePath is String
            BitmapFactory.Options bOp = new BitmapFactory.Options();  // bmap is Bitmap
            bmap = BitmapFactory.decodeFile(selectedImagePath, bOp);
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            bmap.compress(Bitmap.CompressFormat.PNG, 100, bOut);
            img = bOut.toByteArray();                                 // img is byte[]
            db.storeProfilePic(num, img);                    // db is object of database class

            cur = db.readPic(num);  // cur is Cursor. num is used as primary key in the table
            if (cur != null)
            {
                cur.moveToFirst();
                do {
                    img = cur.getBlob(cur.getColumnIndex("image"));    // img is byte[]
                } while (cur.moveToNext());
            }

            Bitmap b1 = BitmapFactory.decodeByteArray(img,0, img.length);
            imgProfile.setImageBitmap(b1);                           // imgProfile is ImageView
        }
    }
}

public String getPath(Uri uri)
{
    if (uri == null)
    {
        return null;
    }
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null)
    {
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    return uri.getPath();
}

将图像保存到数据库的功能 -

public void storeProfilePic(String user, byte[] img)
{
    String query = "insert into profilePicture(userID, image) values('" + user
            + "', '" + img + "')";
    db1.execSQL(query);                        // db1 is SQLiteDatabase
}

从数据库中读取图像的功能 -

public Cursor readPic(String ID)
{
    String query = "select image from profilePicture where userID = '" + ID + "'";
    cur = db1.rawQuery(query, null);
    return cur;
}

我的代码有什么问题?我该如何编辑它以使图像显示在ImageView中?

2 个答案:

答案 0 :(得分:0)

最后,当没有其他人帮助时,我找到了解决方案。我刚做了一些编辑,现在情况正常。

txtCP.setOnClickListener(new OnClickListener()  // I changed the Imageview from here and put a TextView
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Select Picture"),
                    SELECT_PICTURE);
        }
    });
}

我只想在单击TextView对象txtCP时将图像保存到数据库,但是在我参加此活动时多次显示它。所以我使用SharedPreferences来做到这一点。

@Override
protected void onResume()
{
    super.onResume();

    if (prefs.getBoolean("firstrun", true))  // prefs is object of SharedPreferences
    {
        loadProfilePic();
        prefs.edit().putBoolean("firstrun", false).commit();
    }
}

private void loadProfilePic()
{
    cur = db.readPic(num);
    if (cur != null)
    {
        cur.moveToFirst();
        do
        {
            img = cur.getBlob(cur.getColumnIndex("image"));
        } while (cur.moveToNext());
    }

    Bitmap b1 = BitmapFactory.decodeByteArray(img, 0, img.length);
    imgProfile.setImageBitmap(b1);
}

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode == RESULT_OK)
    {
        if (requestCode == SELECT_PICTURE)
        {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            BitmapFactory.Options bOp = new BitmapFactory.Options();
            bmap = BitmapFactory.decodeFile(selectedImagePath, bOp);
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            bmap.compress(Bitmap.CompressFormat.PNG, 100, bOut);
            img = bOut.toByteArray();
            db.storeProfilePic(num, img);

            loadProfilePic();
        }
    }
}

public String getPath(Uri uri)
{
    if (uri == null)
    {
        return null;
    }
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null)
    {
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    return uri.getPath();
}

将图像保存到数据库的功能 -

public void storeProfilePic(String user, byte[] img)
{
    ContentValues cv = new ContentValues();
    cv.put("userID", user);
    cv.put("image", img);
    db1.insert("profilePicture", null, cv);
}

从数据库中读取图像的功能与问题中的相同。

答案 1 :(得分:-1)

使用此cose:

      image.setImageBtmap(decodeSampledBitmapFromUri(url, 200,
        200));

     public static Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,
        int reqHeight) {

    Bitmap bm = null;
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(path, options);

    return bm;
}

public static int calculateInSampleSize(

BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }

    return inSampleSize;
}