我使用java.sql.Blob对象在mySql中保存图像。 当我在数据库中尝试插入对象时,我有异常“Java.lang.NullPointerException”
这是我的代码:
@Override
protected Object doInBackground(Object... arg0) {
try {
Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Users user = new Users();
user.setName("haris");
下一个代码让我异常。
try {
Blob blo = null;
blo.setBytes(1, getBytes(photo));
} catch (Exception e) {
System.out.println("Error:"+e.toString()); //There is my Exception
}
/
if (Korisnik_servis.Registracija(user)){ // Call my REST services
System.out.println("Registration succesful");
}
else
{
System.out.println("Registration not succesful");
}
} catch (Exception e) {
System.out.println("Error:"+e.toString());
}
return null;
}
将位图转换为byte []
的功能public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
我的问题是:如何成功初始化Blob对象。
答案 0 :(得分:1)
我正在使用这段代码在Blob中存储位图(从drawable转换而来):
db = this.getWDB();
ContentValues values = new ContentValues();
Drawable d = model.getAppIcon();
BitmapDrawable bitDw = ((BitmapDrawable) d);
Bitmap bitmap = bitDw.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageInByte = stream.toByteArray();
values.put(COLUMN_ICON_BLOB, imageInByte);
db.insert(TABLE_APPS, null, values);
db.close();
并从数据库中检索此方法
public static Drawable convertByteArrayToDrawable( byte[] byteArrayToBeCOnvertedIntoBitMap) {
Bitmap bitMapImage = BitmapFactory.decodeByteArray(
byteArrayToBeCOnvertedIntoBitMap, 0,
byteArrayToBeCOnvertedIntoBitMap.length);
return new BitmapDrawable(bitMapImage);
}
答案 1 :(得分:1)
您有异常,因为Blob是一个接口,而setBytes是一个抽象方法。请检查此链接how to store Image as blob in Sqlite & how to retrieve it?