我为一个人提取单张图片。一切顺利,但如果数据库中没有图像,我会得到一个异常(我的应用程序崩溃)。我用else语句处理这个问题,但它似乎没有用。 这是代码:
private void Get_Image_From_Database(DataBaseHelper db,String query)// GET_IMAGE
{
Bitmap bitmap=null;
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor c=db1.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst())
{
do
{
byte[] blob = c.getBlob(0);
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
bitmap = BitmapFactory.decodeStream(inputStream);
img.setImageBitmap(bitmap); // if there is a image it will render one
} while (c.moveToNext());
}
else{File imgfile=new File("/drawable/none.jpg"); //the else statement fails
Bitmap mybitmap=BitmapFactory.decodeFile(imgfile.getAbsolutePath());
img.setImageBitmap(mybitmap);}
}
}
我的目标是(如您所见)从数据库中获取图像(如果没有),如果没有,则显示默认图像。
答案 0 :(得分:0)
我认为drawable在你项目的资源中?
如果是,请尝试这样做以获得您的绘图:
Drawable myDrawable = getResources().getDrawable(R.drawable.none);
img.setImageDrawable(myDrawable);
答案 1 :(得分:0)
如果该图像位于Drawable文件夹中,则只需将其他部分更改为
即可else
{
img.setImageResource(R.drawable.none);
}
我猜else
部分位置错误。
修改强>
如果您正在使用try-catch
阻止,那么您可以在catch块中执行此操作
catch (Exception e)
{
img.setImageResource(R.drawable.none);
}
答案 2 :(得分:0)
for loading images you can use universal imageLoader, it will also hellp you to cache the images
and it has a beautiful option
ex
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.showImageOnLoading(R.drawable.placeholder)
.showImageForEmptyUri(R.drawable.placeholder)
.showImageOnFail(R.drawable.placeholder)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
as you can see if you dont have any image to display to can display the default image
答案 3 :(得分:0)
这解决了我的问题! Thanx家伙特别是aniruddha !!
private void Get_Image_From_Database(DataBaseHelper db,String query)// GET_IMAGE
{
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor c=db1.rawQuery(query, null);
c.moveToFirst();
if (c.isNull(0))
{
img.setImageResource(R.drawable.none);
}
else
{
byte[] blob = c.getBlob(0);
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
img.setImageBitmap(bitmap); // if there is a image it will render one
}
}