Hardcoded SD Card Path
ID |
java.android_sdcard_path |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Java |
Tags |
android, portability |
Description
Reports string literals that refer to hardcoded SD card paths (/sdcard, /mnt/sdcard, /storage/sdcard0). These paths are implementation details that are not guaranteed by the Android platform. Starting with scoped storage (API 29+), direct access to these paths is restricted and will fail at runtime.
Rationale
Android devices use different mount points for external storage depending on the manufacturer and OS version. Hardcoding /sdcard or /mnt/sdcard may work on a single test device but breaks on others. Furthermore, scoped storage (introduced in Android 10) restricts apps from accessing arbitrary paths on the filesystem, meaning code that targets these paths will receive FileNotFoundException or permission errors on modern devices.
// Bad: hardcoded SD card paths
File f = new File("/sdcard/data");
String photos = "/mnt/sdcard/photos";
String music = "/storage/sdcard0/music";
Remediation
Use the Android API to obtain the correct storage directory at runtime. The recommended alternatives are Context.getExternalFilesDir(), Environment.getExternalStorageDirectory(), or the Storage Access Framework for user-facing files.
// Good: use the API to get the correct path
File dir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File legacy = Environment.getExternalStorageDirectory();
// Best: use Storage Access Framework for user files
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE);