maui: [regression/8.0.0-preview.5.8529] Crash on scrolling collection view

Description

App just crashes with Java.Lang.RuntimeException: 'Canvas: trying to use a recycled bitmap android.graphics.Bitmap@4b0165b' Seems like the same issue as before. This should be solved here, but in every 8.0.* revision it seems to still be crashing (and I’ve tried them all).

Here is the call stack. It always seems to be the same. The very odd thing in it is the reference to net7.0/JniEnvironment.g.cs. As the version I’m runing the app is .net8 ¯_(ツ)_/¯ image

Steps to Reproduce

  1. open my repository in github (it has some redundant parts from testing over issues, but does the job)
  2. run on android emulator
  3. wait for a minute until it crashes (try to stay on the top of the page, so new images appear and push over images down)

Expected behavior: images open up and older images are pushed down

Actual behavior: images open up and older images are pushed down, but after about a minute you experience a crash with Java.Lang.RuntimeException: 'Canvas: trying to use a recycled bitmap android.graphics.Bitmap@4b0165b

P.S. for anyone that might launch the app on windows and see the insane behavior of DataTemplates - I already reported it here, over a year back.

Link to public reproduction project repository

https://github.com/MissedSte4k/MAUI-Canvas-trying-to-use-a-recycled-bitmap-crash-sample

Version with bug

8.0.0-preview.5.8529

Is this a regression from previous behavior?

Yes, this used to work in .NET MAUI

Last version that worked well

8.0.0-preview.4.8333

Affected platforms

Android

Affected platform versions

No response

Did you find any workaround?

Nope. Tried everything referenced in issues that got solved in https://github.com/dotnet/maui/pull/12310, but to no avail.

Relevant log output

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 6
  • Comments: 35 (6 by maintainers)

Most upvoted comments

When I replace the default StreamImageSourceService with the following code. Scroll through the CollectionView quickly and the program never crash again.

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            })
            .ConfigureImageSources(services =>
            {
#if ANDROID
                services.RemoveAll<IImageSourceService<IStreamImageSource>>();
                services.RemoveAll<IImageSourceService<StreamImageSource>>();
                services.AddService<IStreamImageSource>(_ => new CustomStreamImageSourceService());
                services.AddService<StreamImageSource>(_ => new CustomStreamImageSourceService());
#endif
            });

#if DEBUG
		builder.Logging.AddDebug();
#endif

        return builder.Build();
    }

#if ANDROID

    public class CustomStreamImageSourceService : StreamImageSourceService
    {
        public override async Task<IImageSourceServiceResult?> LoadDrawableAsync(IImageSource imageSource, ImageView imageView, CancellationToken cancellationToken = default)
        {
            var result = await base.GetDrawableAsync(imageSource, imageView.Context!, cancellationToken);
            // if (result?.Value is BitmapDrawable drawable && drawable.Bitmap?.IsRecycled == true)
            // {
            //     drawable.Bitmap.IsRecycled always false.
            // }
            imageView.SetImageDrawable(result?.Value);
            return result;
        }
    }

#endif

}

It might be base.LoadDrawableAsync passes a recycled bitmap to imageView, causing the program to crash. The same may be required for both FileImageSource and UriImageSource. (Machine translation was used)

From my tests this resolve the problem

I have seen this before. Not specifying the Height and Width request, in your ImageViews, (using URLs of uploaded pictures with 1000x1600 for example as source) that are contained in your CollectionView, lead to the following problems:

In Android: You get random runtime crashes, when you scroll down the collection view. In IOS: You get empty collection view the first time you enter the page. Collection view with only first item loaded the second time you enter the page. And full collection view when you enter 3rd time in the page.

Setting WidthRequest=100, HeightRequest=100 is quick way to check if this applies to you.

(Forgot to say that this IOS behavior does not repeat when you close and open the app (it seems caching is involved in making the problem resolve itself), only reinstall introduces it again. But on Android it is persistent.)

When I replace the default StreamImageSourceService with the following code. Scroll through the CollectionView quickly and the program never crash again.

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            })
            .ConfigureImageSources(services =>
            {
#if ANDROID
                services.RemoveAll<IImageSourceService<IStreamImageSource>>();
                services.RemoveAll<IImageSourceService<StreamImageSource>>();
                services.AddService<IStreamImageSource>(_ => new CustomStreamImageSourceService());
                services.AddService<StreamImageSource>(_ => new CustomStreamImageSourceService());
#endif
            });

#if DEBUG
		builder.Logging.AddDebug();
#endif

        return builder.Build();
    }

#if ANDROID

    public class CustomStreamImageSourceService : StreamImageSourceService
    {
        public override async Task<IImageSourceServiceResult?> LoadDrawableAsync(IImageSource imageSource, ImageView imageView, CancellationToken cancellationToken = default)
        {
            var result = await base.GetDrawableAsync(imageSource, imageView.Context!, cancellationToken);
            // if (result?.Value is BitmapDrawable drawable && drawable.Bitmap?.IsRecycled == true)
            // {
            //     drawable.Bitmap.IsRecycled always false.
            // }
            imageView.SetImageDrawable(result?.Value);
            return result;
        }
    }

#endif

}

It might be base.LoadDrawableAsync passes a recycled bitmap to imageView, causing the program to crash. The same may be required for both FileImageSource and UriImageSource. (Machine translation was used)

Still have this issue as well on Android using Maui 8.0.92 with .NET SDK 8.0.403 as well

@Simoo23 Instead of using Image in XAML and binding ImageSource, I use ContentView and I bind Content to byte[].

I ran into this one again on my own app when I decided to remove the WidthRequest from my images. Setting an explicit WidthRequest and HeightRequest is certainly the workaround.

Meaning the crashing stops? I’ve wondered if perhaps I can set or bind the height/width request to a calculated value so it is provided (but still fills the available width/height but stops the crashes)

Not only the android crashing. The weird behavior on IOS also. You open “details” page, that contains CollectionView, that has ItemTeplate of DataTemplate of Image. Nothing else. And on the Image you have set “MaximumWidthRequest” and “MaximumHeightRequest”, with aspect set to Fit. Open details once - empty. Second - only one image showing. Third time - everything.

Set specific measurements and both problems are gone.

To make matter worse - on the device I develop with most of the time, this problem could not be reproduced. On one of the test devices, this problem was showing, but only if your list has set amount of items. 4 or 5 pages - no problem. And the key to find this out was another test device, that was throwing this exception (crashing, actually), the second you try to scroll.

I hope this saves you some time.

Thanks for the reply!

Setting WidthRequest=100, HeightRequest=100 is quick way to check if this applies to you.

Meaning the crashing stops? I’ve wondered if perhaps I can set or bind the height/width request to a calculated value so it is provided (but still fills the available width/height but stops the crashes)

Same issue with .NET 8. I have a CollectionView with images, if you scroll the list the app will crash. I didn’t find any workaround.

Same here 😕 I had to wait with releasing of my app due to huge issues in .net7 These were fixed in .net8 but now I am stopped at this one 😕 so I cannot release my app to my customers again… No workaround works for me.