Edit and sync features with feature service

View on GitHubSample viewer app

Synchronize offline edits with a feature service.

Image of edit and sync features with feature service

Use case

A survey worker who works in an area without an internet connection could take a geodatabase of survey features offline at their office, make edits and add new features to the offline geodatabase in the field, and sync the updates with the online feature service after returning to the office.

How to use the sample

Pan and zoom into the desired area, making sure the area you want to take offline is within the current extent of the map view. Tap on the "Generate Geodatabase" button to take the area offline. When complete, the map will update with a red outline around the offline area. To edit features, tap to select a feature, and tap again anywhere else on the map to move the selected feature to the tapped location. To sync the edits with the feature service, click the "Sync geodatabase" button.

How it works

  1. Create a GeodatabaseSyncTask from a URL to a feature service.
  2. Use createDefaultGenerateGeodatabaseParameters() on the geodatabase sync task to create GenerateGeodatabaseParameters, passing in an Envelope extent as the parameter.
  3. Create a GenerateGeodatabaseJob from the GeodatabaseSyncTask using createGenerateGeodatabaseJob(...) passing in parameters and a path to the local geodatabase.
  4. Start the job and get the result Geodatabase.
  5. Load the geodatabase and get its feature tables. Create feature layers from the feature tables and add them to the map's operational layers collection.
  6. Create SyncGeodatabaseParameters and set the sync direction.
  7. Create a SyncGeodatabaseJob from GeodatabaseSyncTask using .createSyncGeodatabaseJob(...) passing in the parameters and geodatabase as arguments.
  8. Start the sync job to synchronize the edits with syncGeodatabaseJob.start().

Relevant API

  • FeatureLayer
  • FeatureTable
  • GenerateGeodatabaseJob
  • GenerateGeodatabaseParameters
  • GeodatabaseSyncTask
  • SyncGeodatabaseJob
  • SyncGeodatabaseParameters
  • SyncLayerOption

Additional information

This sample uses the GeoView-Compose Toolkit module to be able to implement a composable MapView.

Tags

feature service, geodatabase, geoview-compose, offline, synchronize

Sample Code

MapViewModel.ktMapViewModel.ktMainActivity.ktMainScreen.kt
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/* Copyright 2024 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.esri.arcgismaps.sample.editandsyncfeatureswithfeatureservice.components

import android.app.Application
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.dp
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.arcgismaps.Color
import com.arcgismaps.data.Feature
import com.arcgismaps.data.Geodatabase
import com.arcgismaps.geometry.Envelope
import com.arcgismaps.geometry.Point
import com.arcgismaps.geometry.Polygon
import com.arcgismaps.geometry.SpatialReference
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.layers.FeatureLayer
import com.arcgismaps.mapping.symbology.SimpleLineSymbol
import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.ScreenCoordinate
import com.arcgismaps.mapping.view.SingleTapConfirmedEvent
import com.arcgismaps.tasks.geodatabase.GenerateGeodatabaseJob
import com.arcgismaps.tasks.geodatabase.GeodatabaseSyncTask
import com.arcgismaps.tasks.geodatabase.SyncDirection
import com.arcgismaps.tasks.geodatabase.SyncGeodatabaseJob
import com.arcgismaps.tasks.geodatabase.SyncGeodatabaseParameters
import com.arcgismaps.tasks.geodatabase.SyncLayerOption
import com.arcgismaps.toolkit.geoviewcompose.MapViewProxy
import com.esri.arcgismaps.sample.editandsyncfeatureswithfeatureservice.R
import com.esri.arcgismaps.sample.sampleslib.components.MessageDialogViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class MapViewModel(private val application: Application) : AndroidViewModel(application) {

    // Create a red boundary line showing the filtered map extents for the features
    private val boundarySymbol = SimpleLineSymbol(
        style = SimpleLineSymbolStyle.Solid,
        color = Color.red,
        width = 5f
    )

    // Create graphic overlay to add graphics
    val graphicsOverlay = GraphicsOverlay()

    // Create a ViewModel to handle dialog interactions.
    val messageDialogVM = MessageDialogViewModel()

    // Create a streets basemap layer
    val map = ArcGISMap(BasemapStyle.ArcGISStreets).apply {

        // Set the max map extents to that of the feature service representing san fransisco area
        maxExtent = Envelope(
            xMin = -1.3641320770825155E7,
            yMin = 4524676.716562641,
            xMax = -1.3617221998199359E7,
            yMax = 4567228.901189857,
            spatialReference = SpatialReference.webMercator()
        )
    }

    // Create a MapViewProxy to handle MapView operations
    val mapViewProxy = MapViewProxy()

    // Keep track of action button text through a string state
    var actionButtonText by mutableStateOf(application.getString(R.string.generate_button_text))
        private set

    // Create a button to keep track of action button enablement status
    var isActionButtonEnabled by mutableStateOf(false)
        private set

    // Determinate GenerateGeodatabase job progress loading dialog visibility state
    var showGenerateGeodatabaseJobProgressDialog by mutableStateOf(false)
        private set

    // Determine GenerateGeodatabase job progress percentage
    var generateGeodatabaseJobProgress by mutableIntStateOf(0)
        private set

    // Determinate SyncGeodatabase job progress loading dialog visibility state
    var showSyncGeodatabaseJobProgressDialog by mutableStateOf(false)
        private set

    // Determine SyncGeodatabase job progress percentage
    var syncGeodatabaseJobProgress by mutableIntStateOf(0)
        private set

    // Create a local file path to the geodatabase
    private val geodatabaseFilePath by lazy {
        application.getExternalFilesDir(null)?.path + File.separator + application.getString(R.string.geodatabase_file)
    }

    // Create a geodatabase sync task with the feature service url
    // This feature service illustrates a collection schema for wildfire information in the san fransisco area
    private val geodatabaseSyncTask by lazy { GeodatabaseSyncTask(application.getString(R.string.feature_server_url)) }

    // Current edit state to track when feature edits can be performed on the geodatabase
    private var geodatabaseEditState = GeodatabaseEditState.NOT_READY

    // List of selected features to edit
    private var selectedFeatures = mutableListOf<Feature>()

    // Geodatabase instance that is loaded
    private var geodatabase: Geodatabase? = null

    // Job used to generate geodatabase
    private var generateGeodatabaseJob: GenerateGeodatabaseJob? = null

    // Job used to sync geodatabase
    private var syncGeodatabaseJob: SyncGeodatabaseJob? = null

    // Initialize polygon to null as starting value and emit its state changes
    var polygon: Polygon? = null

    // Create a SnackbarHostState to handle successful operation messages
    val snackbarHostState = SnackbarHostState()

    init {
        viewModelScope.launch(Dispatchers.Main) {
            // If map load failed, show the error and return
            map.load().onFailure {
                return@launch messageDialogVM.showMessageDialog(
                    title = "Unable to load map",
                    description = it.message.toString()
                )
            }
            // If the geodatabase sync from feature service fails to load, show the error and return
            geodatabaseSyncTask.load().onFailure {
                return@launch messageDialogVM.showMessageDialog(
                    title = "Failed to fetch geodatabase metadata",
                    description = it.message.toString()
                )
            }
            // Enable the sync button since the task is now loaded
            isActionButtonEnabled = true
        }
    }

    /**
     * Collect and handle map touch events
     */
    fun onSingleTapConfirmed(event: SingleTapConfirmedEvent) {
        // Receive the point in map coordinates where the user tapped,
        event.mapPoint?.let { point ->
            // Perform an action based on the current edit state
            when (geodatabaseEditState) {
                GeodatabaseEditState.NOT_READY -> {
                    // If not ready, show info message
                    messageDialogVM.showMessageDialog("Can't edit yet. The geodatabase hasn't been generated!")
                }

                GeodatabaseEditState.EDITING -> {
                    // If edits have been performed, move the selected features
                    moveSelectedFeatures(point)
                }

                GeodatabaseEditState.READY -> {
                    // If no edits are performed but geodatabase is ready, select the tapped features
                    selectFeatures(screenCoordinate = event.screenCoordinate)
                }
            }
        }
    }

    /**
     * Handle button click events
     */
    fun onClickActionButton() {
        when (geodatabaseEditState) {
            // If geodatabase hasn't been generated
            GeodatabaseEditState.NOT_READY -> {
                polygon?.extent?.let { polygon -> generateGeodatabase(extents = polygon) }
            }

            // Cannot sync in the middle of edit
            GeodatabaseEditState.EDITING ->
                showSuccessMessage("Features are currently being edited!")

            // If the edits have been completed
            GeodatabaseEditState.READY -> syncGeodatabase()
        }
    }

    /**
     * Starts a [GeodatabaseSyncTask] with the given [ArcGISMap] and [Envelope.extent],
     * runs a GenerateGeodatabaseJob and saves the geodatabase file into local storage
     */
    private fun generateGeodatabase(extents: Envelope) {
        // Create a boundary representing the extents selected
        val boundary = Graphic(
            geometry = extents,
            symbol = boundarySymbol
        )

        // Add this boundary to the graphics overlay
        graphicsOverlay.graphics.add(boundary)

        with(viewModelScope) {

            launch(Dispatchers.IO) {
                // Create generateGeodatabase parameters for the selected extents
                val defaultParameters =
                    geodatabaseSyncTask.createDefaultGenerateGeodatabaseParameters(extents)
                        .getOrElse {
                            // Show the error and return if the sync task fails
                            return@launch messageDialogVM.showMessageDialog(title = "Error creating geodatabase parameters")
                        }.apply {
                            // Set return attachments option to false
                            // Indicates if any attachments are added to the geodatabase from the feature service
                            returnAttachments = false
                        }

                // Create a generateGeodatabase job
                generateGeodatabaseJob = geodatabaseSyncTask.createGenerateGeodatabaseJob(
                    parameters = defaultParameters,
                    pathToGeodatabaseFile = geodatabaseFilePath
                )

                generateGeodatabaseJob?.let { generateGeodatabaseJob ->

                    // Show the dialog of generateGeodatabase Job
                    showGenerateGeodatabaseJobProgressDialog = true

                    // Create a flow-collection for the job's progress
                    launch{
                        generateGeodatabaseJob.progress.collect { progress ->
                            // Display the current job's progress value
                            generateGeodatabaseJobProgress = progress
                        }
                    }

                    // Start the job
                    generateGeodatabaseJob.start()

                    // If the job completed successfully, get the geodatabase from the result
                    geodatabase = generateGeodatabaseJob.result().getOrElse {
                        // Show an error and return if job failed
                        messageDialogVM.showMessageDialog("Error fetching geodatabase: ${it.message}")
                        // Dismiss the dialog
                        showGenerateGeodatabaseJobProgressDialog = false
                        // Clear any drawn boundary
                        graphicsOverlay.graphics.clear()

                        return@launch
                    }

                    // Load and display the geodatabase
                    loadGeodatabase()

                    // Dismiss the dialog
                    showGenerateGeodatabaseJobProgressDialog = false
                }
            }
        }
    }

    /**
     * Loads the [Geodatabase] and renders the feature layers on to the [ArcGISMap]
     */
    private suspend fun loadGeodatabase() {
        // Load the geodatabase
        geodatabase?.let { geodatabase ->
            geodatabase.load().onFailure {
                // If the load failed, show the error and return
                return messageDialogVM.showMessageDialog("Error loading geodatabase")
            }

            // Add all of the geodatabase feature tables to the map as feature layers
            map.operationalLayers.addAll(geodatabase.featureTables.map { featureTable ->
                FeatureLayer.createWithFeatureTable(featureTable)
            })
        }

        // Update the sync button text to show a sync action
        actionButtonText = getApplication<Application>().getString(R.string.sync_button_text)

        // Update the geodatabase edit state to indicate its ready for edits and syncs
        geodatabaseEditState = GeodatabaseEditState.READY

    }

    /**
     * Syncs changes made on either the local [Geodatabase] or web service geodatabase with each other
     */
    private fun syncGeodatabase() {
        // Create parameters for the geodatabase sync task
        val syncGeodatabaseParameters = SyncGeodatabaseParameters().apply {
            geodatabaseSyncDirection = SyncDirection.Bidirectional
            shouldRollbackOnFailure = false
        }

        geodatabase?.let { geodatabase ->
            // Set synchronization option for each layer in the geodatabase we want to synchronize
            syncGeodatabaseParameters.layerOptions.addAll(geodatabase.featureTables.map { featureTable ->
                // Create a new sync layer option with the layer id of the feature table
                SyncLayerOption(featureTable.serviceLayerId)
            })

            syncGeodatabaseJob = geodatabaseSyncTask.createSyncGeodatabaseJob(
                parameters = syncGeodatabaseParameters, geodatabase = geodatabase
            )

            syncGeodatabaseJob?.let { syncGeodatabaseJob ->

                // Show the dialog
                showSyncGeodatabaseJobProgressDialog = true

                // Start the job and wait for Job result
                syncGeodatabaseJob.start()

                with(viewModelScope) {

                    // Create the SyncGeodatabaseJob using the parameters and the geodatabase
                    launch(Dispatchers.IO) {
                        syncGeodatabaseJob.result().onSuccess {
                            showSuccessMessage("Sync Complete")
                        }
                            .onFailure { messageDialogVM.showMessageDialog("Database did not sync correctly") }

                        // Dismiss the dialog
                        showSyncGeodatabaseJobProgressDialog = false

                        // Set the edit state to indicate geodatabase is ready for edits
                        geodatabaseEditState = GeodatabaseEditState.READY
                    }
                    // Create a flow-collection for the job's progress
                    launch(Dispatchers.Main) {
                        syncGeodatabaseJob.progress.collect { progress ->
                            // Display the current job's progress value
                            syncGeodatabaseJobProgress = progress
                        }
                    }
                }
            }
        }
    }

    /**
     * Queries and selects features on FeatureLayers at the tapped [ScreenCoordinate] on the [ArcGISMap]
     */
    private fun selectFeatures(screenCoordinate: ScreenCoordinate) {
        // Set the current edit state to editing
        geodatabaseEditState = GeodatabaseEditState.EDITING

        // Create a new coroutine to handle the selection
        viewModelScope.launch(Dispatchers.Main) {
            // Flag to indicate if any features were selected
            var featuresSelected = false

            // For each feature layer in the map
            map.operationalLayers.filterIsInstance<FeatureLayer>().forEach { featureLayer ->

                // Identify the layer at the tapped screenCoordinate
                val identifyLayerResult = mapViewProxy.identify(
                    layer = featureLayer,
                    screenCoordinate = screenCoordinate,
                    tolerance = 12.dp,
                    returnPopupsOnly = false
                ).getOrElse {
                    // Show an error and return if the identifyLayer operation failed
                    return@launch messageDialogVM.showMessageDialog(
                        title = "Unable to identify selected layer",
                        description = it.message.toString()
                    )
                }

                // Get the identified features in the feature layer
                val identifiedFeatures = identifyLayerResult.geoElements.filterIsInstance<Feature>()
                if (identifiedFeatures.isNotEmpty()) {
                    // Select the features on the map
                    featureLayer.selectFeatures(identifiedFeatures)
                    // Add the identified features to the selectedFeatures list
                    selectedFeatures.addAll(identifiedFeatures)
                    // Set the flag to true
                    featuresSelected = true
                }
            }

            // If no features were selected
            if (!featuresSelected) {
                // Show a message
                showSuccessMessage("No features found at the tapped location!")

                // Reset the current edit state to ready
                geodatabaseEditState = GeodatabaseEditState.READY
            }
        }
    }

    /**
     * Moves the selected features to a new [Point] on the [ArcGISMap]
     */
    private fun moveSelectedFeatures(point: Point) {
        // Create a new coroutine to move the features
        selectedFeatures.forEach { feature ->
            // Update each selected features geometry
            feature.geometry = point

            // Update the feature
            viewModelScope.launch(Dispatchers.IO) {
                feature.featureTable?.updateFeature(feature)
            }
        }

        // Clear the list of selected features once all have been updated
        selectedFeatures.clear()

        // Clear any selected features on the map
        map.operationalLayers.filterIsInstance<FeatureLayer>().forEach { featureLayer ->
            featureLayer.clearSelection()
        }

        // Set the current edit state to ready
        geodatabaseEditState = GeodatabaseEditState.READY
    }

    fun cancelGenerateGeodatabaseJob() {
        viewModelScope.launch(Dispatchers.IO) {
            generateGeodatabaseJob?.cancel()
        }
    }

    fun cancelSyncGeodatabaseJob() {
        viewModelScope.launch(Dispatchers.IO) {
            syncGeodatabaseJob?.cancel()
        }
    }

    private fun showSuccessMessage(message: String) {
        viewModelScope.launch(Dispatchers.Main) {
            snackbarHostState.showSnackbar(message)
        }
    }

    /**
     * Enum state class to track editing of features
     */
    enum class GeodatabaseEditState {
        NOT_READY,  // geodatabase has not yet been generated
        EDITING,  // a feature is in the process of being moved
        READY, // the geodatabase is ready for synchronization or further edits
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.