0

I have a very strange bug. It only happens in the Emulator. I tested it on multiple Android phones and the Acer Tablet, it works fine there.

My program has a loop that loads in Bitmaps into a Bitmap[] bitCards. The Array is set up for 14 elements by bitCards = new Bitmap[14].

Now it loops 12 times to put a Bitmap into the Array as follows:

bitCards[i] = BitmapFactory.decodeStream(inputStream);

When i = 8 it crashes at this statement.

If i replace it with

bitCards[0] = BitmapFactory.decodeStream(inputStream);

it does not crash, I thought maybe somehow the Array was not big enough so I did the following

bitCards[8]=BitmapFactory.decodeStream(inputStream); // Still did not crash.

The only thing that makes sense is that when I have

bitCards[i] = BitmapFactory.decodeStream(inputStream);

It is relasing the old memory and putting in a new object, thus only memory for one object is created, but.... the exception does not go off, shouldn't I get some kind of an error?

Here is my full code:

void Shuffle()
{
    Random generator;
    generator = new Random();
    int[] iCardsUsed;
    iCardsUsed = new int[55];
    for(int i=0;i<55;i++)
    iCardsUsed[i]=0;

    try {   

        bitCards = new Bitmap[14];
        iCards = new int[14];
        iTurnOver = new int[14];

        for (int i = 0; i < 12; i++)
        {
            iTurnOver[i]=0;

            int cardId;

            do {
                cardId = generator.nextInt(50);
            } while( iCardsUsed[cardId] ==1);

            iCardsUsed[cardId] =1;
            iCards[i]=cardId;

            iCards[i]=i;    
            String fName=new String("card");
            fName+=Integer.toString(iCards[i]+1);
            fName+=".jpg";

            AssetManager assetManager= ctx.getAssets();
            InputStream inputStream;
            inputStream = assetManager.open(fName);

            // this is where it crashes
            bitCards[i]=BitmapFactory.decodeStream(inputStream);

            inputStream.close();    
        }

    } catch( IOException e)
    {
        gi++;
    }
    // update screen
    invalidate();
}
Dr1Ku
  • 2,875
  • 3
  • 47
  • 56
Ted pottel
  • 6,869
  • 21
  • 75
  • 134

1 Answers1

1

Since you have provided no error message, I am taking a shot in the dark and assuming it is going OOM.

You say that it stops after running for a few times ( when i = 8) , I believe that you are not freeing the resources. Bitmaps can sometime take up a lot of space and if you are persisting them in the memory, I would not be surprised if the device goes OutOfMemory. Different devices have different specs for memory and after a few runs it is filling up the memory.

So, my suggestion would be to clear the Bitmaps, using mBitmap.recycle(), and the other storage that you are using for temporary purposes.

Also, have a look at this question!

Community
  • 1
  • 1
Swayam
  • 16,294
  • 14
  • 64
  • 102