MessagingCenter is working on WPF but not working on Android - xamarin.forms

I created this app to answer some questions regarding MessagingCenter, but I am not able to continue the code due to a problem running the application specifically on the Android platform, if you know what may be wrong please help me. Thanks for the support.
I've tried to change some things how Result page to new Result view in messagingcenter subscribe, but i have no idea about what is happen, to me it's like not finding the message in subscribe.
App Link(GitHub)
In ResultView:
public void Registro()
{
MessagingCenter.Subscribe<ResultView>(this, "DisplayAlert", message =>
{
this.DisplayAlert("Alerta de Registro", "Mensagem DisplayAlert com registro Enviada", "Ok");
});
}
In MainPage:
ResultView ResultPage = new ResultView();
private void GoPaginaResultComRegistro(object sender, EventArgs e)
{
ResultPage.Registro();
MessagingCenter.Send<ResultView>(ResultPage, "DisplayAlert");
MessagingCenter.Unsubscribe<ResultView>(ResultPage, "DisplayAlert");
this.Navigation.PushAsync(ResultPage);
}
I wait for DisplayAlert on the other screen when sending the message, but the App simply skips the code inside subscribe.

First in your GoPaginaResultComRegistro() method ,you should send message after PushAsync
private void GoPaginaResultComRegistro(object sender, EventArgs e)
{
ResultPage.Registro();
this.Navigation.PushAsync(ResultPage);
MessagingCenter.Send<ResultView>(ResultPage, "DisplayAlert");
MessagingCenter.Unsubscribe<ResultView>(ResultPage, "DisplayAlert");
}
Second in your ResultView page, call DisplayAlert in the MainThread :
public void Registro()
{
MessagingCenter.Subscribe<ResultView>(this, "DisplayAlert", message =>
{
Device.BeginInvokeOnMainThread( async() =>
{
await DisplayAlert("Alerta de Registro", "Mensage DisplayAlert com registro Enviada", "Ok");
});
});
}

Try this
public void Registro()
{
MessagingCenter.Subscribe<ResultView,string>(this, "DisplayAlert", async (sender,message) =>
{
await DisplayAlert("Alerta de Registro", message, "Ok");
});
}
var mensagem = "teste";
MessagingCenter.Send<ResultView,string>(ResultPage, "DisplayAlert",mensagem);
Here is some example i use in my project
in my PCL MainPage.cs
public MainPage()
{
InitializeComponent();
MessagingCenter.Send<string>("ok", "showBar");
}
in my Native android project MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
MessagingCenter.Subscribe<string>(this, "showBar", (sender) =>
{
this.Window.ClearFlags(WindowManagerFlags.Fullscreen);
});
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
this.Window.AddFlags(WindowManagerFlags.Fullscreen);
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
you don't need to create new instance of your page to send as parameter.

Related

Java.Lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.auth.FirebaseAuth.zza

I'm trying to implement Authenticate with Firebase on Android using a Phone Number by following the Google official documentation on Xamarin Android. But I am getting this error:
Java.Lang.NullPointerException: 'Attempt to invoke virtual method 'void com.google.firebase.auth.FirebaseAuth.zza(java.lang.String, long, java.util.concurrent.TimeUnit, com.google.firebase.auth.PhoneAuthProvider$OnVerificationStateChangedCallbacks, android.app.Activity, java.util.concurrent.Executor, boolean)' on a null object reference'
I created an Android studio project And I got no error sending sms. I was supposed to publish the app yesterday but I'm stuck here.
Note: I have already a reference to Xamarin.GooglePlayServices.Base, Xamarin.Firebase.Auth:71.1605.0 and I have a code with push notification FCM which is working fine.
Here is my MainActivity.OnCreate code:
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
Xamarin.FormsMaps.Init(this, savedInstanceState);
FirebaseApp firebaseApp = FirebaseApp.InitializeApp(this);
var firebaseAuthInstance = FirebaseAuth.GetInstance(firebaseApp);
if(firebaseAuthInstance == null)
{
firebaseAuthInstance = new FirebaseAuth(firebaseApp);
}
verificationStateChangedCallbacks = new VerificationStateChangedCallbacks(); //This class is below.
PhoneAuthProvider.Instance.VerifyPhoneNumber("+16505559999", 60, TimeUnit.Seconds, this //The activity, verificationStateChangedCallbacks); // I got the error here
Class VerificationStateChangedCallbacks:
public class VerificationStateChangedCallbacks : OnVerificationStateChangedCallbacks
{
public override void OnVerificationCompleted(PhoneAuthCredential p0)
{
}
public override void OnVerificationFailed(FirebaseException p0)
{
}
public override void OnCodeSent(string p0, ForceResendingToken p1)
{
base.OnCodeSent(p0, p1);
}
}
I just fixed it by changing
PhoneAuthProvider.Instance.VerifyPhoneNumber("+16505559999", 60, TimeUnit.Seconds, this, verificationStateChangedCallbacks);
to
PhoneAuthProvider.GetInstance(firebaseAuthInstance).VerifyPhoneNumber("+16505559999", 60, TimeUnit.Seconds, this, verificationStateChangedCallbacks);
2 days and I didn't think about changing it.
can you check whether "PhoneAuthProvider.Instance" a null object. If yes then please check your file "google-services.json". Normally "FirebaseAuth.GetInstance(firebaseApp)" will not return a null.

Login and sign up issue

I am currently trying to build a new app (complete Novice) I have run into a strange issue on the login page.The sign up process works fine connects to firebase and returns to the login screen, then allows you to login and goes to the next activity. The problem occurs when you reload the app and use the details to re-login the login button does not work until you go into the sign up activity and come out of it then the login button works fine and allows you to sign in.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button button = findViewById(R.id.signupbtn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openSignupActivity();
}
});
}
private void openSignupActivity() {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
setContentView(R.layout.activity_login);
LoginEmail = findViewById(R.id.LoginEmail);
LoginPassword = findViewById(R.id.LoginPassword);
Loginprogressbar = findViewById(R.id.Loginprogressbar);
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.Loginbtn).setOnClickListener(this);
if conditions between
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Login Successful",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.Loginbtn:
Loginuser();
break;`enter code here`

Xamarin.Forms - OnStop(), OnExit(), OnClose()

I'm developing an app and I need to know when the app gets Stopped, Closed, Exited, whatever interrupts it, in order to stop some services such as WebSocket. How can I get 'access' to those events?
Thanks!
I have tested the following in a small example. (Tested it on UWP and works, the OnSleep() is called, when i close the App). The OnSleep() Method which can be overridden in the App.xaml.cs is the Method you are looking for.
The Xamarin Application LifeCycle offers some methods for your needs.
OnStart - Called when the application starts.
OnSleep - Called each time the application goes to the background.
OnResume - Called when the application is resumed, after being sent to the background.
Note that there is no method for application termination. Under normal
circumstances (ie. not a crash) application termination will happen
from the OnSleep state, without any additional notifications to your
code.
Example:
using System;
using System.Diagnostics;
using Xamarin.Forms;
namespace App1
{
public partial class App : Application
{
public App()
{
InitializeComponent();
if (Device.RuntimePlatform == Device.iOS)
MainPage = new MainPage();
else
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart() {
Debug.WriteLine("OnStart");
}
protected override void OnSleep() {
Debug.WriteLine("OnSleep");
}
protected override void OnResume() {
Debug.WriteLine("OnResume");
}
}
}
Update
According to this you have to catch unhandled exceptions in the native code. That makes it a lil complicated to shutdown your services.
Example:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {
protected override void OnCreate(Bundle bundle) {
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs) {
//crashed by exception
}
}
Further Reading on Unhandled Exceptions: here

Xamarin Navigation.PopAsync can't work.I write the code like official example

The app.cs:
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new App9.LoginPage());
}
The LoginPage.cs
public LoginPage()
{
InitializeComponent();
}
async void OnLoginButtonClicked(object sender, EventArgs e)
{
Navigation.InsertPageBefore(new Page1(), this);
await Navigation.PopAsync();
}
I write this like official example,but when I click the login button,the LoginPage can't remove.And when I click the login button another time,it throw a exception.
In the official example ,the code work well.
How can I do to make this work?

Windows service starts and exits immediately

I have written a windows service which in turn calls a web service. When I run the windows service from a test app., it works perfectly. However when I install the service and then start it, it stops almost immediately. The only two entries I see in the log are Constructor and Thread Started. Not sure what is wrong.
public partial class WindowsService : ServiceBase
{
public LogManager.LogFile _log;
public Thread m_thread;
protected TimeSpan m_delay;
CommonFunctions _cf = new CommonFunctions();
DBFunctions _db = new DBFunctions();
public WindowsService()
{
InitializeComponent();
_log = new LogManager.LogFile(#"c:\test\servicelog.txt", true, true);
_log.WriteToLog("Constructor", LogLevel.Level0);
}
protected override void OnStart(string[] args)
{
m_delay = new TimeSpan(0,0,300);
base.OnStart(args);
try
{
m_thread = new System.Threading.Thread(Execute);
m_thread.Start();
_log.WriteToLog("Thread Started", LogLevel.Level0);
}
catch (Exception ex)
{ _log.WriteToLog(ex.Message, LogLevel.Level0); }
}
public void Execute()
{
_log.WriteToLog("Begin Execute...", LogLevel.Level0);
try
{
ProcessNewLMSUsers();
}
catch (Exception ex)
{
_log.WriteToLog(ex.Message.ToString());
}
}
private void ProcessNewLMSUsers()
{
try
{
_log.WriteToLog("Begin: Processing new LMS Users", LogLevel.Level1);
// Check for new users in the LMS.
string callErrorText = "";
bool userAdded = false;
LMSWS.SSO lms = _cf.GetLMSSSOWS(); **// this is a web service**
lms.Timeout = 99999;
}
REST OF THE CODE.................
}
I can't see there is anything wrong with your code. but you can try to put a "Thread.Sleep(20000); " code at the begining of OnStart method. e.g.
protected override void OnStart(string[] args)
{
Thread.Sleep(20000);
m_delay = new TimeSpan(0,0,300); //set a break-point here
base.OnStart(args);
try
{
m_thread = new System.Threading.Thread(Execute);
m_thread.Start();
_log.WriteToLog("Thread Started", LogLevel.Level0);
}
catch (Exception ex)
{ _log.WriteToLog(ex.Message, LogLevel.Level0); }
}
and once you start this service program in Windows Service, then you have to quickly attach you source code to the service program. In visual studio, it's menu "Debug" -> "Attach to Process...". then you can set break-point in your source code anywhere to check what's going wrong.

Resources