提问人:Tommy 提问时间:11/2/2023 最后编辑:Tommy 更新时间:11/3/2023 访问量:47
如何在Kotlin中下载GeoJSON文件?
How to download GeoJSON file in Kotlin?
问:
因此,GeoJSON 文件将使用以下代码创建:
val coordinates = listOf(
Coordinate(4.5165132153, 99.651681683),
Coordinate(4.5163152153, 99.878981683),
Coordinate(4.3584532153, 99.021481683),
Coordinate(4.1578132153, 99.698781683),
Coordinate(4.3655132153, 99.321481683),
Coordinate(4.8795132153, 99.874581683)
)
val geometry = mapOf(
"type" to "Polygon",
"coordinates" to listOf(listOf(coordinates.map { listOf(it.lon, it.lat) }))
)
val properties = mapOf(
"name" to "Your Polygon Name",
// Add other properties as needed
)
val feature = mapOf(
"type" to "Feature",
"geometry" to geometry,
"properties" to properties
)
val featureCollection = mapOf(
"type" to "FeatureCollection",
"features" to listOf(feature)
)
然后将 GeoJSON 数据序列化为 JSON 字符串
val gson = Gson()
val geoJsonString = gson.toJson(featureCollection)
然后将 JSON 字符串写入应用的内部存储中
val fileName = "my_polygon.geojson"
val file = File(context.filesDir, fileName)
file.writeText(geoJsonString)
所以我想下载这些数据,并通过点击一个按钮将其保存到手机存储中,例如:binding.downloadButton.setOnClickListener{ }
有谁知道如何执行这项任务?
谢谢!
答:
1赞
ΓDΛ
11/2/2023
#1
首先,定义所需的 .permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
检查。permissions
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
requestPermissions(
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSION_REQUEST_CODE
)
}
并保存文件操作
try {
val root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
if (!root.exists()) {
root.mkDirs()
}
val file = File(root, "fileName.json")
val writer = FileWriter(file)
writer.append(geoJsonString)
writer.flush()
writer.close()
} catch (e: Exception) {
e.printStackTrace()
}
您的案例
binding.downloadButton.setOnClickListener {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
requestPermissions(
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSION_REQUEST_CODE
)
} else {
try {
val root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
if (!root.exists()) {
root.mkdirs()
}
val file = File(root, "fileName.json")
val writer = FileWriter(file)
writer.append(geoJsonString)
writer.flush()
writer.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
评论
0赞
Tommy
11/3/2023
这行得通!谢谢!但是对于 Android v33 及更高版本,不允许WRITE_EXTERNAL_STORAGE,这个 SIR 的替代权限是什么?谢谢!
1赞
ΓDΛ
11/3/2023
别客气。İ 推荐 youtu.be/dEASm7nv7DA?si=WyYfDqjmlnbkBO50
评论