尝试同步SyncTable时,Xamarin应用程序崩溃

时间:2016-12-15 22:57:34

标签: c# azure xamarin azure-storage

我使用xamarin和azure移动服务制作应用。我正在尝试添加离线同步功能,但我陷入困境。我有一个看起来像这样的服务

class AzureService
    {

        public MobileServiceClient Client;

        AuthHandler authHandler;
        IMobileServiceTable<Subscription> subscriptionTable;
        IMobileServiceSyncTable<ShopItem> shopItemTable;
        IMobileServiceSyncTable<ContraceptionCenter> contraceptionCenterTable;
        IMobileServiceTable<Member> memberTable;
        const string offlineDbPath = @"localstore.db";


        static AzureService defaultInstance = new AzureService();
        private AzureService()
        {
            this.authHandler = new AuthHandler();
            this.Client = new MobileServiceClient(Constants.ApplicationURL, authHandler);

            if (!string.IsNullOrWhiteSpace(Settings.AuthToken) && !string.IsNullOrWhiteSpace(Settings.UserId))
            {
                Client.CurrentUser = new MobileServiceUser(Settings.UserId);
                Client.CurrentUser.MobileServiceAuthenticationToken = Settings.AuthToken;
            }

            authHandler.Client = Client;

            //local sync table definitions
            //var path = "syncstore.db";
            //path = Path.Combine(MobileServiceClient.DefaultDatabasePath, path);

            //setup our local sqlite store and intialize our table
            var store = new MobileServiceSQLiteStore(offlineDbPath);

            //Define sync table
            store.DefineTable<ShopItem>();
            store.DefineTable<ContraceptionCenter>();

            //Initialize file sync context
            //Client.InitializeFileSyncContext(new ShopItemFileSyncHandler(this), store);

            //Initialize SyncContext
            this.Client.SyncContext.InitializeAsync(store);

            //Tables
            contraceptionCenterTable = Client.GetSyncTable<ContraceptionCenter>();
            subscriptionTable = Client.GetTable<Subscription>();
            shopItemTable = Client.GetSyncTable<ShopItem>();
            memberTable = Client.GetTable<Member>();

        }

        public static AzureService defaultManager
        {
            get { return defaultInstance; }
            set { defaultInstance = value; }
        }

        public MobileServiceClient CurrentClient
        {
            get { return Client; }
        }
 public async Task<IEnumerable<ContraceptionCenter>> GetContraceptionCenters()
        {
            try
            {
                await this.SyncContraceptionCenters();
                return await contraceptionCenterTable.ToEnumerableAsync();
            }
            catch (MobileServiceInvalidOperationException msioe)
            {
                Debug.WriteLine(@"Invalid sync operation: {0}", msioe.Message);
            }
            catch (Exception e)
            {
                Debug.WriteLine(@"Sync error: {0}", e.Message);
            }
            return null;



        }
public async Task SyncContraceptionCenters()
        {

            ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;

            try
            {
                //await this.Client.SyncContext.PushAsync();

                await this.contraceptionCenterTable.PullAsync(
                    //The first parameter is a query name that is used internally by the client SDK to implement incremental sync.
                    //Use a different query name for each unique query in your program
                    "allContraceptionCenters",
                    this.contraceptionCenterTable.CreateQuery());
            }
            catch (MobileServicePushFailedException exc)
            {
                if (exc.PushResult != null)
                {
                    syncErrors = exc.PushResult.Errors;
                }
            }

            // Simple error/conflict handling. A real application would handle the various errors like network conditions,
            // server conflicts and others via the IMobileServiceSyncHandler.
            if (syncErrors != null)
            {
                foreach (var error in syncErrors)
                {
                    if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null)
                    {
                        //Update failed, reverting to server's copy.
                        await error.CancelAndUpdateItemAsync(error.Result);
                    }
                    else
                    {
                        // Discard local change.
                        await error.CancelAndDiscardItemAsync();
                    }

                    Debug.WriteLine(@"Error executing sync operation. Item: {0} ({1}). Operation discarded.", error.TableName, error.Item["id"]);
                }
            }
        }

我收到此错误: System.NullReferenceException: Object reference not set to an instance of an object.运行SyncContraceptionCenters()时。据我所知,我在我的服务中复制了coffeeItems例子但是我被卡住了。

1 个答案:

答案 0 :(得分:0)

我想我找到了解决方案。问题在于表格的同步方式。

同时调用SyncContraceptionCenters()SyncShop() shopItemtable.PullAsynccontraceptionTable.PullAsync同时发生。这显然很糟糕。所以,但是将它们放在相同的方法中并等待它们,它们会分开运行,并且它们按预期工作。