0

This is quite a tricky one. I thought I had it resolved as it was working with my S2. But the problem has come back during testing HTC One M7.

I have a welcome screen kind of app, which keeps displaying random (or same selected) images from a storage folder whenever user switches phone on.

I'm preparing image view in OnResume, where I'm calling my image drawing method.

    protected void onResume() {
      super.onResume();
      if (isCallActive(this) == false) {
        changeImage(false);
      } else {
      }
    }

ChangeImage method code is:

    public void changeImage(Boolean vForce) {
      String pathV = null;
      SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
      Boolean vPicChosen;
      vPicChosen = pref.getBoolean("PicChosen", false);
      if (vPicChosen == true) {
        pathV = pref.getString("PicURL", "NOPIC");
      } else pathV = "NOPIC";
      if (pathV == "NOPIC" || vForce == true) {
        pathV = randomPic();
      }
      imgFile = new File(pathV);

    if(imgFile.exists()) {
        img1 = (ImageView)findViewById(R.id.imageView);
        Display display = getWindowManager().getDefaultDisplay();
        float width = display.getWidth();
        float height = display.getHeight();
        if (reusedBitmap != null && !reusedBitmap.isRecycled()) {
            //reusedBitmap.recycle();
        }
        reusedBitmap = decodeSampledBitmapFromPath(pathV, (int)width, (int)height); 
        img1.setImageBitmap(reusedBitmap);

    }
    else
        Toast.makeText(this,  "no Image present", Toast.LENGTH_SHORT).show();

  }

Now with this code, every time my app was presenting an image (same or different), the memory heap was growing by 3 to 6MB, depending upon the image size. After 5-6 screen switchons, the memory would go beyond 50Mb, and eventually result in out of memory, or app being killed.

So I tried many things, and eventually succeeded in keeping a tab on memory by recycling the bitmap in onStop method:

    @Override
protected void onStop() {
    Log.i("event","onStop");
    if (reusedBitmap != null && !reusedBitmap.isRecycled()) {
        reusedBitmap.recycle();
    }
}

As I mentioned earlier, this used to work fine on my S2.

But on my HTC One M7, due to this call, image drawing is throwing error

12-03 16:21:12.944: E/AndroidRuntime(25881): java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@41af3468

If I remove this line from onStop, the memory growing problem comes back.

Any suggestion please?

kaushal
  • 53
  • 4
  • Could you try nullifying the bitmap after recycling it and check? `reusedBitmap.recycle(); reusedBitmap = null;` – Antrromet Dec 03 '14 at 16:43
  • Tried, unfortunately it throws same exception of "trying to use a recycled bitmap" when activity is started and application tries to draw the imageview. – kaushal Dec 03 '14 at 16:55

0 Answers0