0

アプリに画像を保存しようとしています。しかし、画像オブジェクトを永続化しようとすると、nullポインタ例外が発生します。これが私のImageクラスです:

 @PersistenceCapable
 public class ImageObject {

     @PrimaryKey
     @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
     private Key key;

     @Persistent
     private String title;

     @Persistent
     private Blob image;

     public ImageObject(){}

 //     all getters and setters
 }

以下は、例外を与えている私のサーブレットコードです:

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
    List<BlobKey> blobKeyList = blobs.get("upload_img_form_input");
    BlobKey blobKey = blobKeyList.get(0);
    String keyString = req.getParameter("upload_img_form_key");

    Key key = KeyFactory.createKey(ImageObject.class.getSimpleName(), keyString);
    Image img = ImagesServiceFactory.makeImageFromBlob(blobKey);
    ImageObject imgObj = new ImageObject();
    imgObj.setKey(key);
    imgObj.setTitle(keyString);
    imgObj.setImage(img.getImageData());
// i am getting exception at this line where i am trying to persist 
    pm.makePersistent(imgObj);

なぜこのNullPointerExceptionが発生するのか教えてもらえますか?前もって感謝します。

4

2 に答える 2

0

この行で Npe を使用できる唯一の方法:

pm.makePersistent(imgObj);

pmがnullのとき

その部分を確認する必要があります:

PersistenceManager pm = PMF.get().getPersistenceManager();

あなたのpersistence.xmlはクラスパスにありますか?

于 2012-10-23T15:09:17.640 に答える
0

私の経験では、変換を適用せずに画像を取得するとimg.getImageData()戻ります。画像変換を行わずに BLOB からバイトを取得する場合、実際にはイメージ サービスは必要なく、BLOB ストアからデータを取得するだけで済みます。ブログ投稿からこのコードを試してみましたが、うまく機能します。nullImagesServiceFactory.makeImageFromBlob

public static byte[] readBlobFully(BlobKey blobKey) {

    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);

    if (blobInfo == null)
        return null;

    if (blobInfo.getSize() > Integer.MAX_VALUE)
        throw new RuntimeException("This method can only process blobs up to " + Integer.MAX_VALUE + " bytes");

    int blobSize = (int) blobInfo.getSize();
    int chunks = (int) Math.ceil(((double) blobSize / BlobstoreService.MAX_BLOB_FETCH_SIZE));
    int totalBytesRead = 0;
    int startPointer = 0;
    int endPointer;
    byte[] blobBytes = new byte[blobSize];

    for (int i = 0; i < chunks; i++) {

        endPointer = Math.min(blobSize - 1, startPointer + BlobstoreService.MAX_BLOB_FETCH_SIZE - 1);

        byte[] bytes = blobstoreService.fetchData(blobKey, startPointer, endPointer);

        for (int j = 0; j < bytes.length; j++)
            blobBytes[j + totalBytesRead] = bytes[j];

        startPointer = endPointer + 1;
        totalBytesRead += bytes.length;
    }

    return blobBytes;
}
于 2014-08-26T08:22:01.567 に答える