I am testing the app on my phone (size 720x1280). The app runs fine when I use the sample size of 2. When I tried to use the sample size of 1 the app crashes in the line where I draw the image (code mentioned below). Please point me where my code need correction.
canvas.drawBitmap(backgoundImage, 0, 0 , null);
public Bitmap getAssetImage(Context context, String filename) throws IOException {
AssetManager assets = getApplicationContext().getResources().getAssets();
InputStream buffer = null;
try {
buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
if (tabletSize) {
Log.i("DragDrop", "am tablet");
} else {
Log.i("DragDrop", "am phone");
options.inSampleSize = 1;
}
Bitmap temp = BitmapFactory.decodeStream(buffer, null, options);
Bitmap finalImage = Bitmap.createScaledBitmap(temp, (int) dWidth, (int) dHeight, true);
temp.recycle();
temp=null;
return finalImage;
}
07-07 12:28:14.150: E/AndroidRuntime(7256): FATAL EXCEPTION: Thread-748
07-07 12:28:14.150: E/AndroidRuntime(7256): java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@416ec9f0
07-07 12:28:14.150: E/AndroidRuntime(7256): at android.graphics.Canvas.throwIfRecycled(Canvas.java:1026)
07-07 12:28:14.150: E/AndroidRuntime(7256): at android.graphics.Canvas.drawBitmap(Canvas.java:1065)
07-07 12:28:14.150: E/AndroidRuntime(7256): at com.example.funandlearn.DragDrop$MyBringBackSurface.run(DragDrop.java:640)
07-07 12:28:14.150: E/AndroidRuntime(7256): at java.lang.Thread.run(Thread.java:856)
For your reference Line # 640 has the code
canvas.drawBitmap(backgoundImage, 0, 0 , null);
You have this
Bitmap temp = BitmapFactory.decodeStream(buffer, null, options);
Bitmap finalImage = Bitmap.createScaledBitmap(temp, (int) dWidth, (int) dHeight, true);
temp.recycle();
temp=null;
Your logcat says
Canvas: trying to use a recycled bitmap
You should recycle bitmap when not in use.
Quoting from the docs
On Android 2.3.3 (API level 10) and lower, using recycle() is recommended.
You should use recycle()
only when you are sure that the bitmap is no longer being used. If you call recycle() and later attempt to draw the bitmap, you will get the error: "Canvas: trying to use a recycled bitmap".
Manage Memory on Android 3.0 and Higher
Android 3.0 (API Level 11) introduces the BitmapFactory.Options.inBitmap field. If this option is set, decode methods that take the Options object will attempt to reuse an existing bitmap when loading content. No need to use recycle
.
Also check this
http://developer.android.com/training/displaying-bitmaps/manage-memory.html