androidxamarinmvvmcross

MvvmCross ViewModel exception when app returns from background


I'm using Xamarin.Android / Xamarin.iOS and MvvmCross for my current App project.

When my android app moves to background I get the exception “failed to construct and initialize ViewModel of type … from locator MvxDefaultViewModelLocator” (s. attached screenshot) when the app comes back to front again. But this happens not every time. It seems as if the error only occurs when the app was in background mode for a long time and many other apps are opened on the device. Has this something to do with Androids memory management?Exception

Thank you for your help.

EDIT: Thank you for your answers. Here is the inner exception:

MvvmCross.Plattform.Exceptions.MvxException: Problem running viewModel lifecycle of type QuestionListViewModel --> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation --> MvvmCross.Platfrom.Exceptions.MvxException: Missing text provider - please initialize IoC with a suitable IMvxTextProvider at MvvmCross.Localization.MvxLanguageBinder.get_TextProivder()...

So I'm using MvvmCross JsonLocalization plugin. On startup I register my textprovider like this:

TextProviderBuilder builder = new TextProviderBuilder(fileService.LocalizationDirectoryPath);
this.builder.LoadResources(cultureKey.Trim());
Mvx.RegisterSingleton<IMvxTextProvider(builder.TextProvider);
Mvx.RegisterSingleton<IMvxTextProviderBuilder>(builder);

and consume it like this in my ViewModel classes:

 public string GetText(string key)
 {
    string text = new MvxLanguageBinder(Constants.GeneralNamespace, "shared").GetText(key);

    return text;
 }

so it seems like the Android memory manager kills the textprovider singleton instance?


Solution

  • Yeah, this has to do something with the android memory management. If many apps are opened and your application didnt get used for a time, android decides that it can put on hold for the time being and frees the allocated memory.

    Did you check your inner exception? Probably something gets reinitialized in your ViewModel and it just cannot do it because some prerequisites are not fullfilled. You basically have to make sure that every view/viewmodel is kinda independent from the others.

    As a example: You parsed something in the previous viewmodel and do something with it in the next viewmodel. Since you somehow pass it over, you ofc have it in your second viewmodel. But if the memory management decides that the memory for your app can be freed, it will be lost, when you open it up again. So you need to make sure that your viewmodel either navigates back, retrieves the lost data somehow else, etc...

    Normally ofc MVVMCross takes care on most of that stuff, but without code from your viewmodel it is hard to put a finger on the problem.