Edit with branch versioning

View on GitHub
Sample viewer app

Create, query and edit a specific server version using service geodatabase.

Image of edit with branch versioning

Use case

Workflows often progress in discrete stages, with each stage requiring the allocation of a different set of resources and business rules. Typically, each stage in the overall process represents a single unit of work, such as a work order or job. To manage these, you can create a separate, isolated version and modify it. Once this work is complete, you can integrate the changes into the default version.

How to use the sample

Once loaded, the map will zoom to the extent of the feature layer. The current version is indicated at the top of the map. Tap "Create Version" to open a dialog to specify the version information (name, access, and description). The version name must meet the following criteria:

  1. Must not exceed 62 characters
  2. Must not include: Period (.), Semicolon (;), Single quotation mark ('), Double quotation mark (")
  3. Must not include a space for the first character
  4. Note - the version name will have the username and a period (.) prepended to it. E.g "editor01.MyNewUniqueVersionName"

Then tap "Create" to create the version with the information that you specified. Select a feature to open a dialog, from which you can edit the feature attribute and tap confirm; or tap "Edit location" and tap again on the map to relocate the point.

Tap the button in the bottom right corner to switch back and forth between the version you created and the default version.

How it works

  1. Create and load a ServiceGeodatabase with a feature service URL that has enabled Version Management.
  2. Get the ServiceFeatureTable from the service geodatabase.
  3. Create a FeatureLayer from the service feature table.
  4. Create ServiceVersionParameters with a unique name, AccessVersion, and description.

    • Note - See the additional information section for more restrictions on the version name.
  5. Create a new version calling serviceGeodatabase.createVersionAsync(...) passing in the service version parameters.
  6. Listen to the returned ListenableFuture<ServiceVersionInfo> to obtain the ServiceVersionInfo of the version created.
  7. Switch to the version you have just created using serviceGeodatabase.switchVersionAsync(...), passing in the version name obtained from the service version info from step 6.
  8. Select a Feature from the map and edit it's "TYPDAMAGE" attribute from the options listed in the combo box.
  9. Tap on the map to relocate the feature.
  10. Apply these edits to your version by calling serviceGeodatabase.applyEditsAsync().
  11. Switch back and forth between your version and the default version to see how the two versions differ.

Relevant API

  • FeatureLayer
  • ServiceFeatureTable
  • ServiceGedodatabase
  • ServiceGeodatabase.applyEditsAsync()
  • ServiceGeodatabase.createVersionAsync()
  • ServiceGeodatabase.switchVersionAsync()
  • ServiceVersionInfo
  • ServiceVersionParameters
  • VersionAccess

About the data

The feature layer used in this sample is Damage to commercial buildings located in Naperville, Illinois.

Additional information

The name of the version must meet the following criteria:

  1. Must not exceed 62 characters
  2. Must not include: Period (.), Semicolon (;), Single quotation mark ('), Double quotation mark (")
  3. Must not include a space for the first character

Branch versioning access permission:

  1. VersionAccess.PUBLIC - Any portal user can view and edit the version.
  2. VersionAccess.PROTECTED - Any portal user can view, but only the version owner, feature layer owner, and portal administrator can edit the version.
  3. VersionAccess.PRIVATE - Only the version owner, feature layer owner, and portal administrator can view and edit the version.

Tags

branch versioning, edit, version control, version management server

Sample Code

MainActivity.kt
                                                                                                                                                                                                                                                                                                                                                                                                                         
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
/*
 * Copyright 2020 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.arcgisruntime.sample.editwithbranchversioning

import android.content.DialogInterface
import android.graphics.Point
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.arcgisservices.ServiceVersionParameters
import com.esri.arcgisruntime.arcgisservices.VersionAccess
import com.esri.arcgisruntime.data.Feature
import com.esri.arcgisruntime.data.ServiceGeodatabase
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.editwithbranchversioning.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.editwithbranchversioning.databinding.CreateVersionDialogBinding
import com.esri.arcgisruntime.sample.editwithbranchversioning.databinding.EditFeatureAttributeDialogBinding
import com.esri.arcgisruntime.security.UserCredential

class MainActivity : AppCompatActivity() {

  private val TAG = MainActivity::class.java.simpleName

  private val serviceGeodatabase: ServiceGeodatabase by lazy {
    ServiceGeodatabase("https://sampleserver7.arcgisonline.com/server/rest/services/DamageAssessment/FeatureServer")
  }

  private var featureLayer: FeatureLayer? = null
  private var selectedFeature: Feature? = null
  private var createdVersionName: String = ""

  private val activityMainBinding by lazy {
    ActivityMainBinding.inflate(layoutInflater)
  }

  private val mapView: MapView by lazy {
    activityMainBinding.mapView
  }

  private val switchVersionButton: Button by lazy {
    activityMainBinding.switchVersionButton
  }

  private val currentVersionNameTextView: TextView by lazy {
    activityMainBinding.currentVersionNameTextView
  }

  private val createVersionButton: Button by lazy {
    activityMainBinding.createVersionButton
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(activityMainBinding.root)

    // authentication with an API key or named user is required to access basemaps and other
    // location services
    ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)

    // hardcode user credentials since this sample has been setup to work with this specific
    // service. Normally you'd handle authentication with the AuthenticationChallengeHandler
    serviceGeodatabase.credential =
      UserCredential(
        getString(R.string.editor01_username),
        getString(R.string.editor01_password)
      )
    // load the service geodatabase
    serviceGeodatabase.loadAsync()
    // when the service geodatabase has loaded
    serviceGeodatabase.addDoneLoadingListener {
      // check if the service geodatabase failed to load
      if (serviceGeodatabase.loadStatus != LoadStatus.LOADED) {
        serviceGeodatabase.loadError?.let {
          Log.e(TAG, "Service Geodatabase failed to load: ${it.cause}")
        }
        return@addDoneLoadingListener
      }
      // create a feature layer from the service geodatabase's service feature table
      val serviceFeatureTable = serviceGeodatabase.getTable(0)
      featureLayer = FeatureLayer(serviceFeatureTable).apply {
        addDoneLoadingListener {
          // zoom to the layer's extent
          mapView.setViewpointAsync(Viewpoint(fullExtent))
        }
      }

      // create a map with a streets vector basemap and add the feature layer
      val map = ArcGISMap(BasemapStyle.ARCGIS_STREETS).apply {
        // add the layer to the map
        operationalLayers.add(featureLayer)
      }

      mapView.apply {
        // set the map to the map view
        this.map = map
        // set on touch listener for single taps
        onTouchListener =
          object : DefaultMapViewOnTouchListener(this@MainActivity, mapView) {
            override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
              // don't allow edits on the sde.DEFAULT version
              if (serviceGeodatabase.versionName.isBlank()
                || serviceGeodatabase.versionName == serviceGeodatabase.defaultVersionName
              ) {
                val message =
                  "This sample does not allow editing of features on the default version."
                Log.e(TAG, message)
                Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
                return true
              }

              // get the screen point of the single tap
              val screenPoint = android.graphics.Point(e.x.toInt(), e.y.toInt())

              // if selected feature is not null, edit the feature location
              selectedFeature?.let {
                editFeatureLocation(it, screenPoint)
                return true
              }

              // if no feature should be moved, identify the feature at the tapped location
              identifyFeature(screenPoint)
              return true
            }
          }
      }

      // display the current name in a text view
      currentVersionNameTextView.text = "Current version: ${serviceGeodatabase.versionName}"
    }
  }

  /**
   * Shows a dialog to the user which is used to create a new version. Calls create version when the
   * user confirms the dialog.
   *
   * @param view which called this method on click
   */
  fun createVersionDialog(view: View) {
    // inflate the view and get references to each of its components
    val dialogBinding = CreateVersionDialogBinding.inflate(LayoutInflater.from(this))
    val createNameEditText = dialogBinding.createNameEditText
    val createDescriptionEditText = dialogBinding.createDescriptionEditText
    val createAccessVersionSpinner = dialogBinding.createAccessVersionSpinner

    // set up the spinner to display options for the VersionAccess parameter for creating a version
    ArrayAdapter.createFromResource(
      this,
      R.array.version_access_array,
      android.R.layout.simple_spinner_item
    ).also { adapter ->
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
      createAccessVersionSpinner.adapter = adapter
    }

    // set up the dialog
    AlertDialog.Builder(this).apply {
      setView(dialogBinding.root)
      setTitle("Create a new version")
      setNegativeButton("Cancel") { _: DialogInterface, _: Int -> }
      setPositiveButton("Create") { _: DialogInterface, _: Int ->
        // when the user confirms check a name has been entered
        if (createNameEditText.text.toString().isNotEmpty()) {
          // create the version with the given parameters
          createVersion(
            createNameEditText.text.toString(),
            VersionAccess.valueOf(createAccessVersionSpinner.selectedItem.toString()),
            createDescriptionEditText.text.toString()
          )
        } else {
          Toast.makeText(
            this@MainActivity,
            "A version name is required!",
            Toast.LENGTH_LONG
          ).show()
        }
      }
    }.create().show()
  }

  /**
   * Creates a new version for this geodatabase
   *
   * @param versionName the name of the new version
   * @param versionAccess the access modifier for this version
   * @param description a text description of the version
   */
  private fun createVersion(
    versionName: String,
    versionAccess: VersionAccess,
    description: String
  ) {
    // create service version parameters with the parameters passed to this method
    val serviceVersionParameters = ServiceVersionParameters().apply {
      name = versionName
      access = versionAccess
      setDescription(description)
    }

    // create the version
    val serviceVersionInfoFuture =
      serviceGeodatabase.createVersionAsync(serviceVersionParameters)
    serviceVersionInfoFuture.addDoneListener {
      // get the new version's name and switch to it
      val serviceVersionInfo = serviceVersionInfoFuture.get()
      createdVersionName = serviceVersionInfo.name
      switchVersion(null)
    }

    // hide the create version button and allow the user to switch versions now
    createVersionButton.visibility = View.GONE
    switchVersionButton.visibility = View.VISIBLE
  }

  /**
   *  Switches between the version created by the user and the default version
   *
   *  @param view which called this method on click
   */
  fun switchVersion(view: View?) {
    // don't switch versions if the new version has not been created yet or the name has not been stored
    if (createdVersionName.isBlank()) {
      val message = "Version names have not been initialized!"
      Log.e(TAG, message)
      Toast.makeText(this, message, Toast.LENGTH_LONG).show()
    }

    // switch between default and created version names
    val versionName = when (serviceGeodatabase.versionName) {
      serviceGeodatabase.defaultVersionName -> createdVersionName
      createdVersionName -> serviceGeodatabase.defaultVersionName
      else -> serviceGeodatabase.defaultVersionName
    }

    // if the user has changed any features
    if (serviceGeodatabase.hasLocalEdits()) {
      // apply those changes
      serviceGeodatabase.applyEditsAsync().addDoneListener {
        try {
          // switch versions
          serviceGeodatabase.switchVersionAsync(versionName).addDoneListener {
            currentVersionNameTextView.text =
              "Current version: ${serviceGeodatabase.versionName}"
          }
        } catch (e: Exception) {
          val error = "Failed to switch version: ${e.message}"
          Log.e(TAG, error)
          Toast.makeText(this@MainActivity, error, Toast.LENGTH_LONG).show()
        }
      }
    } else {
      try {
        // switch versions
        serviceGeodatabase.switchVersionAsync(versionName).addDoneListener {
          currentVersionNameTextView.text =
            "Current version: ${serviceGeodatabase.versionName}"
        }
      } catch (e: Exception) {
        val error = "Failed to switch version: ${e.message}"
        Log.e(TAG, error)
        Toast.makeText(this@MainActivity, error, Toast.LENGTH_LONG).show()
      }
    }
  }

  /**
   * Identify the first feature near the given screen point. If one is found, select it and call
   * edit feature attribute.
   *
   * @param screenPoint to identify from
   */
  private fun identifyFeature(screenPoint: Point) {
    try {
      val identifyFuture = mapView.identifyLayerAsync(featureLayer, screenPoint, 10.0, false)
      identifyFuture.addDoneListener {
        val identifyLayerResult = identifyFuture.get()
        // if there is a feature at the location, select it and edit its attribute
        if (identifyLayerResult.elements.isNotEmpty()) {
          val feature = identifyLayerResult.elements[0] as Feature
          featureLayer?.selectFeature(feature)
          selectedFeature = feature
          editFeatureAttribute()
        }
      }
    } catch (e: Exception) {
      val error = "Identify layer failed: ${e.message}"
      Log.e(TAG, error)
      Toast.makeText(this@MainActivity, error, Toast.LENGTH_LONG).show()
    }
  }

  /**
   * Changes the location of the selected feature on the map.
   *
   * @param feature to move
   * @param screenPoint where the user tapped on the screen
   */
  private fun editFeatureLocation(feature: Feature, screenPoint: android.graphics.Point) {
    feature.geometry = mapView.screenToLocation(screenPoint)
    // features will not update visually until the feature table has been updated
    feature.featureTable.updateFeatureAsync(feature).addDoneListener {
      serviceGeodatabase.applyEditsAsync()
    }
    editFeatureAttribute()
  }

  /**
   * Creates a dialog which allows the user to edit a feature's TYPDAMAGE attribute or go on to edit
   * the feature's location
   */
  private fun editFeatureAttribute() {
    // if there is a selected feature
    selectedFeature?.let { feature ->
      val editFeatureAttributeDialogBinding =
        EditFeatureAttributeDialogBinding.inflate(layoutInflater)
      val featureAttributeSpinner = editFeatureAttributeDialogBinding.featureAttributeSpinner
      // set up the spinner with acceptable TYPDAMAGE values
      ArrayAdapter.createFromResource(
        this,
        R.array.feature_attribute_array,
        android.R.layout.simple_spinner_item
      ).also { adapter ->
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        featureAttributeSpinner.adapter = adapter
      }

      featureAttributeSpinner.setSelection(
        resources.getStringArray(R.array.feature_attribute_array)
          .indexOf(feature.attributes["TYPDAMAGE"])
      )

      // create the dialog
      AlertDialog.Builder(this).apply {
        setView(editFeatureAttributeDialogBinding.root)
        setTitle(feature.attributes["PLACENAME"].toString())
        setNegativeButton("Cancel") { _: DialogInterface, _: Int ->
          // clear the selection
          selectedFeature = null
          featureLayer?.clearSelection()
        }
        setNeutralButton("Edit location") { _: DialogInterface, _: Int ->
          // change the attribute
          feature.attributes["TYPDAMAGE"] =
            featureAttributeSpinner.selectedItem.toString()
          feature.featureTable.updateFeatureAsync(feature).addDoneListener {
            serviceGeodatabase.applyEditsAsync()
          }
        }
        setPositiveButton("Confirm") { _: DialogInterface, _: Int ->
          // change the attribute
          feature.attributes["TYPDAMAGE"] =
            featureAttributeSpinner.selectedItem.toString()
          feature.featureTable.updateFeatureAsync(feature).addDoneListener {
            serviceGeodatabase.applyEditsAsync()
          }
          // clear the selection
          featureLayer?.clearSelection()
          selectedFeature = null
        }
        setOnCancelListener {
          // clear the selection if the user taps outside the dialog
          featureLayer?.clearSelection()
          selectedFeature = null
        }.create().show()
      }
    }
  }

  override fun onResume() {
    super.onResume()
    mapView.resume()
  }

  override fun onPause() {
    mapView.pause()
    super.onPause()
  }

  override fun onDestroy() {
    mapView.dispose()
    super.onDestroy()
  }
}

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