2012-01-06 23 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錯誤在你的文章? – 2012-01-06 04:32:21

+0

@Khush,發佈logcat錯誤或確切地提到你錯誤的位置 – 2012-01-06 05:12:37

回答

1

你的錯誤可能是由於fos = new FileOutputStream(f)而是採用fos = [context instance].openFileOutput(filename, mode)的Android的特定方式使用。

這可能是因爲您沒有權限寫入tempDir,因此您得到NullPointerException

請參閱documentation。它清楚地闡述了它。

+0

非常感謝。這有幫助。但是,儘管我在清單文件中添加了權限,tempDir仍然沒有創建。 – Khush 2012-01-06 05:26:49