albilaga
albilaga

Reputation: 439

ListAdapter On Xamarin for Android

I create ListView using ListAdapter on Android Xamarin. I am using it on Activity which extend ListActivity

This is my code

ListAdapter = new ArrayAdapter<string> (
    this, 
    Android.Resource.Layout.SimpleListItem1, 
    new string[] { "tes1", "tes2", "tes3" }
);

When I put that in Oncreate() it shown. But I do need that ListAdapter to bind some data when some event (says download completed event) so I put it in a method which I call after download data completed but why ListAdapter can't be shown? My ListView become empty. I am using the same code as above.

this is my OnCreate method

base.OnCreate(bundle);

            _DataTopStories = new TopStoriesViewModel();
            _DataService = new DataService();


            SetContentView(Resource.Layout.ListTopStoriesLayout);

            _DataService.GetTopStories();
            _DataService.DownloadCompleted += _DataService_DownloadCompleted;

this is Download Event Completed

void _DataService_DownloadCompleted(object sender, EventArgs e)
        {
            var raw = ((DownloadEventArgs)e).ResultDownload;
            if(raw!=null)
            {
                _DataTopStories = JsonConvert.DeserializeObject<TopStoriesViewModel>(raw);
                CreateList();
                Log.Info("ds", "download completed");
            }
        }

this is CreateList() method

private void CreateList()
        {
            Log.Info("ds", "list");
            ListAdapter = new ArrayAdapter<string>(Application.Context, Android.Resource.Layout.SimpleListItem1, new string[] { "tes4", "tes52", "tes6" });
            Log.Info("ds", "set adapter");

        }

And in Android logcat "set adapter" will not shown. It looks stopped on ListAdapter.

Upvotes: 0

Views: 1846

Answers (1)

albilaga
albilaga

Reputation: 439

Ok. Found my solution. To update ListAdapter I need to run it on UI Thread so this is my new Download Completed Event

void _DataService_DownloadCompleted(object sender, EventArgs e)
        {
            var raw = ((DownloadEventArgs)e).ResultDownload;
            if(raw!=null)
            {
                _DataTopStories = JsonConvert.DeserializeObject<TopStoriesViewModel>(raw);
                RunOnUiThread(() => CreateList());
                //CreateList();
                Log.Info("ds", "download completed");
            }
        }

Upvotes: 1

Related Questions