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

从Android中的数据库读取后,无法在ImageView中显示图像,android,image,sqlite,imageview,Android,Image,Sqlite,Imageview,我试图在从图库读取到数据库并在ImageView中显示后保存图像。当我运行代码时没有错误,但我无法在ImageView中看到我的图像。我会发布相关代码 我计划在单击ImageView时打开图库- imgProfile.setOnClickListener(new OnClickListener() // imgProfile is object of Imageview { @Override public void onClick(View v)

我试图在从图库读取到数据库并在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;
}
函数从数据库中读取图像-

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中?

使用此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;
}

最后,当没有其他人帮忙时,我找到了一个解决办法。我刚刚做了一些编辑,现在一切正常

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时将图像保存到数据库,但在我进行此活动时显示它的次数相同。所以我用SharedReferences来做这件事

@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);
}

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

在哪里显示图像?我们所能看到的只是您正在选择一个光标。另外,将图像存储在数据库中不是一个好主意,最好将它们作为文件存储在文件系统中。您是否将图像URL保存在数据库中,如果是,那么您是否使用select方法从数据库中获取这些URL???@BalvinderSingh如果这是问题,我应该如何编辑代码?@panini在-cur=db.readPic(num)之后查看if条件;我正在向计算机显示我的图像ImageView@panini为什么将图像保存到数据库不是一个好主意?从数据库获取url的位置将该url放在image.setImageBtmap(decodeSampledBitmapFromUri(url,200200))中;如果数据库中有多个URL,您可以在循环中使用它。这不是一个URL,而是一个数据块。我认为您必须在数据库中保存图像的URL,这将使您易于处理图像,否则您稍后会遇到内存异常。我需要在我的应用程序中保存这些图像,即使它们已从库中删除。在这种情况下,保存URL是个好主意吗?