I have created an application that asks for a username and returns the stats for this user. When a counter is more than 1 it focuses on a picker and asks to choose one of the options. After, the SelectedIndexChanged (Platformselect_SelectedIndexChanged) method is being called and gets the stats. The problem is that if the user enters a username, the first time it works. When the user goes back and re-enters the username it doesn't focus (it doesn't show the picker) and automatically calls the SelectedIndexChanged method with platformselect.SelectedIndex being -1 causing my program to crash. Could you please help me?
I have tried to set focus on the main thread, I have tested it in both iOS and Android and the same problem appears.
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
platformselect.HeightRequest = 0;
this.search.Clicked += Button_Clicked;
}
public async void searchStats(string usernameText)
{
search.IsEnabled = false;
activityIndicator.IsRunning = true;
var id = await GetDataLogic.GetID(usernameText);
publicid = id;
activityIndicator.IsRunning = false;
if (id.uid == "error")
{
await DisplayAlert("Error", "Could not find username: " + usernameText, "OK");
search.IsEnabled = true;
return;
}
else if (id.uid == "errornointernet")
{
await DisplayAlert("Error", "Could not connect to the Internet. Please check your connection and try again.", "OK");
search.IsEnabled = true;
return;
}
else
{
if(id.platforms.Count > 1)
{
platformselect.ItemsSource = publicid.platforms.ToList();
//we have to show alert to choose platform and then call get user stats.
**Device.BeginInvokeOnMainThread(() =>
{
if (platformselect.IsFocused)
platformselect.Unfocus();
platformselect.Focus();
});**
}
else
{
//we call it without asking because there is only one platform.
var userstats = await GetDataLogic.GetStats(id, 0);
await Navigation.PushAsync(new Stats(userstats, favorites));
}
}
}
private async void Platformselect_SelectedIndexChanged(object sender, EventArgs e)
{
//the second time it doesnt show the picker and it automatically enters -1... it returns null exception. Has to be investigated.
var userstats = await GetDataLogic.GetStats(publicid, platformselect.SelectedIndex);
await Navigation.PushAsync(new Stats(userstats, favorites));
}
}
I would like it to always focus on the picker and wait for the response for the user, not automatically call SelectedIndexChanged with -1 as the selectedindex
if(platformselect.SelectedIndex == -1) return;
– Jesus Angulo