I am trying to update a LinearLayout from a class outside the activity and doing so gives me the following:exception
Android.Util.AndroidRuntimeException:"Only the original thread that created a view hierarchy can touch its views."
This is what I have:
The first thing I do is launch a thread that every few seconds will check that I have a connection to the server.
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
context = this;
Task.Run( () => ComprobarConexion());
}
This is the method I use:
protected static void ComprobarEstado()
{
while(true){
TestearConexion();
Thread.Sleep(segundos * 1000);
}
}
And here I check that the connection is working:
public static void TestearConexion()
{
try{
WebService.Test();
}catch(Exception ex){ //En la realidad tengo completadas distintas excepciones.
LayoutInflater lDesconexion = (LayoutInflater)MainActivity.context.GetSystemService(Context.LayoutInflaterService);
View vDesconexion = lDesconexion.Inflate(Resource.Layout.layout_disconected, null, false);
MainActivity.contenidoPrincipal.RemoveAllViews();
MainActivity.contenidoPrincipal.AddView(vDesconexion);
}
}
The exception I get when trying to modify MainActivity.contenidoPrincipal
.
How can I show the connection failure?
First, you must understand how a Task and a Thread work to simulate asynchronous execution.
Not recommended: Thread.Sleep
Recommended: Task.Delay
Difference in memory between Thread.Sleep and Task.Delay:
Understood the difference, here we go with the solution:
Solution:
Recommendation: if you are going to use a method to check a WebService connection you should create a utility Singleton class and not attach it to an Activity. Activities tend to take on a lot of tasks and your code can get polluted with useful code.
References and examples: