Generate geodatabase replica from feature service

View inJavaKotlinView on GitHubSample viewer app

Generate a local geodatabase replica from an online feature service.

Image of generate geodatabase

Use case

Generating geodatabase replicas is the first step toward taking a feature service offline. It allows you to save features locally for offline display.

How to use the sample

Zoom to any extent. Then tap the generate button to generate a geodatabase of features from a feature service filtered to the current extent. A red outline will show the extent used. The job's progress is shown while the geodatabase is generated. When complete, the map will reload with only the layers in the geodatabase, clipped to the extent.

How it works

  1. Create a GeodatabaseSyncTask with the URL of the feature service and load it.
  2. Create GenerateGeodatabaseParameters specifying the extent and whether to include attachments.
  3. Create a GenerateGeodatabaseJob with geodatabaseSyncTask.generateGeodatabaseAsync(parameters, downloadPath). Start the job with job.start().
  4. When the job is done, get the geodatabase from job.result. Inside the geodatabase are feature tables which can be used to add feature layers to the map.
  5. Call syncTask.unregisterGeodatabaseAsync(geodatabase) after generation when you're not planning on syncing changes to the service.

Relevant API

  • GenerateGeodatabaseJob
  • GenerateGeodatabaseParameters
  • Geodatabase
  • GeodatabaseSyncTask

Offline data

  1. Download the data from ArcGIS Online.
  2. Extract the contents of the downloaded zip file to disk.
  3. Open your command prompt and navigate to the folder where you extracted the contents of the data from step 1.
  4. Push the data into the scoped storage of the sample app: adb push SanFrancisco.tpkx /Android/data/com.esri.arcgisruntime.sample.generategeodatabase/files/SanFrancisco.tpkx

Tags

disconnected, local geodatabase, offline, replica, sync

Sample Code

MainActivity.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
/* 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.generategeodatabasereplicafromfeatureservice

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.concurrent.Job
import com.esri.arcgisruntime.data.Geodatabase
import com.esri.arcgisruntime.data.TileCache
import com.esri.arcgisruntime.layers.ArcGISTiledLayer
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.Basemap
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.tasks.geodatabase.GenerateGeodatabaseJob
import com.esri.arcgisruntime.tasks.geodatabase.GeodatabaseSyncTask
import com.esri.arcgisruntime.sample.generategeodatabasereplicafromfeatureservice.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.generategeodatabasereplicafromfeatureservice.databinding.DialogLayoutBinding

class MainActivity : AppCompatActivity() {

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

    // define the local path where the geodatabase will be stored
    private val localGeodatabasePath: String by lazy { externalCacheDir?.path + getString(R.string.wildfire_geodatabase) }

    // objects that implement Loadable must be class fields to prevent being garbage collected before loading
    private val geodatabaseSyncTask: GeodatabaseSyncTask by lazy { GeodatabaseSyncTask(getString(R.string.wildfire_sync)) }
    private lateinit var geodatabase: Geodatabase

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

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

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activityMainBinding.root)
        // use local tile package for the base map
        val sanFrancisco =
            TileCache(getExternalFilesDir(null).toString() + getString(R.string.san_francisco_tpkx))
        val tiledLayer = ArcGISTiledLayer(sanFrancisco)

        // add the map and graphics overlay to the map view
        mapView.apply {
            // create a map with the tile package basemap
            map = ArcGISMap(Basemap(tiledLayer))
            // create a graphics overlay to display the boundaries
            graphicsOverlays.add(GraphicsOverlay())
        }
    }

    /**
     * Creates a GenerateGeodatabaseJob and runs it.
     *
     * @param view the button which calls this function
     */
    fun generateGeodatabase(view: View) {
        // load the geodatabase sync task
        geodatabaseSyncTask.loadAsync()
        geodatabaseSyncTask.addDoneLoadingListener {
            // draw a box around the extent
            mapView.apply {
                // clear any previous operational layers and graphics
                map.operationalLayers.clear()
                graphicsOverlays[0].graphics.clear()
                // show the extent used as a graphic
                graphicsOverlays[0].graphics.add(
                    Graphic(
                        visibleArea.extent,
                        SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 5f)
                    )
                )
            }

            // create parameters for the job with the return attachments option set to false
            val parameters = geodatabaseSyncTask
                .createDefaultGenerateGeodatabaseParametersAsync(mapView.visibleArea.extent).get()
                .apply { isReturnAttachments = false }

            // create the generate geodatabase job
            val generateGeodatabaseJob =
                geodatabaseSyncTask.generateGeodatabase(parameters, localGeodatabasePath)

            // show the job's progress in a dialog
            val dialogLayoutBinding = DialogLayoutBinding.inflate(layoutInflater)
            val dialog = createProgressDialog(generateGeodatabaseJob)
            dialog.setView(dialogLayoutBinding.root)
            dialog.show()
            // define progress and done behaviours and start the job
            generateGeodatabaseJob.apply {
                // update progress
                addProgressChangedListener {
                    dialogLayoutBinding.progressBar.progress = this.progress
                    dialogLayoutBinding.progressTextView.text = "${this.progress}%"
                }
                // get geodatabase when done
                addJobDoneListener {
                    // close the progress dialog
                    dialog.dismiss()
                    // load the geodatabase and display its feature tables on the map
                    loadGeodatabase(generateGeodatabaseJob, geodatabaseSyncTask)
                }
            }.start()
        }
    }

    /**
     * Loads the geodatabase from a GenerateGeodatabaseJob and displays its feature tables on the map.
     *
     * @param generateGeodatabaseJob the job which generated this geodatabase
     * @param geodatabaseSyncTask the GeodatabaseSyncTask which created the job
     */
    private fun loadGeodatabase(
        generateGeodatabaseJob: GenerateGeodatabaseJob,
        geodatabaseSyncTask: GeodatabaseSyncTask
    ) {
        // return if the job failed
        if (generateGeodatabaseJob.status != Job.Status.SUCCEEDED) {
            val error =
                generateGeodatabaseJob.error?.message ?: "Unknown error generating geodatabase"
            Log.e(TAG, error)
            Toast.makeText(this, error, Toast.LENGTH_LONG).show()
            return
        }
        // if the job succeeded, load the resulting geodatabase
        geodatabase = generateGeodatabaseJob.result
        geodatabase.loadAsync()
        geodatabase.addDoneLoadingListener {
            // return if the geodatabase failed to load
            if (geodatabase.loadStatus != LoadStatus.LOADED) {
                val error = "Error loading geodatabase: " + geodatabase.loadError.message
                Log.e(TAG, error)
                Toast.makeText(this, error, Toast.LENGTH_LONG).show()
                return@addDoneLoadingListener
            }
            // if the geodatabase loaded, hide the generate button
            genGeodatabaseButton.visibility = View.GONE
            // add all of the geodatabase feature tables to the map as feature layers
            val featureLayers =
                geodatabase.geodatabaseFeatureTables.map { featureTable -> FeatureLayer(featureTable) }
            mapView.map.operationalLayers.addAll(featureLayers)

            val message = "Local geodatabase stored at: $localGeodatabasePath"
            Log.i(TAG, message)
            Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        }
        // unregister since we're not syncing
        geodatabaseSyncTask.unregisterGeodatabaseAsync(geodatabase).addDoneListener {
            val message = "Geodatabase unregistered since we wont be editing it in this sample."
            Log.i(TAG, message)
            Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        }
    }

    /**
     * Create a progress dialog box for tracking the generate geodatabase job.
     *
     * @param generateGeodatabaseJob the generate geodatabase job progress to be tracked
     * @return an AlertDialog set with the dialog layout view
     */
    private fun createProgressDialog(generateGeodatabaseJob: GenerateGeodatabaseJob): AlertDialog {
        val builder = AlertDialog.Builder(this@MainActivity).apply {
            setTitle(getString(R.string.progress_fetching))
            // provide a cancel button on the dialog
            setNeutralButton("Cancel") { _, _ ->
                generateGeodatabaseJob.cancelAsync()
            }
            setCancelable(false)
            setView(
                LayoutInflater.from(this@MainActivity)
                    .inflate(R.layout.dialog_layout, null)
            )
        }
        return builder.create()
    }

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

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

    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.