[Question] Avoid exception "View is null" on Android
In Xamarin.Forms, when I leave a page with a MediaPlayerElement
on it, and come back, I restart the MediaPlayer at "OnAppearing" of the view.
This is working fine on iOS, however gives me an exception on Android.
I guess the problem is, that I create new MediaPlayer
while the MediaPlayerElement
is still invisible.
<vlc:MediaPlayerElement
x:Name="videoView"
BackgroundColor="{DynamicResource Black}"
EnableRendererDiscovery="True"
MediaPlayer="{Binding MediaPlayer}"
/>
--- End of managed Java.Lang.NullPointerException stack trace ---
java.lang.NullPointerException: view is null
at org.videolan.libvlc.AWindow.setView(AWindow.java:235)
at org.videolan.libvlc.AWindow.setVideoView(AWindow.java:268)
at mono.java.lang.RunnableImplementor.n_run(Native Method)
at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:30)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
After this crash, the view cannot be used anymore.
The crash happens at this code snippet:
MediaPlayer = new MediaPlayer(Media)
{
EnableHardwareDecoding = true,
NetworkCaching = Convert.ToUInt32(NetworkBufferTime),
FileCaching = Convert.ToUInt32(FileCaching),
};
This MediaPlayer is bound to the "MediaPlayer" property of the MediaPlayerElement
.
I also tried to check if the VideoView is null, before updating the MediaPlayer property.
However it says, view is not null.
bool viewReady = videoView?.VideoView != null
So my question now, is there a way to check in code behind if the native view is null or not?
Is there any property of the MediaPlayerElement
or MediaPlayer
object which indicates that the view
is not ready?
So that I can check it before updating the MediaPlayer property?
Thank you!