In my Xamarin forms App, I am trying to get data from Azure cosmos db and display it in my collectionView.
I successfully get data from Cosmos db but when I am trying to display by searching I have duplicated data in my collectionview
Here is how I get data from cosmos db :
public async static Task<List<MyUser>> GetUserList(string MyFriendName)
{
MyFriendName = MyFriendName.ToLower();
List<MyUser> UsersList = new List<MyUser>();
string sql = "SELECT TOP 25 * FROM " + collectionId + " u WHERE CONTAINS(LOWER(u.username),'"+ MyFriendName+ "') ";
QueryDefinition query = new QueryDefinition(sql);
using (FeedIterator<MyUser> iterator = container.GetItemQueryIterator<MyUser>(
queryDefinition: query,
requestOptions: new QueryRequestOptions()
{
MaxItemCount = -1,
}))
{
while (iterator.HasMoreResults)
{
FeedResponse<MyUser> result = await iterator.ReadNextAsync();
UsersList.AddRange(result.Resource);
}
return UsersList;
}
}
Here is how I prepare to show the data from cosmos db:
ObservableRangeCollection<MyCommunityModel> datasource;
MyCommunityModel CommunityUser;
async Task<ObservableRangeCollection<MyCommunityModel>> OnPersonSearch(string MyFriendName)
{
datasource.Clear();
//get data from cosmos db function
var UsersList = await UserManager.GetUserList(MyFriendName);
foreach (var u in UsersList)
{
CommunityUser = new MyCommunityModel();
CommunityUser.MyId = u.MyId;
CommunityUser.Username = u.Username;
datasource.Add(CommunityUser);
}
return datasource;
}
//Here is how I show data
void OnSearchCommunity(System.Object sender, Xamarin.Forms.TextChangedEventArgs e)
{
// show data
Device.BeginInvokeOnMainThread(async () =>
{
MyCommunityCollectionList.ItemSizingStrategy = ItemSizingStrategy.MeasureFirstItem;
//display data here
MyCommunityCollectionList.ItemsSource = await OnPersonSearch(searchTerm);
});
2
Answers
create api and call it
datasource.Clear();
. When it stops there, continue. Does it get there a second time, before the data is displayed? That’s the only way I can see data getting doubled.If two calls interleave: clear – await – clear – await – fill – fill, the result after second call would be doubled data.
var UsersList = await …
line. This avoids possibility of second call coming between clear and filling of data.