Xamarin Forms user login and logout not working on Android

2.3k views Asked by At

I have problem with login and logout user. If in first time i click button login and after click logout everything works good but if i again launch app i have only blank page and i have to uninstall app thaht works like in first case

App.cs Code:

public App()
{
    InitializeComponent();

     if (!Current.Properties.ContainsKey("IsLoggedIn"))
     {
        Current.Properties["IsLoggedIn"] = false;
        if ((bool)Current.Properties["IsLoggedIn"] == false)
        {
            MainPage = new LoginPage();
        }
        else
        {
            MainPage = new NavigationPage(new MainPage());
        }
     }
}

Login Page:

async private void Button_Clicked_Login(object sender, EventArgs e)
{
   Application.Current.Properties["IsLoggedIn"] = true;
   await Application.Current.SavePropertiesAsync();
   Application.Current.MainPage = new NavigationPage(new MainPage());
}

Logout:

 async private void Button_Clicked(object sender, EventArgs e)
 {
    Application.Current.Properties["IsLoggedIn"] = false;
    await Application.Current.SavePropertiesAsync();
    Application.Current.MainPage = new LoginPage();
 }
1

There are 1 answers

0
Taier On BEST ANSWER

The problem is in

if (!Current.Properties.ContainsKey("IsLoggedIn"))

On the first app launch, you are checking if that property exists. And it does not exists, so it goes into your if statement. But then, you assign that property, and for next launches that if will always fail.

I would suggest you to re-write that if statement into something like that:

    if (!Current.Properties.ContainsKey("IsLoggedIn")) {
        Current.Properties["IsLoggedIn"] = false;
        await Application.Current.SavePropertiesAsync();
        MainPage = new LoginPage();
     } else {
        if(Current.Properties["IsLoggedIn"] == true) {
          MainPage = new NavigationPage(new MainPage());
        } else {
          MainPage = new LoginPage();
        }         
     }