Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

External Storage in Android with Example

External storage in Android refers to a location where you can save files that aren't directly tied to your application's lifecycle, meaning they can persist even if the app is uninstalled. This could be an SD card or an internal partition, depending on the device. External storage is typically used for saving files that should be shareable between apps or large files like media.

Permissions

Before you can read from or write to external storage, you need to request the necessary permissions.

  • Add permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

However, starting from Android 10 (API 29), apps are encouraged to use scoped storage, which provides specific access to files and folders via system file pickers without requiring broad storage permissions.

  • Request permissions at runtime:

For Android 6.0 (API 23) and later, you also need to request permissions at runtime:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}

Write to External Storage

Here's a basic example to write a simple text file to external storage:

File externalDirectory = Environment.getExternalStorageDirectory();
File myFile = new File(externalDirectory, "mytextfile.txt");

try {
    FileOutputStream fos = new FileOutputStream(myFile);
    fos.write("Hello, World!".getBytes());
    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}

Read from External Storage

To read the previously written text file:

try {
    FileInputStream fis = new FileInputStream(myFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String line = br.readLine();
    br.close();
    Log.d("ExternalStorage", "Read from file: " + line);
} catch (IOException e) {
    e.printStackTrace();
}

Note:

  • Remember to check if the external storage is mounted and writable before attempting to write.
  • Due to changes in recent Android versions, especially with the introduction of Scoped Storage in Android 10, direct access to external storage has been limited. Instead, you're encouraged to use the Storage Access Framework (SAF) to allow users to select files or directories that your app can access. For most use-cases on modern Android, you'll want to use SAF or specific Media or Download collections.
  • Apps targeting Android 11 (API 30) and later are scoped to their own storage sandboxes and cannot directly access shared storage, unless they use the MANAGE_EXTERNAL_STORAGE permission or SAF.
  1. Checking external storage availability in Android:

    • Description: This example checks if external storage (SD card) is available on the device.
    • Code:
      String state = Environment.getExternalStorageState();
      if (Environment.MEDIA_MOUNTED.equals(state)) {
          // External storage is available
      } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
          // External storage is read-only
      } else {
          // External storage is not available
      }
      
  2. Reading and writing files to external storage in Android:

    • Description: Demonstrates how to read from and write to external storage.
    • Code:
      // Writing to external storage
      String data = "Hello, External Storage!";
      File file = new File(Environment.getExternalStorageDirectory(), "example.txt");
      try {
          FileWriter writer = new FileWriter(file);
          writer.write(data);
          writer.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
      
      // Reading from external storage
      try {
          BufferedReader reader = new BufferedReader(new FileReader(file));
          String line = reader.readLine();
          reader.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
      
  3. Requesting runtime permissions for external storage in Android:

    • Description: Shows how to request runtime permissions for accessing external storage.
    • Code:
      if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
              != PackageManager.PERMISSION_GRANTED) {
          ActivityCompat.requestPermissions(this,
                  new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                  MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
      }
      
  4. Handling file operations on external storage with example:

    • Description: Covers basic file operations like creating, deleting, and renaming files on external storage.
    • Code:
      // Creating a file
      File newFile = new File(Environment.getExternalStorageDirectory(), "new_file.txt");
      try {
          newFile.createNewFile();
      } catch (IOException e) {
          e.printStackTrace();
      }
      
      // Deleting a file
      if (newFile.exists()) {
          newFile.delete();
      }
      
      // Renaming a file
      File renamedFile = new File(Environment.getExternalStorageDirectory(), "renamed_file.txt");
      newFile.renameTo(renamedFile);
      
  5. Using MediaScannerConnection for media files on external storage:

    • Description: Demonstrates how to use MediaScannerConnection to notify the system of new media files.
    • Code:
      MediaScannerConnection.scanFile(context, new String[]{file.getPath()}, null,
              new MediaScannerConnection.OnScanCompletedListener() {
                  @Override
                  public void onScanCompleted(String path, Uri uri) {
                      // Media scan is complete
                  }
              });
      
  6. Saving and retrieving data from external storage in Android:

    • Description: Illustrates saving and retrieving data (e.g., preferences) on external storage.
    • Code:
      // Saving data
      SharedPreferences preferences = getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = preferences.edit();
      editor.putString("key", "value");
      editor.apply();
      
      // Retrieving data
      String retrievedValue = preferences.getString("key", "default_value");