Get user data before downloading the application

валера карманов 396 Reputation points
2024-10-04T07:06:07.21+00:00

I'm trying to add a login page to an Android app. There are no problems with the page itself, the issue is how to get user data before loading the app, namely.

public partial class App : Application
{
	public App()
	{
		InitializeComponent();
		var userId = Preferences.Get("userId", "0");
		if(Int32.Parse(userId) > 0)
		{
			HttpRequest request = new HttpRequest();
			request.LoadedUserData(userId, this);
		}
		else
		{
			MainPage = new Pages.LoginPage();
		}
		// System.NotImplementedException:
		// 'Either set MainPage or override CreateWindow.'
	}
}

public async void LoadedUserData(string userId, Application app)
{
	try
	{
		response = await client.GetAsync("/userdata.php?id=" + userId);
		if (response.IsSuccessStatusCode)
		{
			var content = await response.Content.ReadAsStringAsync();
			AppShell.userData = JsonSerializer.Deserialize<UserData>(content, jsonOptions);
			app.MainPage = new AppShell();
		}
		else
		{
			app.MainPage = new Pages.ErrorPage("Error text default");
		}
	}
	catch (Exception ex)
	{
		Debug.WriteLine("Error : " + ex.Message);
		app.MainPage = new Pages.ErrorPage(ex.Message);
	}
}

The error occurs in the "AppShell" class, most likely because the application continues loading regardless of whether the request is completed or not. How can I fix this?

Maybe it is possible to make an HttpClient request without using "Async"?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,596 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 44,016 Reputation points Microsoft Vendor
    2024-10-07T05:42:06.59+00:00

    Hello,

    For the case of obtaining user information to determine the page display, it is recommended that you place it in the OnAppearing method of AppShell for the following reasons.

    • App.xaml.cs is not a UI component. For UI initialization, it would be a better choice to write it in AppShell.xaml.cs.
    • HttpClient initiates a request to the Service asynchronously, so it is necessary to use await when calling it, but the async/await keywords are not allowed in the constructor. Therefore, you can put this method in the OnAppearing method of AppShell.xaml.cs to process this request when the UI is initialized.
    protected override async void OnAppearing()
    {
        base.OnAppearing();
        // Handle Http request here.
    }
    

    Updated:

    This order is expected. Usually, when an app loads user data, it will first load a loading animation page instead of loading data when the app starts. Then decide whether to display the home page or the login page based on the network request. The reasons are as follows:

    • Use animated pages to load data, and the page transition will be smoother.
    • The API that requests user data is not guaranteed to be available all the time. For example, the user may be out of network, the server may be delayed, or the DNS resolution may be wrong. In these cases, if there is no page to remind the user that the program has encountered an error, the application will be stuck on the SplashScreen. On Windows platforms, this means that the window is not loaded after the application is opened.

    In general, developers should avoid anything that would cause their app to lag on startup.

    If you need to implement it in the order of requesting user data before loading, you need to add this method to the constructor of App. This will cause the program to be unable to handle the situation where the Task request fails.

    You could refer to the following runable code sample:

    
    public App()
    
    {
    
        InitializeComponent();
    
        Debug.WriteLine("Start");
    
        Task.Run( async() => await LoadedUserData("1"));
    
        MainPage = new AppShell();
    
    }
    
    public async Task LoadedUserData(string userId)
    
    {
    
        try
    
        {
    
            using (var client = new HttpClient())
    
            {
    
                HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/" + userId);
    
     
    
                if (response.IsSuccessStatusCode)
    
                {
    
                    string content = await response.Content.ReadAsStringAsync();
    
                    // Debug.WriteLine("189|content : " + content);
    
     
    
                    AppShell.userData = JsonSerializer.Deserialize<UserData>(content);
    
     
    
                    Debug.WriteLine("193|UserID : " + AppShell.userData.id);
    
                    Debug.WriteLine("194|Username : " + AppShell.userData.title);
    
                }
    
                else
    
                {
    
                    Debug.WriteLine("198|Error");
    
                    App.Current.MainPage = new LoginPage();
    
                    /*
    
                    app.MainPage = new Pages.ErrorPage(
    
                        ErroCode.HttpClientRequest,
    
                        AppResources.HttpClientRequestError,
    
                        "Error text"
    
                    );
    
                    */
    
                }
    
            }
    
        }
    
        catch (Exception ex)
    
        {
    
            Debug.WriteLine("Class name : " + ex.ToString());
    
            Debug.WriteLine("Error : " + ex.Message);
    
     
    
            /*
    
            app.MainPage = new Pages.ErrorPage(
    
                ErroCode.HttpClientRequest,
    
                AppResources.HttpClientRequestError,
    
                ex.Message
    
            );
    
            */
    
        }
    
     
    
     
    
    }
    
    

    In the MainPage of AppShell:

    
    public MainPage()
    
            {
    
                InitializeComponent();
    
                Debug.WriteLine("DashboardPage");
    
                Debug.WriteLine("End");
    
            }
    
    

    Debug Input:

    
    Start
    
    193|UserID : 1
    
    194|Username : delectus aut autem
    
    DashboardPage
    
    End
    
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.