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

Creating and reading files in internal storage


From:

Android SDK: Local Data Storage

with David Gassner

Video: Creating and reading files in internal storage

The Android SDK includes all of the tools you need to create and read files. You can create binary or text files. And for text files, you can use your own arbitrary format, or you can use common structured data formats, such as JSON and XML. The files can be placed in either internal or external storage. This refers to whether the file is local to the application or shared with other applications. I'll start with internal files. I'm working in a version of the project called Internal Storage.
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

Creating and reading files in internal storage

The Android SDK includes all of the tools you need to create and read files. You can create binary or text files. And for text files, you can use your own arbitrary format, or you can use common structured data formats, such as JSON and XML. The files can be placed in either internal or external storage. This refers to whether the file is local to the application or shared with other applications. I'll start with internal files. I'm working in a version of the project called Internal Storage.

This project has an Edit Text control in the layout and then two buttons at the bottom labeled Create file and Read file. And there's also a TextView object at the bottom that I'll use to output information. I'll go to the MainActivity class. I'll expand to full screen, and I'll start in the onCreate method, after the existing code. In order to work with internal files, the first step is to create an instance of the file class. This is the same file class that's used in all Java code.

It represents either a directory or file, and in this case it will represent the internal files directory for the current application. You get it by calling a method called getFilesDir. I'll create a new File object, which I'll name f. For the import, I'll select the file class from java.io. I'll name the object f and I'll get its value from getFilesDir. Next, I'll create a string variable that I'll name path, and I'll get its value by calling the file object getAbsolutePath.

I'm going to show you exactly where these files are placed on your device or in you emulator. Next, I'll use my UIHelper class and I'll call the displayText method. I'll pass in this to reference the current activity, R.id.textView1 as the textView object I want to use to display the text, and then the path. I'll save my changes, and I'll run the application in the emulator. As the application opens, it gets a reference to the internal files directory and displays the location at the bottom of the activity. It's /data/data and then the package for the application and then the files folder.

When you're working in the emulator, you can actually see this folder. I'll go back to Eclipse and I'll go to the DDMS perspective. From there, I'll go to the File Explorer tab. I'll open the data folder and then from there, go to the data subfolder. I'll expand the size of this column so I can see all of the packages. I'll scroll down and find my application package. I'll open that, and there is the files folder. And right now it's empty.

If you try to do the same thing on an actual device, it probably won't work, unless you've gained root access to the device, or, as it's mostly known, "rooted the device" and gotten permission to see these directories. But in the emulator, you have complete access, and you can see exactly what's going on. So now I'll go back to my coding perspective and I'll go to a method stub that I've created called createFile. This method would be called when the user clicks the createFile button.

The first step will be to retrieve a String Value that the user enters, through an editText object that's a part of the layout. So I'll create a string that I'll call text, and I'll use my UIHelper class, and I'll call the getText method. I'll pass in this and then the resource ID of my editText object R.id.editText1. So now I have a value that I can add to a file. I'm going to use an instance of the class FileOutputStream.

I'll type the beginning of the class name, FileOutputStream. I'll name the object fos, and I'll call a method called openFileOutput. You pass in the name of the file you want create. You don't need to include a file extension, but you can if you want. I'll call it simply myfile.txt. And then I'll set the mode to MODE_PRIVATE. At this point, you're working with file io and you might be throwing exceptions, so you'll be calling methods that require throwing an exception or surrounding the code with a try-catch block.

To make things simple, I'm just going to add a throws declaration to the current method. The name of the class will be FileNotFoundException. and it's a part of the java.io package. Next, I'll write to the file. I'll move the cursor after the code that's creating the OutputStream, and I'll call the method fos.write. There are a few versions of this method. I'm going to pass in the one that takes an array of bytes. And then I'll get the array of bytes by calling the text object, and it's getBytes method.

When you're working with a FileOutputStream and a string, you're working with classes that were a part of the standard Java Toolkit, not anything that's unique to Android. Then when I'm done, I need to make sure I close the FileOutputStream, so I'll call fos.close. And finally, I need to let the user know that the action was taken, so I'll call my UIHelper.displayText method, I'll pass in this, the textView ID, and a literal string of File written to disk.

I'm still getting errors, so once again, I'll go and do a quick fix. I'll click on an error icon and once again call Add throws declaration, and notice that the name of my exception class was changed, not added. It's now IOException, and that will cover all the possible exceptions that might occur in this method. I'll save my changes, and I'll run the application in the emulator. When the application opens, I'll type some text.

I'll type "Looking forward to visiting California." I'll click the Create file button and I see the message that the file was written to disk. I'll go back to Eclipse, to the DDMS view, and there's the file. It was added to my disk and placed in the files folder. And again, I can see it easily in the emulator, but you might not be able to do the same thing with the real device. So now let's look at the code that you need to read the file. I'll go back to my Editing perspective.

I've named mine Android. And I'll go to the method stub readFile. I used the FileOutputStream to create the file, so I'll use a FileInputStream to read it. I'll create an instance of FileInputStream, which I'll call fis, and I'll get its reference with openFileInput. And I'll pass in the same string name: myfile.txt. And you could a constant for that if you prefer. Now with the file open, I'll use some pretty standard Java code to read the contents of the file into memory.

I'll create a BufferedInputStream object, which I'll call bis, and I'll instantiate it with its constructor method, and I'll pass in the fis, or FileInputStream. Now I can read the file efficiently. Next, I'll create a StringBuffer object, which I'll name b, and I'll instantiate it with the StringBuffer constructor method. I'll use the StringBuffer to read one character at a time from the stream. I'll do a loop. I'll type the key word while and press Ctrl+Spaceb, and choose a while loop with a condition.

I'll set the condition using the available method of the BufferedInputStream. I'll ask the question, are there any characters available, with bis.available is not equal to zero? Each time you call the available method, you are queuing up another character, and then you can read the character calling the Read method. Within the while loop, I'll create a char variable, which I'll name c, and I'll call bis.read.

And then I'll press Command+1 on Mac or Ctrl+1 on Windows and do a quick fix to add the cast to char. Then I'll take that char value, or character, and I'll append it to the buffer, calling b.append, and I'll pass in the character. Notice that once again, just like in the createFile method, I'm getting warnings that there are exceptions that might be thrown. I'll do a quick fix on one of them and add a throws declaration, and that clears all of those errors.

So now I've read the string into memory, and I'm ready to display it to the user. And for that, I'll once again use my UIHelper class and its displayText method. I'll pass in this, the I.D. of the textView object R.id.textView1, and the toString method of the Buffer object. To make sure that I've completely cleaned up, I'll call the Close method of the BufferedInputStream and FileOutputStream. And I'll call them in reverse order from how I opened them.

I'll call bis.close and fis.close. I'll save my changes, and I'll run the application, and when the application opens in the emulator, I'll click the Read file button and I see the message Looking forward to visiting California. The important thing here is that the creating and the reading of the file were in two application sessions. The data is persisting on disk because I'm saving it using these FileInput and Output methods.

And again, I'm using arbitrary text here, but in the next couple of videos, I'll show you how you can use these tools to save and read structured data using JSON and XML.

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.