New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Start learning with our library of video tutorials taught by experts. Get started

Android SDK: Local Data Storage
Illustration by Don Barnett

Working with files in external storage


From:

Android SDK: Local Data Storage

with David Gassner

Video: Working with files in external storage

Each Android app has both an internal and an external storage area. Files in internal storage can only be accessed by the application that created them. Files in external storage are available to all applications on the device. I'll describe how to create an application that uses external storage using this project called ExternalStorage. First, the application must be given permission to acces external storage. To do this, edit your Android manifest file.
Expand all | Collapse all
  1. 6m 34s
    1. Welcome
      50s
    2. What you should know before starting this course
      2m 11s
    3. Using the exercise files
      3m 33s
  2. 21m 6s
    1. Exploring local data storage options
      5m 58s
    2. Configuring Eclipse and the Android Developer Tools
      5m 29s
    3. Creating an Android virtual device
      3m 23s
    4. Creating a new Android project
      6m 16s
  3. 31m 30s
    1. Using preferences in Android apps
      5m 28s
    2. Defining preferences with Java
      9m 31s
    3. Defining shared preferences with an activity
      10m 50s
    4. Listening for changes to shared preferences
      5m 41s
  4. 51m 13s
    1. Creating and reading files in internal storage
      10m 18s
    2. Creating and reading JSON data files
      9m 48s
    3. Working with files in external storage
      11m 22s
    4. Parsing a read-only XML file with XmlPullParser
      11m 46s
    5. Parsing a read-only XML file with JDOM
      7m 59s
  5. 1h 8m
    1. Creating a new SQLite database
      2m 52s
    2. Defining a database with SQLiteOpenHelper
      12m 12s
    3. Managing the database with a DataSource class
      9m 38s
    4. Inserting data into a database table
      10m 29s
    5. Retrieving and displaying data
      11m 44s
    6. Importing data from XML to SQLite
      5m 15s
    7. Filtering and sorting data
      9m 27s
    8. Accessing a database from the command line
      6m 46s
  6. 42m 0s
    1. Improving the data display
      9m 29s
    2. Passing user-selected data to a detail activity
      11m 36s
    3. Working with multiple database tables
      10m 28s
    4. Deleting data from database tables
      10m 27s
  7. 49s
    1. Where to go from here
      49s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
Android SDK: Local Data Storage
3h 41m Intermediate Jan 25, 2013

Viewers: in countries Watching now:

Take your Android programming skills to the next level with the Android built-in framework that enables local data management in text files and SQLite-based relational databases. This course shows you how to create datacentric apps for Android devices, using SQLite, Java, and the built-in android.database packages. Author David Gassner describes how to define shared preferences, work with JSON and XML files in internal and external data stores, and create new local SQLite databases.

Topics include:
  • Exploring local data storage options
  • Creating an Android virtual device
  • Starting a new project
  • Defining preferences with Java and activities
  • Creating and reading JSON and XML data files
  • Creating a new SQLite database
  • Inserting and retrieving data in the database
Subjects:
Developer Mobile Apps Programming Languages
Software:
Android Java
Author:
David Gassner

Working with files in external storage

Each Android app has both an internal and an external storage area. Files in internal storage can only be accessed by the application that created them. Files in external storage are available to all applications on the device. I'll describe how to create an application that uses external storage using this project called ExternalStorage. First, the application must be given permission to acces external storage. To do this, edit your Android manifest file.

I'll open the Android manifest. It might open in XML format or in the Manifest view. Either way, click on the Permissions tab. Click the Add button and select Users Permission, and click OK. Pull down the list of available Permissions on the right, scroll all the way down to the bottom, and choose WRITE_EXTERNAL _STORAGE, and save your changes to the file. If you forget to do this, when you try to run the application using the code that I'm about to create, it will crash and you'll get no exception errors and information in the console view telling you what you missed.

Now that the application has permission, I can add code to read and write to external storage. I'll go to my MainActivity class. I already have code in this class that's accessing internal storage. I'll go to the bottom of the onCreate method. It starts up here. And then down towards the bottom, there's a bit of code that accesses the internal files directory. It does this using the method getFilesDir. To access external files, I'll change this from getFilesDir to getExternalFilesDir.

When you call this method, you're asked to pass in a string value. You can pass in a constant that references one of the standard subfolders of the external files directory. You can create subfolders for music files, for audio files, and for many other special types of files, but if you just want to get the root directory in your external storage area, pass in a value of null. All I'm doing in the onCreate method is getting that directory reference and its absolute path and then displaying that location in my user interphase.

So I'll save and run the application in the emulator. When the application opens, it shows the absolute address of the external file's location. It starts with mnt, then the name of the SD card, then Android, data, the package for the application, and the directory name files. You can see this location if you go to the DDMS perspective. From there, go to the File Explorer tab, go to the mnt folder, from there to sdcard, then to Android, to data.

You'll find folders there with package names. Here's the package for my application. I'll open that, and there's the files folder, and it's currently empty. So now we know we can get to external storage, and we're ready to write some code that creates a file there. I'll go back to my coding perspective, which I've called Android. Before you access content in the external files area, you should always check to make sure that it's actually available on the device on which you're running the application.

To do that, create a special method that will return a Boolean value. I'll scroll down to the bottom of my class and I'll create a new method called checkExternalStorage. I'll make it public, and it will return a Boolean value, and here's the method name. To checkExternalStorage state, call a method called getExternalStorageState, which is a static method of the environment class. It's a string. So I'll start by creating a string variable that I'll call state, and I'll get its value by calling Environment.getExternalStorageState.

Now I'll evaluate the state and determine whether I can write to external storage. I'll start with an if clause. I'll type in if and then press Ctrl+Space and choose if else. For this first conditional, I'll ask whether the state variable equals a value called MEDIA_MOUNTED. The code looks like this: state.equals, then I'll pass in Environment.MEDIA_MOUNTED, a constant.

If you get back this value, that means that external storage is available and you can write to it. So I'll return true. Here are the other possibilities. For my first else, I'll use an else if, and then I'll ask the question, does the state have a value of MEDIA_MOUNTED read-only? I'll take the part between the outer parentheses, copy it, and paste it into this parentheses, and I'll change this constant to MEDIA_MOUNTED_READ_ONLY.

If that's the condition, I'll output to the screen a string of external storage is read-only. I'll use my UIHelper class, I'll pass in this as the activity, and then the textView object and then the literal string, External storage is read-only. Finally, I'll put in an else clause, and for this condition, I'll tell the user that the external storage isn't reachable at all. I'll duplicate this line of code and move it down, and I'll change the literal string to External storage is unavailable.

Finally, after all the conditional code, I'll return false. So the only condition in which our report that external storage is available and writable is if I get back a value of MEDIA_MOUNTED. So now, I have code that contest my state and I'm ready to write to ExternalStorage. I'm going to scroll up a bit and find the method createFile. If you have trouble finding the method, restore your editor to its original size and try using the Outline view on the right.

I've modified my createFile method. I'm still using JSON data as I did before, but I've taken all of the code that's creating the JSON packet and put it into its own method, called getNewJSONData. That reduces the amount of code I'm reading here, and it'll make it easier to add some new functionality. In the createFile method, I'll find out whether I can write to external storage. I'll create an if statement, and I'll set the condition to not checkExternalStorage.

That's the method I just created. If that condition is true--that is, if external storage is not available--I'll just return. That's it. This method will stop operating. But if external storage is available, the rest of the code will be executed. I'll create my JSON array and I'll be ready to write it to disk. Now, before I create the file, I'm going to add some constants and fields to the top of the class. First, I'm going to declare a file object that will persist for the lifetime of the activity.

I'll declare this after the existing fields. I'll set it to private. I'll give it a data type of File and a name of file, all lowercase. I'll also create a constant named FILENAME, and this will be the name of the file I'm about to create. I'll declare a private static final and string, I'll name it FILENAME, all upper- case, and then the name of the actual file will be jsondata, all lowercase. I'll initialize the file in the onCreate method.

I'll go down to the bottom of the onCreate method, and here I'm going to use this variable that represents my external files directory. I'll create a new file reference that points to a file in that directory. Down here, I'll say file = new File. I'll create a new file that's placed in the external files directory. So the first argument will be f, which points to that file's directory, and the second argument will be the name of the file and I'll use my new constant, FILENAME.

To make this a little bit easier to read, I'll refactor and rename this variable. I'll select the variable f, right- click and choose Refactor > Rename. I'll name the variable extDir, for External Directory. So now this file object is going to point to the file and I'll be able to use it as many times as I need to within the activity. So now I'll go back to the createFile method. To make this a little bit easier, I'll restore the editor and then use my outline over here and go to createFile, and then expand the editor again.

In order to point to my file that I've just defined in external storage, I'll remove this code that's defining a file in internal storage. I'll replace it with a bit of code that instantiates FileOutputStream and passes in the file object. Now the file is being written to external storage instead of internal storage. I'll do the same sort of thing to the readFile method. I'll move down here. And here's where I'm creating my FileInputStream.

I'll remove that code and instead use the FileInputStream's constructor method and pass in the file object. Now, this method is also pointing to a file in external storage. I'm done. I'm ready to test my code. I'll run the application in the emulator. When the application opens, I'll click Create file and the file is written to disk. Then I'll click Read file and the file is read from disk. Now, to show where the file has been created, I'll go back to Eclipse, to the DDMS perspective, and I'll refresh my view by clicking on one of the spinners in the directory tree, and there's my file jsondata.

With the file selected, I'll click the link to pull the file from the device. I'll place it on my desktop and save the file to disk. Now, I'll go to Finder. If you're working on Windows, you can go to Windows Explorer. I'll go to my desktop, and there's my file. And I'll open it in a text editor. I'll use TextEdit, but you can use any text editor you like. Here I can see that the file has been created using JSON format and is available in the External Files directory.

Because this file is external, you can access it not just in the emulator but with an actual device. So at this point, I encourage you to try running the application on an actual Android device. Remember I said that with internal storage, you'd be able to access the directory on an emulator but not so easily on a real device. With external storage, you should be able to see the file, and you should be able to pull the file to your development computer and verify the structure and content of the file that you're creating and reading in an Android app.

There are currently no FAQs about Android SDK: Local Data Storage.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Android SDK: Local Data Storage.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.