0

我有一个非常奇怪的错误。它只发生在模拟器中。我在多部 Android 手机和 Acer 平板电脑上对其进行了测试,它在那里运行良好。

我的程序有一个循环,将位图加载到Bitmap[] bitCards. 数组由 14 个元素设置bitCards = new Bitmap[14]

现在它循环 12 次以将 Bitmap 放入 Array 中,如下所示:

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

当 i = 8 时,它会在此语句处崩溃。

如果我将其替换为

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

它不会崩溃,我想也许阵列不够大所以我做了以下

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

唯一有意义的是,当我有

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

它正在释放旧内存并放入一个新对象,因此只创建了一个对象的内存,但是....异常没有消失,我不应该得到某种错误吗?

这是我的完整代码:

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();
}
4

1 回答 1

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!

于 2012-08-31T17:26:24.757 回答