Click here to learn
about this Sponsor:
Home  |  News  |  Articles  |  Polls  |  Forum

Keywords: Match:
Building an Android file browser
by John Lombardo (Nov. 15, 2007)

Android Project Process
Set up the project in Eclipse

The first step is to set the project up in Eclipse.

  1. Start up Eclipse
  2. Right click the package explorer and click on New->Android Project
  3. In the new Project dialog box, fill out the following
    • Project Name: FSExplorer1
    • Package Name: org.lombardos.android.FSExplorer1
    • Activity Name: FileList
    • Application Name: Filesystem Explorer
  4. Click Finish to complete the Project dialog box.

New Android Project
(Click to enlarge)

Display the Root File System

The next step is to modify the FileList so that the files and directories on the root directory are displayed. This is similar to how the Notes are displayed in the Notepad, except we don't get our info from the embedded SQL database, we get it from the file system on the Android phone.

  1. Add a string named "no_files" to res/values/strings.xml. It's value should be "This directory is empty". This string will be displayed when there are no files or subdirectories within a directory.

  2. Create a new layout called directory_list.xml. It should look the same as below. The format of this file is covered step four of the first exercise in the tutorial.
    
          <?xml version="1.0" encoding="utf-8"?>
          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content">
    
            <ListView id="@id/android:list"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"/>
            <TextView id="@id/android:empty"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="@string/no_files"/>
          </LinearLayout>
    
  3. Create another new layout called file_row.xml. It should look the same as below. The format of this file is covered step five of the first exercise in the tutorial.
          <?xml version="1.0" encoding="utf-8"?>
          <TextView id="@+id/text1"
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"/>
    

    This layout is used to display each individual file or subdirectory within a directory.

  4. Modify the onCreate() function in FileList.java so that it reads as so:
    
              public void onCreate(Bundle icicle) {
                  super.onCreate(icicle);
                  setContentView(R.layout.directory_list);
                  fill(new File("/").listFiles());
              }
    
    We changed the first parameter of setContentView() to R.layout.directory_list so that the list of Mp3s would appear instead of the "main" view. We also added a call to the fill() method. We haven't written fill() yet, but we'll get there in a second.

  5. Change the class that FileList extends from "Activity" to "ListActivity". It should look like this:
    
          public class FileList extends ListActivity {
    
  6. Create a private field, items, that holds the items in the current directory. This should go just under the "public class FileList" line.
    
              private List<String> items = null;
    
  7. The private fill() method takes a File[] array, and displays each file name on the screen in the list.
    
          1    private void fill(File[] files) {
          2        items = new ArrayList<String>();
          3        for( File file : files )
          4            items.add(file.getPath());
          5        ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.file_row, items);
          6        setListAdapter(fileList);
          7    }
    
    1. Lines 2-4 take the files[] array and make an ArrayList<String> out of each file's name. "items" is a class field because it will be used later when the user clicks on one of the files or directories.

    2. Line 5 creates an ArrayAdapter<String> out of the items using the file_row layout. This is what marries the list of List<> of files to the list on the screen.
    3. Finally, on line six, the current screen's content is set to the list of file names.
                <>   
  8. You may have to hit Shift-Control-O to Organize Imports.

  9. Save all your files and run. You should have a list of directories on your emulated Android phone.

  10. Click on them and nothing happens -- next step fixes that.
Navigate the Directory Tree

Now that we can see the root directory structure, let's see if we can display some sub directories.

  1. We're going to need some way to navigate back to the root of the tree, or we'll eventually get stuck on a leaf with no way back. A quick solution is to give our users a way to hop all the way back to the root from wherever they are. To implement this, the first step is to add a string to the strings.xml file. The name should be to_top. The value should be "[Back to Top]".

  2. Next we need to add the "to_top" string to the item list in the fill() method. Add this line just after the "items = new ArrayList<String>(); line in the fill method:
    
            items.add(getString(R.string.to_top));
    
    Note that using the getString(R.string.<name>) is preferable to including the string as a final field within your class (or even worse, just putting the string in-line). Moving all of your strings to the resource directory goes a long way toward internationalizing your code if you ever need to do so.

  3. When the user clicks on a list item, we have the opportunity to intercept that click and do something interesting with it. To that end we override the onListItemClick() method of ListActivity. Here's a method that will do nicely:
    
          1    @Override
          2    protected void onListItemClick(ListView l, View v, int position, long id) {
          3        int selectionRowID = (int)getSelectionRowID();
          4        if (selectionRowID==0){
          5            fillWithRoot();
          6        } else {
          7            File file = new File(items.get(selectionRowID));
          8            if (file.isDirectory())
          9                fill(file.listFiles());
          10           else
          11               AlertDialog.show(this, "Not a Directory", "That's a file, not a directory", "Cancel", false);
          12       }
          13   }
    
    Notes:
    • Line 3 reveals which line number the user clicked on.
    • On line five, we display the root of the file system again if the user chose line 0.
    • Line nine descends into the sub directory that the user chose.
    • Line 11 shows how to display a simple error dialog box to the user.

  4. Now we need to create the fillWithRoot() method. It does the same thing as the last line of our onCreate() method.
    
              private void fillWithRoot() {
                  fill(new File("/").listFiles());
              }
    
  5. Don't forget to replace the fill() method in the onCreate() method with fillWithRoot().

The complete source code file for this project, ready for importing into Eclipse, is available for download, here (32K Zip archive)



Return to Article



(Click here for further information)


7 Advantages of D2D Backup
For decades, tape has been the backup medium of choice. But, now, disk-to-disk (D2D) backup is gaining in favor. Learn why you should make the move in this whitepaper.

4 Legal Reasons to Control Internet Access
The Internet is obviously a valuable resource for many organizations. However, many are exposed to legal liability concerns because they fail to control Internet access. Learn if you're safe in this white paper.

Rapidly Resolve J2EE Application Problems
Whether you are in the process of building J2EE applications or have J2EE applications already running in production, you must ensure that they deliver the expected ROI. Learn how in this white paper.

Load Testing 2.0 for Web 2.0
There are many unknowns in stress testing Web 2.0 applications. Find out how to test the performance of Web 2.0 in this white paper.

Build Better Games Online
For the game infrastructure providers, life is complex. Making money from games has become more complicated. Why? Find out in this white paper.

Building a Virtual Infrastructure from Servers to Storage
This white paper discusses the virtual storage solutions that reduce cost, increase storage utilization, and address the challenges of backing up and restoring Server environments.

Gaining Faster Wireless Connections with WiMAX
Welcome to what is quickly becoming the hyperconnected world where anything that would benefit from being connected to the network will be connected. Learn more in this white paper.

Is Your Desktop a Security Threat?
The new wave of sophisticated crimeware not only targets specific companies, but also targets desktops and laptops as backdoor entryways into those business’ operations and resources. Learn how to stay safe in this white paper.

Increasing SAN Reliability by 100 Percent
Storage area networks (SAN) are a strong part of storage plans. Learn how to increase your reliability and uptime by 100 percent in this case study.

 


Got a HOT tip?   please tell us!
Free weekly newsletter
Enter your email...
Click here for a profile of each sponsor:
PLATINUM SPONSORS
GOLD SPONSORS
(Become a sponsor)

ADVERTISEMENT
(Advertise here)

Check out the latest Linux powered...

mobile phones!

other cool
gadgets



BREAKING NEWS

• Linux-friendly SoCs target low-end multimedia
• CompactFlash as a COTS "standard"
• 65nm ARM9 SoCs target PNDs, smartphones
• Motorola Ming A1600 ships
• N810 gains Android installer
• PC/104-Plus board runs Linux on x86 SoC
• Webinars explore embedded Linux development
• Linux video camera geo-tags, writes to SATA drives
• Garmin Nav devices run Gnome Linux
• Ten LiMo phones this month?
• It's a Yankee Doodle Linux phone
• Wind River to host "Developer Day"
• Dev boards gain Linux support
• 802.11n zooms ahead
• Low-power mini-ITX board runs Linux


Most popular stories -- past 30 days:
• World's cheapest Linux-based laptop?
• Ubuntu ported to a PDA
• 64-way chip gains Linux IDE, dev cards, design wins
• Embedded PowerPC dev kits come with Linux
• Rapid time-to-evaluation -- a key goal for silicon providers
• Embedded Linux is doomed. DOOOMED!
• Rugged PDA available with Linux
• Netflix Player runs Linux
• Miniature Linux PC targets military apps
• $7 SoC runs Linux
• Android Developer Challenge announces first-round winners
• Dual-core ARM SoC clocks to 1.2GHz


Linux-Watch headlines:
• Microsoft tactics push India toward Linux
• Bell, SuperMicro sued over GPL
• "Business intelligence" software goes GPL
• Will Atom bomb?
• LF Summit videos posted
• Linux gains "embedded" maintainers
• Virtualization on tap in SLES and RHEL upgrades
• Linux gets security black eye
• Verizon chooses Linux "platform of choice"
• Hats off to Fedora 9


Also visit our sister site:


Sign up for LinuxDevices.com's...

news feed

Home  |  News  |  Articles  |  Polls  |  Forum  |  About  |  Contact
 

Ziff Davis Enterprise Home | Contact Us | Advertise | Link to Us | Reprints | Magazine Subscriptions | Newsletters
Tech RSS Feeds | White Papers | ROI Calculators | Tech Podcasts | Tech Video | VARs | Channel News

Baseline | Careers | Channel Insider | CIO Insight | DesktopLinux | DeviceForge | DevSource | eSeminars |
eWEEK | Enterprise Network Security | LinuxDevices | Linux Watch | Microsoft Watch | Mid-market | Networking | PDF Zone |
Publish | Security IT Hub | Strategic Partner | Web Buyer's Guide | Windows for Devices

Developer Shed | Dev Shed | ASP Free | Dev Articles | Dev Hardware | SEO Chat | Tutorialized | Scripts |
Code Walkers | Web Hosters | Dev Mechanic | Dev Archives | igrep

Use of this site is governed by our Terms of Service and Privacy Policy. Except where otherwise specified, the contents of this site are copyright © 1999-2008 Ziff Davis Enterprise Holdings Inc. All Rights Reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff Davis Enterprise is prohibited. Linux is a registered trademark of Linus Torvalds. All other marks are the property of their respective owners.