Tech Blog

Coding

Accessing Removable SD card in Android Studio

By Mahek pariawala3 min read
← Back to blog

For Android versions that are below Android 10, accessing the External Storage of your device is pretty straightforward. The method Environment.getExternalStorageDirectory() would return the appropriate path but now, this method is deprecated and only points to /sdcard which is not necessarily the removable secondary storage path.

You could try to hardcode the path such as mnt/externalsd, but this path varies from device to device, so it is not reliable.

From Android 10 onwards, you will need to use a Content Provider for this purpose.

What is a Content Provider?

A content provider manages access to a central repository of data which is intended to be used by other applications, using a provider client object. 

Depending on the type of files you want to access using content provider, you would either have to use :

Media Provider – audio, video and image files through MediaStoreAPI  (link https://developer.android.com/training/data-storage/shared/media) 

Documents provider – files such as pdfs or EUPB files for which MIME type is required

(link https://developer.android.com/training/data-storage/shared/documents-files) 


Here, I will stress on using a document provider.

To use a Content Provider, for any action, you need to first create a new Intent with the required action. For reading Documents, use the action ACTION_READ_DOCUMENT and for writing, use ACTION_CREATE_DOCUMENT after which you can navigate to the desired folder. 

For the Intent, you need to include setType as the MIME type of your document.

Then handle the URI using an Inputstream/Outputstream and perform your desired action using getContentProvider() in the OnActivityResult() method of your Activity as shown: 

InputStream is = getContentResolver().openInputStream(FILE_PATH_URI);

Here is an example of a simple code to read and write files from the External Storage. 

int CREATE_FILE_REQUEST_CODE = 11;
int OPEN_FILE_REQUEST_CODE = 12;

public void newDocument() {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("text/plain");
        startActivityForResult(intent, CREATE_FILE_REQUEST_CODE);
}
public void readDocument(){
 Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("text/plain");
            startActivityForResult(intent, OPEN_FILE_REQUEST_CODE);
}

public void onActivityResult(int requestCode, int resultCode, Intent fileIntent) {
        super.onActivityResult(requestCode, resultCode, data);
        FILE_PATH = fileIntent.getData();

        if ( requestCode == CREATE_FILE_REQUEST_CODE ) {
            if (resultCode == RESULT_OK) {
                try {
                    PrintWriter writer = new PrintWriter((getContentResolver().openOutputStream(FILE_PATH)));
                    writer.write("Hello! This is a text file");
                    writer.flush();
                    writer.close();

                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
            else if(requestCode ==OPEN_FILE_REQUEST_CODE) {
	if(resultCode==RESULT_OK){
                try {
                 InputStream is = getContentResolver().openInputStream(FILE_PATH);
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String  line = reader.readLine();
                System.out.printLn( "String: " + line);
                reader.close();
            }catch (IOException e) {
                    System.out.println(e.getMessage());
            }
            }
}
}

Keep reading

You may be interested in

Browse all articles →
Active Directory Federation Service
July 5, 20235 min read

Active Directory Federation Service

Active Directory Federation Service (ADFS) uses claims-based identity model to maintain application security and to implement federated identity. ADFS is a concept of Windows Server operating system, that provides users with single sign-on access to the application, those are located across organizational boundaries. For Example: We have 2 organizations – Organization 1 and Organization 2. […]

By Abinash MishraRead More →
Remote Access to Microsoft SQL Database Server
April 5, 20232 min read

Remote Access to Microsoft SQL Database Server

Remote access to a SQL server is important because it allows users to access the server from anywhere, at any time. This enables remote workers to access the data they need when they need it, even if they are not physically in the same location as the server. It also allows IT admins to access […]

By Malkeet SinghRead More →
Types of Load Balancer in AWS
February 6, 20235 min read

Types of Load Balancer in AWS

What is Load Balancing ? Load balancing is a critical component of any scalable and highly available Cloud or On-premise architecture. It helps distribute incoming traffic across multiple servers, improving the availability and scalability of a website or application. In the cloud, load balancing is offered as a service by various cloud providers such as […]

By Keerthik ShenoyRead More →