Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

70. An Android Storage Access Framework Example

As previously discussed, the Storage Access Framework considerably eases the process of integrating cloud based storage access into Android applications. Consisting of a picker user interface and a set of new intents, access to files stored on document providers such as Google Drive and Box can now be built into Android applications with relative ease. With the basics of the Android Storage Access Framework covered in the preceding chapter, this chapter will work through the creation of an example application which uses the Storage Access Framework to store and manage files.

70.1 About the Storage Access Framework Example

The Android application created in this chapter will take the form of a rudimentary text editor designed to create and store text files remotely onto a cloud based storage service. In practice, the example will work with any cloud based document storage provider that is compatible with the Storage Access Framework, though for the purpose of this example the use of Google Drive is assumed.

In functional terms, the application will present the user with a multi-line text view into which text may be entered and edited, together with a set of buttons allowing storage based text files to be created, opened and saved.

70.2 Creating the Storage Access Framework Example

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter StorageDemo into the Name field and specify com.ebookfrenzy.storagedemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

Designing the User Interface

The user interface will need to be comprised of three Button views and a single EditText view. Within the Project tool window, navigate to the activity_main.xml layout file located in app -> res -> layout and double-click on it to load it into the Layout Editor tool. With the tool in Design mode, select and delete the Hello World! TextView object.

Drag and position a Button widget in the top left-hand corner of the layout so that both the left and top dotted margin guidelines...

70.3 Declaring Request Codes

Working with files in the Storage Access Framework involves triggering a variety of intents depending on the specific action to be performed. Invariably this will result in the framework displaying the storage picker user interface so that the user can specify the storage location (such as a directory on Google Drive and the name of a file). When the work of the intent is complete, the application will be notified by a call to a method named onActivityResult().

Since all intents from a single activity will result in a call to the same onActivityResult() method, a mechanism is required to identify which intent triggered the call. This can be achieved by passing a request code through to the intent when it is launched. This code is then passed on to the onActivityResult() method by the intents, enabling the method to identify which action has been requested by the user. Before implementing the onClick handlers to create, save and open files, the first...

70.4 Creating a New Storage File

When the New button is selected, the application will need to trigger an ACTION_CREATE_DOCUMENT intent configured to create a file with a plain-text MIME type. When the user interface was designed, the New button was configured to call a method named newFile(). It is within this method that the appropriate intent needs to be launched.

Remaining in the MainActivity.java file, implement this method as follows:

package com.ebookfrenzy.storagedemo;

 

import android.app.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.EditText;

import android.content.Intent;

import android.view.View;

import android.net.Uri;

 

public class MainActivity extends AppCompatActivity {

 

    private static EditText textView;

 

    private static final int CREATE_REQUEST_CODE = 40;

    private...

70.5 The onActivityResult() Method

The onActivityResult() method will be shared by all of the intents that will be called during the lifecycle of the application. In each case, the method will be passed a request code, a result code and a set of result data which contains the Uri of the storage file. The method will need to be implemented such that it checks for the success of the intent action, identifies the type of action performed and extracts the file Uri from the results data. At this point in the tutorial, the method only needs to handle the creation of a new file on the selected document provider, so modify the MainActivity.java file to add this method as follows:

public void onActivityResult(int requestCode, int resultCode,

         Intent resultData) {

 

       super.onActivityResult(requestCode, resultCode, resultData);

 

       if...

70.6 Saving to a Storage File

Now that the application is able to create new storage based files, the next step is to add the ability to save any text entered by the user to a file. The user interface is configured to call the saveFile() method when the Save button is selected by the user. This method will be responsible for starting a new intent of type ACTION_OPEN_DOCUMENT which will result in the picker user interface appearing so that the user can choose the file to which the text is to be stored. Since we are only working with plain text files, the intent needs to be configured to restrict the user’s selection options to existing files that match the text/plain MIME type. Having identified the actions to be performed by the saveFile() method, this can now be added to the MainActivity.java class file as follows:

public void saveFile(View view)

{

       Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

   ...

70.7 Opening and Reading a Storage File

Having written the code to create and save text files, the final task is to add some functionality to open and read a file from the storage. This will involve writing the openFile() onClick event handler method and implementing it so that it starts an ACTION_OPEN_DOCUMENT intent:

public void openFile(View view)

{

       Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

       intent.addCategory(Intent.CATEGORY_OPENABLE);

       intent.setType("text/plain");

       startActivityForResult(intent, OPEN_REQUEST_CODE);

}

In this code, the intent is configured to filter selection to files which can be opened by the application. When the activity is started, it is passed the open request code constant which will now need to be handled within the onActivityResult() method...

70.8 Testing the Storage Access Application

With the coding phase complete the application is now ready to be fully tested. Begin by launching the application on an Android device or AVD configured with your Google account identity and selecting the “New” button. Within the resulting storage picker interface, select a Google Drive location and name the text file storagedemo.txt before selecting the Save option located to the right of the file name field.

When control returns to your application look for the file uploading notification, then enter some text into the text area before selecting the “Save” button. Select the previously created storagedemo.txt file from the picker to save the content to the file. On returning to the application, delete the text and select the “Open” button, once again choosing the storagedemo.txt file. When control is returned to the application, the text view should have been populated with the content of the...

70.9 Summary

This chapter has worked through the creation of an example Android Studio application in the form of a very rudimentary text editor designed to use cloud based storage to create, save and open files using the Android Storage Access Framework.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth