I'm learning C# and am trying to make a simple application that continuously updates a listview (as new information comes in).
Naturally, I assumed that I could create an async thread to run in perpetuity that would continuously update the listview.
I was able to do this conceptually by creating a threaded function and running it (shown here https://replit.com/@JacksonEnnis4/Def#main.cs).
I tried duplicating this methodology in Xamarin for Android, and got an error that the GUI could only be updated on the "Main Thread".
I saw some people mentioning using RunOnUiThread and a Runnable to succeed in asynchronously updating the UI (android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi), however when I try to implement a C# version of the solution, I get the error
Line 54 "There is no argument given that corresponds to the required formal parameter 'handler' of Runnable.Runnable(Action)"
I assume that I've missed something, or I have some sort of fundamental misunderstanding of how you would want to update the ui continuously. If anyone could help me, it would mean the world.
Thanks!
MainActivity.cs
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using AndroidX.AppCompat.App;
using Java.Lang;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Organized_Chaos
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private ArrayAdapter adapter;
private ListView listView;
private List<string> testData;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
ObservableCollection<string> person;
//This basically just loads in the TEST data
testData = new List<string>();
testData.Add("Task 1");
testData.Add("Task 2");
testData.Add("Task 25");
testData.Add("Task 26");
//Creates an adapter for the data
adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, testData);
listView = FindViewById<ListView>(Resource.Id.taskListView);
//Sets the adapter to the listview
listView.SetAdapter(adapter);
ThreadPool.QueueUserWorkItem(o => SlowMethod());
}
[System.Obsolete]
private void SlowMethod()
{
int counter = 0;
System.Threading.Thread.Sleep(1000);
testData[0] = counter.ToString();
counter += 1;
RunOnUiThread(new Runnable()
{
@Override
public void run()
{
//Do stuffs
}
});
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}