Basti Arcega
Basti Arcega

Reputation: 41

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

When pressing the login button, it throws an error mentioned despite the async is already used in the button to run the task and the code is correct.

token = await Task.Run(() => { return core.SignIn(username.Text, password.Text); }).ConfigureAwait(false);

Upvotes: 1

Views: 3743

Answers (1)

JoeTomks
JoeTomks

Reputation: 3276

You're trying to interact with an element of the UI that was created by the primary dispatcher from within a Task.

token = await Task.Run(() => 
{ 
    return core.SignIn(username.Text, password.Text); 
}).ConfigureAwait(false);

needs to be something like:

token = await Task.Run(() => 
{ 
    Activity.RunOnUiThread(()=>{
        return core.SignIn(username.Text, password.Text); 
    });
}).ConfigureAwait(false);

EDIT:

Slight tweak based on the assumption that you're getting the username and password from EditText controls:

token = await Task.Run(() => 
{ 
    string usernm = string.Empty;
    string pass = string.Empty;

    Activity.RunOnUiThread(()=>{
          usernm = username.Text;
          pass = password.Text;
    });

    return core.SignIn(usernm, pass);
}).ConfigureAwait(false);

Upvotes: 4

Related Questions