Reputation: 423
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:
Upvotes: 0
Views: 1824
Reputation: 9084
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. : )
Upvotes: 1