问题
I using java.sql.Blob object to save images in mySql. When i try insert object in database i have exception "Java.lang.NullPointerException"
Here is my code :
@Override
protected Object doInBackground(Object... arg0) {
try {
Bitmap photo = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Users user = new Users();
user.setName("haris");
Next code get me exception.
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;
}
Function for convert Bitmap to byte []
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
My question is: how to successfully initialize Blob object.
回答1:
I am using this piece of code to store bitmaps in blobs (converted from 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();
and to retrieve it from database this method is used
public static Drawable convertByteArrayToDrawable( byte[] byteArrayToBeCOnvertedIntoBitMap) {
Bitmap bitMapImage = BitmapFactory.decodeByteArray(
byteArrayToBeCOnvertedIntoBitMap, 0,
byteArrayToBeCOnvertedIntoBitMap.length);
return new BitmapDrawable(bitMapImage);
}
回答2:
You have exception because Blob is an interface and setBytes is an abstract method. Check this link how to store Image as blob in Sqlite & how to retrieve it?
来源:https://stackoverflow.com/questions/14607032/java-lang-nullpointerexception-in-blob