I'm trying to load in images from the disk in an other thread to not slow down my draw thread however the problem is that when the object that hold the bitmap is transfered to the new thread they have different pointers. I'm not exactly sure how Java handles pointers across multipliable threads but I'm looking for a solution that will have both threads working with the same object (shallow copy) and not depth copy of the object between threads.
Here is my code
new LoadImageTask().execute(ThisTimeDrawBitmaps.indexOf(bitmapWrapper), gameEngine);
private class LoadImageTask extends AsyncTask {
protected BitmapWrapper LoadImage(BitmapWrapper bitmapWrapper, GameEngine gameEngine) {
//loading the image in a temp object to avoid fatal error 11
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = true;
Bitmap tempImage = BitmapFactory.decodeResource(Sceptrum.GetResources, bitmapWrapper.getID(), options);
tempImage = Bitmap.createScaledBitmap(bitmapWrapper.getBitmap(), (int) (bitmapWrapper.getBitmap().getWidth() * gameEngine.getScale()), (int) (bitmapWrapper.getBitmap().getHeight() * gameEngine.getScale()), false);
//so that the image can be gc.
Bitmap RemovePointer = bitmapWrapper.getBitmap();
//to avoid fatal error 11
bitmapWrapper.setBitmap(tempImage);
//removing the old image.
RemovePointer.recycle();
return bitmapWrapper;
}
@Override
/**
* add the bitmapwrapper you want to load and make sure to add the GameEngine as the last parameter.
*/
protected Object doInBackground(Object... params) {
for (int i = 0; i < params.length - 1; i++) {
return LoadImage(ThisTimeDrawBitmaps.get((Integer) params[i]), (GameEngine) params[params.length - 1]);
}
return null;
}
}
public class BitmapWrapper{
private Bitmap bitmap;
/**
* Use only to send the bitmap as a parameter. To modify or read data to/from the bitmap use the methods provided by BitmapWrapper.
* @return
*/
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
private int id;
public int getID()
{
return id;
}
private Point originalSize;
public Point getOriginalSize() {
return originalSize;
}
public BitmapWrapper(Bitmap bitmap, int ID) {
this.setBitmap(bitmap);
id = ID;
originalSize = new Point(bitmap.getWidth(), bitmap.getHeight());
}
public int getWidth()
{
return bitmap.getWidth();
}
public int getHeight()
{
return bitmap.getHeight();
}
public void createScaledBitmap(GameEngine gameEngine)
{
bitmap = Bitmap.createScaledBitmap(bitmap, (int) (originalSize.x * gameEngine.getScale()), (int) (originalSize.y * gameEngine.getScale()), false);
}
public void CreateBitmap()
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
bitmap = BitmapFactory.decodeResource(Sceptrum.GetResources, id, options);
}
}