#167 android: guard getExternalFilesDir, flutter: guard empty volume list

This commit is contained in:
Thibault Deckers 2022-01-28 10:25:40 +09:00
parent 6c53a11ea6
commit a62ad03851
3 changed files with 70 additions and 58 deletions

View file

@ -89,6 +89,7 @@ object StorageUtils {
}
private fun findPrimaryVolumePath(context: Context): String? {
try {
// we want:
// /storage/emulated/0/
// `Environment.getExternalStorageDirectory()` (deprecated) yields:
@ -96,12 +97,17 @@ object StorageUtils {
// `context.getExternalFilesDir(null)` yields:
// /storage/emulated/0/Android/data/{package_name}/files
return appSpecificVolumePath(context.getExternalFilesDir(null))
} catch (e: Exception) {
Log.e(LOG_TAG, "failed to find primary volume path", e)
}
return null
}
private fun findVolumePaths(context: Context): Array<String> {
// Final set of paths
val paths = HashSet<String>()
try {
// Primary emulated SD-CARD
val rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET") ?: ""
if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
@ -153,6 +159,9 @@ object StorageUtils {
System.getenv("SECONDARY_STORAGE")?.let { secondaryStorages ->
paths.addAll(secondaryStorages.split(File.pathSeparator).filter { it.isNotEmpty() })
}
} catch (e: Exception) {
Log.e(LOG_TAG, "failed to find volume paths", e)
}
return paths.map { ensureTrailingSeparator(it) }.toTypedArray()
}

View file

@ -23,13 +23,13 @@ class _CreateAlbumDialogState extends State<CreateAlbumDialog> {
final ValueNotifier<bool> _existsNotifier = ValueNotifier(false);
final ValueNotifier<bool> _isValidNotifier = ValueNotifier(false);
late Set<StorageVolume> _allVolumes;
late StorageVolume _primaryVolume, _selectedVolume;
late StorageVolume? _primaryVolume, _selectedVolume;
@override
void initState() {
super.initState();
_allVolumes = androidFileUtils.storageVolumes;
_primaryVolume = _allVolumes.firstWhere((volume) => volume.isPrimary, orElse: () => _allVolumes.first);
_primaryVolume = _allVolumes.firstWhereOrNull((volume) => volume.isPrimary) ?? _allVolumes.firstOrNull;
_selectedVolume = _primaryVolume;
_nameFieldFocusNode.addListener(_onFocus);
}
@ -144,8 +144,9 @@ class _CreateAlbumDialogState extends State<CreateAlbumDialog> {
}
String _buildAlbumPath(String name) {
if (name.isEmpty) return '';
return pContext.join(_selectedVolume.path, 'Pictures', name);
final selectedVolume = _selectedVolume;
if (selectedVolume == null || name.isEmpty) return '';
return pContext.join(selectedVolume.path, 'Pictures', name);
}
Future<void> _validate() async {

View file

@ -37,9 +37,11 @@ class _FilePickerState extends State<FilePicker> {
@override
void initState() {
super.initState();
final primaryVolume = volumes.firstWhere((v) => v.isPrimary);
final primaryVolume = volumes.firstWhereOrNull((v) => v.isPrimary);
if (primaryVolume != null) {
_goTo(primaryVolume.path);
}
}
@override
Widget build(BuildContext context) {