java.lang.NullPointerException in Blob

空扰寡人 提交于 2020-01-16 19:09:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!