2012-01-06 8 views
0
public static File saveCanvasPictureToTempFile(Picture picture) 
{ 
    File tempFile = null; 

    // save to temporary file 
    File dir = getTempDir(); 
    if(dir != null) 
    { 
     FileOutputStream fos = null; 
     try 
     { 
      File f = File.createTempFile("picture", ".stream", dir); 
      fos = new FileOutputStream(f); 
      picture.writeToStream(fos); 
      tempFile = f; 
     } 
     catch(IOException e) 
     { 
      Log.e(TAG, "failed to save picture", e); 
     } 
     finally 
     { 
      close(fos); 
     } 
    }  

    return tempFile; 
} 

이 코드는 임시 파일을 만들어 주 활동으로 반환 하겠지만 파일은 주 활동에서 널 포인터 예외를 제공합니다. 내가 뭘 잘못하고 있니? 내 주요 활동에 대한인쇄 이미지에 NUll 포인터 예외가 발생했습니다.

코드는

void printCanvasAsBitmapExample() 
{ 
    // create canvas to render on 
    Bitmap b = Bitmap.createBitmap(240, 240, Bitmap.Config.RGB_565); 
    Canvas c = new Canvas(b); 

    // fill background with WHITE 
    c.drawRGB(0xFF, 0xFF, 0xFF); 

    // draw text 
    Paint p = new Paint(); 
    Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD); 
    p.setTextSize(18); 
    p.setTypeface(font); 
    p.setAntiAlias(true);  
    Rect textBounds = new Rect(); 
    p.getTextBounds(HELLO_WORLD, 0, HELLO_WORLD.length(), textBounds); 
    int x = (c.getWidth() - (textBounds.right-textBounds.left))/2; 
    int y = (c.getHeight() - (textBounds.bottom-textBounds.top))/2; 
    c.drawText(HELLO_WORLD, x, y, p); 

    // draw icon 
    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.icon); 
    c.drawBitmap(icon, 0, 0, null); 

    // queue bitmap for printing 
    try 
    { 
     File f = PrintUtils.saveBitmapToTempFile(b, Bitmap.CompressFormat.PNG); 
     if(f != null) 
     { 
      PrintUtils.queueBitmapForPrinting(this, f, Bitmap.CompressFormat.PNG); 
     } 
    } 
    catch(Exception e) 
    { 
     Log.e(TAG, "failed to save/queue bitmap", e); 
    } 
} 
+0

게시물에 logcat 오류를 넣을 수 있습니까? –

+0

@Khush, 게시판 오류 또는 정확히 어디에서 오류가 발생하는지 언급하십시오 –

답변

1

귀하의 오류로 인해 대신 fos = [context instance].openFileOutput(filename, mode)을 사용하는 안드로이드 특정 방법의 fos = new FileOutputStream(f)의 사용을 가능하게입니다.

tempDir에 쓸 수있는 권한이 없으므로 NullPointerException이 표시 될 수 있습니다.

documentation을 참조하십시오. 그것은 그것을 분명하게 내 보냅니다.

+0

고마워요. 도움이되었습니다. 하지만 tempDir은 여전히 ​​매니페스트 파일에 권한을 추가하는 데 영향을받지 않습니다. – Khush

관련 문제