Search code examples
c#xamarinxamarin.formsfirebase-cloud-messagingforeground

update data inside app each time i recieved a notification while app is open xamarin forms C# code ui?


Hi I'm using the puglin FirebasePushNotification. And i have my view with c# code and working width xamarin forms

CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
{
    //EJECUTAR ESTE METODO [OnNotificationReceived] POR DEFECTO Y NO CUANDO HAGA CLICK EN EL EVENTO
    try
    {
        System.Diagnostics.Debug.WriteLine("Enter OnNotificationReceived");
        var json = JsonConvert.SerializeObject(p.Data, Newtonsoft.Json.Formatting.Indented);
        FirebasePushNotificactionData myobject;
        myobject = new FirebasePushNotificactionData();
        myobject = JsonConvert.DeserializeObject<FirebasePushNotificactionData>(json);
        txtUsuario.Text = myobject.nombreUsuario;
        //obtenerDatosDelServicioZonasTrabajoAsync(myobject.codigo);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine("error: " + ex.Message);
    }
};

and the error ex.Message is

Only the original thread that created a view hierarchy can touch its views

the label (txtUsuario.Text) update with the correct data of the notification for the first time and this error only shows the first time too.

always enter in OnNotificationReceived. That's good but only the first time update the label.


Solution

  • You are trying to update the UI on a different thread. You can call this method, to update in the UI thread.

    Device.BeginInvokeOnMainThread(() =>
    {
        txtUsuario.Text = myobject.nombreUsuario;
    });