简体   繁体   中英

Xamarin.Android how to auto update RecyclerView

Following this article I created a simple application that displays a list. The list I get from a web service (.asmx web service).

I want to auto update RecyclerView every 5 seconds and I have no idea how to do it.

In WinForms I would have used the Timer component, but I don't know how this works in Xamarin.

MainActivity.cs

[Activity(Label = "CibMonitor", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : AppCompatActivity
    {
        RecyclerView recyclerView;
        RecyclerView.LayoutManager layoutManager;
        ConnectionItemsAdapter adapter;
        ConnectionItem[] connectionItems;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            var ci = new ConnectionItem();

            //Get list from web service
            connectionItems = ci.GetList().ToArray();

            //Setup RecyclerView
            adapter = new ConnectionItemsAdapter(this, connectionItems);

            recyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView);

            recyclerView.SetAdapter(adapter);

            ChangedData();
        }
    }

Update I created new method in activity class as York Shen suggested

void ChangedData()
{
    Task.Delay(5000).ContinueWith(t =>
    {
        var newData = ConnectionItem.GetList();
        adapter.RefreshItems(newData);
        ChangedData();
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

This is my update method in adapter class:

public void RefreshItems(List<ConnectionItem> newItems)
{
    items.Clear();
    items = newItems;
    NotifyDataSetChanged();
}

my app stops working, no exception only this message: 在此处输入图片说明

You can create a Task which can help you update recyclerView every 5 seconds:

void ChangedData()
    {
        Task.Delay(5000).ContinueWith(t =>
        {
           adapter.NotifyDataSetChanged();
           ChangedData();//This is for repeate every 5s.
        }, TaskScheduler.FromCurrentSynchronizationContext());
    }

EDIT:

Sorry for late reply, calling the ChangedData() in Task.Delay() can resolve the repeate problem. You can invoke the ChangedData() in OnCreate() method. Hope this can help you. : )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM