From 9534a1031a9185556460f7ea68deb68bcca1464e Mon Sep 17 00:00:00 2001 From: Tom Levy Date: Mon, 18 Mar 2024 15:31:42 +0000 Subject: [PATCH] Delete exported file on error If ActivityResultContracts.CreateDocument launches the native Files app (com.android.documentsui), then it will create the file before the Uri is returned to us. So if we don't complete the export (due to an exception or because there are no messages) we should delete the file, otherwise there will be an empty/incomplete file left behind. --- .../fossify/messages/activities/SettingsActivity.kt | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/app/src/main/kotlin/org/fossify/messages/activities/SettingsActivity.kt b/app/src/main/kotlin/org/fossify/messages/activities/SettingsActivity.kt index 454fd92d..a66230a8 100644 --- a/app/src/main/kotlin/org/fossify/messages/activities/SettingsActivity.kt +++ b/app/src/main/kotlin/org/fossify/messages/activities/SettingsActivity.kt @@ -5,6 +5,7 @@ import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle +import android.provider.DocumentsContract import androidx.activity.result.contract.ActivityResultContracts import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json @@ -119,6 +120,7 @@ class SettingsActivity : SimpleActivity() { private fun exportMessages(uri: Uri) { ensureBackgroundThread { + var success = false try { MessagesReader(this).getMessagesToExport(config.exportSms, config.exportMms) { messagesToExport -> if (messagesToExport.isEmpty()) { @@ -132,10 +134,20 @@ class SettingsActivity : SimpleActivity() { outputStream.use { it.write(jsonString.toByteArray()) } + success = true toast(org.fossify.commons.R.string.exporting_successful) } } catch (e: Throwable) { // also catch OutOfMemoryError etc. showErrorToast(e.toString()) + } finally { + if (!success) { + // delete the file to avoid leaving behind an empty/corrupt file + try { + DocumentsContract.deleteDocument(contentResolver, uri) + } catch (ignored: Exception) { + // ignored because we don't want to overwhelm the user with two error messages + } + } } } }