【问题标题】:Do I need to call MobileServiceSyncContext.initialize in each Activity?我需要在每个 Activity 中调用 MobileServiceSyncContext.initialize 吗?
【发布时间】:2017-07-24 00:02:44
【问题描述】:

使用 Azure 移动服务 Android SDK 进行离线同步时,是否需要在需要访问某个表的每个 Activity 中调用 MobileServiceSyncContext.initialize?如果是这样,为什么?本地数据库不应该只初始化一次吗?我做错了吗?每次调用方法 initialize 时,它​​都会尝试再次创建所有表,即使它们已经存在,对我来说也不是很好。有什么办法可以只初始化一次syncContext,或者至少避免每次初始化syncContext时框架运行sql脚本来创建表?

谢谢!

PS:我是 Android 开发的新手,请善待 :)

【问题讨论】:

    标签: android azure-mobile-services azure-android-sdk


    【解决方案1】:

    根据您的描述,根据我的理解,您似乎已经按照下面的一些文档和示例使用离线同步数据功能创建了您的应用程序。

    1. 博客:Offline support in the Azure Mobile Services Android SDK
    2. 样品:https://github.com/Azure/mobile-services-samples/blob/master/TodoOffline/Android/blog20140807/app/src/main/java/com/example/blog20140807/ToDoActivity.java

    根据我的经验并根据适用于 Android 的 Azure 移动应用 SDK 的 javadocs,我认为您可以尝试使用下面的方法 MobileServiceSyncContext.isInitalized 添加代码以检查 MobileServiceSyncContext 初始化状态,基于 @ 987654325@如下,避免重复初始化操作。

    MobileServiceSyncContext syncContext = mClient.getSyncContext();
    
    if(syncContext.isInitalized()) {
    
        Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
        tableDefinition.put("id", ColumnDataType.String);
        tableDefinition.put("text", ColumnDataType.String);
        tableDefinition.put("complete", ColumnDataType.Boolean);
        tableDefinition.put("__version", ColumnDataType.String);
    
        localStore.defineTable("ToDoItem", tableDefinition);
        syncContext.initialize(localStore, handler).get();
    }
    

    【讨论】:

      【解决方案2】:

      也许以下细节可以帮助您找到解决方案。对于 MobileServiceClient,您需要应用程序的上下文,而不是每个 Activity 的上下文。因此,您不必为每个 Activity 初始化 syncContext。可能您可以使用 Gson() 将其保存在 SharedPreferences 中。

      MobileServiceClient mClient = new MobileServiceClient(
      "<MobileAppUrl>",       // Replace with the Site URL
      this);                  // Your application Context
      

      来源:[1]:https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-android-how-to-use-client-library

      【讨论】:

        猜你喜欢
        • 2013-01-28
        • 1970-01-01
        • 2010-12-07
        • 2011-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        相关资源
        最近更新 更多