-1

Mypageviewmodel.cs

using MonkeyCache.FileStore;
using MvvmHelpers.Commands;
using Newtonsoft.Json;
using Refit;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using UsersApp.Model;
using UsersApp.Services;
using Xamarin.Essentials;

namespace UsersApp.Viewmodel
{
    public class Mypageviewmodel : INotifyPropertyChanged
    {
        public IUsers Usercache = new Userscache();


        public ICommand Getusers { get; set; }
        public ObservableCollection<Users> users { get; set; }

        public Mypageviewmodel()
        {
            Getusers = new Command(async () => await getusers());
            Getusers.Execute(null);
        }

        async Task getusers()
        {

            var result = await Userscache.GetUsersAsync();
            if (result != null)
                users = new ObservableCollection<Users>(result);

        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Userscache.cs

using MonkeyCache.FileStore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using UsersApp.Model;
using Xamarin.Essentials;

namespace UsersApp.Services
{
    public class Userscache : IUsers
    {
        const string url = "https://jsonplaceholder.typicode.com";

        public Userscache()
        {
            Barrel.ApplicationId = "UsersApp";
        }
        public async Task<IEnumerable<Users>> GetUsersAsync()
        {
            try
            {
                if (Connectivity.NetworkAccess != NetworkAccess.Internet &&
                    !Barrel.Current.IsExpired(key: url))
                {
                    await Task.Yield();
                    return Barrel.Current.Get<IEnumerable<Users>>(key: url);
                }

                var client = new HttpClient();
                var json = await client.GetStringAsync(url);

                var getusers = JsonConvert.DeserializeObject<IEnumerable<Users>>(json);

                Barrel.Current.Add(key: url, data: getusers, expireIn: TimeSpan.FromDays(1));

                return getusers;
            }
            catch (Exception ex)
            {
                //Debug.WriteLine($"Unable to get information from server {ex}");
                //throw ex;
            }
            return null;
        }
    }
}

IUsers.cs

using Refit;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using UsersApp.Model;

namespace UsersApp.Services
{
    [Headers("Content-Type: application/json")]
    public interface IUsers
    {
        //[Get("/users")]
        Task<IEnumerable<Users>> GetUsersAsync();
    }
}

Mypage.xaml.cs

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UsersApp.Viewmodel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace UsersApp.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Mypage : ContentPage
    {
        public Mypage()
        {
            InitializeComponent();
            BindingContext = new Mypageviewmodel();
        }

    }
}

Mypage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:viewmodels="clr-namespace:UsersApp.Viewmodel"
             x:Class="UsersApp.Views.Mypage">
    <ContentPage.BindingContext>
        <viewmodels:Mypageviewmodel/>
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout Padding="40">
            <Button Text="Get Users" Command="{Binding Getusers}"
                BackgroundColor="Black" TextColor="White" HorizontalOptions="FillAndExpand"/>
            <ListView x:Name="UsersList">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding name}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

I used refit first to get the data back from the typicode.json API but I have to do caching also so I tried to follow https://xamgirl.com/improving-the-ux-of-a-xamarin-forms-application-by-caching-data/ this article. But I am stuck now I tried to use static but then there are more errors coming. Also, can someone tell me how to upload this data into my local storage (creating using SQLite). I am new to xamarin*

2 Answers2

0

public IUsers Usercache = new Userscache();

this was the issue

public IUsers Userscache = new Userscache();

its not showing any error know but after building the app in emulator when i click get users it doesn't show anything

is my ICommand is wrong or is there any issue with my xaml code and bindings

0

You are exeuting the command before the UsersCache get's a value

Bandi Tóth
  • 167
  • 1
  • 9
  • how to correct that? before i was using the clicked method in my button but now i am doing it as MVVM so i have to get rid of that async void method and use command in my viewmodel – Navflash Jul 12 '21 at 12:56