Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RunOnUIThread() in Xamarin Android

I would like to run this statement after getting result into OStateUserId object.

details.Text = OStateUserID.name + "\n" + OStateUserID.population);

bStateuserID.Click +=  async delegate 
{
    details.Text=" ";
    Guid x = new Guid("33F8A8D5-0DF2-47A0-9C79-002351A95F88");
    state OStateUserID =(state) await obj.GetStateByUserId(x.ToString());
    details.Text = OStateUserID.name + "\n" + OStateUserID.population);
};

GetStateByUserId() method returns an object of class State.

It runs asynchronously. After completing operation, I'd like to assign the name and population to the TextView details.

How can i use RunOnUIThread() in this case?

like image 357
Suraj Avatar asked Dec 23 '13 10:12

Suraj


2 Answers

I'm not sure how you could have missed it, since you have the proper function name. Anyway, you could do it with lambda expression :

Activity.RunOnUiThread(() => {
    details.Text = OStateUserID.name + "\n" + OStateUserID.population;
});

Or you could create a method for it

Activity.RunOnUiThread(Action);

private void Action() 
{ 
    details.Text = OStateUserID.name + "\n" + OStateUserID.population;
}

In the latter case, you would have to store variables in private fields if it wasn't the case already. In the first case, it will work if the variables are in the same scope as the RunOnUiThread call.

like image 123
ForceMagic Avatar answered Nov 01 '22 22:11

ForceMagic


You don't need to.

In this code you posted:

bStateuserID.Click +=  async delegate 
{
    details.Text=" ";
    Guid x = new Guid("33F8A8D5-0DF2-47A0-9C79-002351A95F88");
    state OStateUserID =(state) await obj.GetStateByUserId(x.ToString());
    details.Text = OStateUserID.name + "\n" + OStateUserID.population);
};

The line

details.Text = OStateUserID.name + "\n" + OStateUserID.population);

is already running on the UI thread.

I have an async intro on my blog that explains this behavior.

like image 22
Stephen Cleary Avatar answered Nov 01 '22 23:11

Stephen Cleary