Building an Android FileBrowser (list-based) !

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Postby bjreddi » Wed Apr 09, 2008 2:01 pm

manojo wrote:I don't have the android.net.ContentURI class. Has there been a modification in the specs?

Manojo



Hello,
Just Import

Import com.android.net.Uri;

In the code user Uri.parse instead of ContentURI()
bjreddi
Junior Developer
Junior Developer
 
Posts: 17
Joined: Thu Apr 03, 2008 1:24 pm

Top

Postby Stephen.Ada » Thu Apr 10, 2008 8:18 pm

thanks for providing such a good toturial for novices like me. ^_^

I used rc15 to build the project, and these is something different from the source code perhaps due to different released version of the android sdk.


I shall post the revised code below:

1)private List<String> directoryEntries = new ArrayList<String>();
changed to :private ArrayList<String> directoryEntries = new ArrayList<String>();
I found that ArrayList do not inherit from List

2)in the okbuttonlistener of the browseTo function, the onClick handler should be changed as follows:
Intent myIntent = new Intent(android.content.Intent.VIEW_ACTION,Uri.parse("file://" + aDirectory.getAbsolutePath()));
startActivity(myIntent);

the try-catch clause is removed, and the Uri takes place of ContentURI

3)in the AlertDialog.show function, an iconid should be added as 3th parameter.

4) this.directoryEntries.clear() need to add in the beginning of the fill function in order to remove file list of the previous directory.

5) in onListItemClick handler function:
"int selectionRowID = (int) this.getSelectionRowID() " should be changed to int selectionRowID = (int) this.getSelectedItemPosition(). ( function getSelectionRowID did not appear in the sdk)
Stephen.Ada
Junior Developer
Junior Developer
 
Posts: 10
Joined: Mon Mar 10, 2008 3:18 pm

Postby nikRbokR » Sat Apr 19, 2008 6:14 am

I'm sorry.. I didn't exactly understand the 3rd suggestion in the post above.

Also, could someone please post the code for the latest build of the SDK (w/ android.net.URI and all the other necessary changes?) thanks!

*EDIT: So, I noticed it was missing an int as a 3rd parameter. I added 0, but then i was getting and IndexOutOfBoundsException. Please, let me know exactly what I put!

THanks!
Let's Go Sharks!!!
Nabby for Vezina.
nikRbokR
Freshman
Freshman
 
Posts: 4
Joined: Fri Apr 11, 2008 7:54 pm
Location: United States

Postby nikRbokR » Tue Apr 29, 2008 11:28 pm

^^ would anyone be able to help me w/ my previous post? ^^

anything would b greatly appreciated

thanks!
Let's Go Sharks!!!
Nabby for Vezina.
nikRbokR
Freshman
Freshman
 
Posts: 4
Joined: Fri Apr 11, 2008 7:54 pm
Location: United States

android os 1.0

Postby pentace » Wed Oct 22, 2008 2:27 pm

So i have been trying to get this code to work in both the sdk emulator and the device its self and every example of this code i run into a few problems i was wondering if anyone could help with.

Code: Select all
    Intent myIntent = new Intent(android.content.Intent.VIEW_ACTION,


error: Android intent VIEW_ACTION could not be resolved


Code: Select all
               AlertDialog.[b]show[/b](this,"Question", "Do you want to open that file?n"
                                        + aDirectory.getName(),
                                        "OK", okButtonListener,
                                        "Cancel", cancelButtonListener, false, null);


error: The method show() in the type Dialog is not applicable for the arguments (AndroidFileBrowser, String, String, String, DialogInterface.OnClickListener, String, DialogInterface.OnClickListener, boolean, null)

Code: Select all
int selectionRowID = (int) this.getSelectionRowID();


error: The method getSelectionRowID() is undefined for the type AndroidFileBrowser


I get the same errors on both your code and the code from the linux page tutorial. If i remove those snippits or try to fix them the program does run but of course i cannot open any directories

any ideas?
pentace
Junior Developer
Junior Developer
 
Posts: 19
Joined: Wed Oct 22, 2008 2:16 pm

Postby sr » Tue Oct 28, 2008 3:47 pm

Hi pentace.
I had the same troubles, and tried to solve them:

1. error: Android intent VIEW_ACTION could not be resolved
-> replace by "ACTION_VIEW" instead of "VIEW_ACTION" and delete the catch exception

2. error: The method show() in the type Dialog is not applicable for the arguments (AndroidFileBrowser, String, String, String, DialogInterface.OnClickListener, String, DialogInterface.OnClickListener, boolean, null)
-> the method show() does not exist anymore. I replace it by the method Builder:

Code: Select all
               new AlertDialog.Builder(this)
               .setTitle("Question")
               .setMessage("Do you want to open that file?n"+ aDirectory.getName())
               .setPositiveButton("OK", okButtonListener)
               .setNegativeButton("Cancel", cancelButtonListener)
               .show();



3. error: The method getSelectionRowID() is undefined for the type AndroidFileBrowser
-> the method does not exist anymore too :
ListActivity.getSelectionRowId() removed from API
Detailed Problem Description:
ListActivity.getSelectionRowId() is gone
Solution:
Use ListActivity.getSelectedItemId() instead.
Notes:
Note that this call may also return no selection (-1) more when the emulator or device is in touch mode. More error checking may be required as a result.


New code:
Code: Select all
int selectionRowID = (int) this.getSelectedItemId();



I'm able to run this application on emulator. I can browse directories and files. But I'm not able to open files. "The application has stopped unexpectly"
If you have any idea... thanks!!!
sr
Freshman
Freshman
 
Posts: 3
Joined: Tue Oct 28, 2008 3:34 pm

Top

Postby pentace » Tue Oct 28, 2008 3:56 pm

thanks for the responce i was able to get it fixed eventually but still have issues here and there do u have a copy of the updated files i can look at?
pentace
Junior Developer
Junior Developer
 
Posts: 19
Joined: Wed Oct 22, 2008 2:16 pm

Postby sr » Tue Oct 28, 2008 4:56 pm

Here is the code of the main .java file (other files remain unchanged):
Code: Select all
package [NameOfYourPackage];
import java.io.File;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class AndroidFileBrowser extends ListActivity {
     
     private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; }

     private final DISPLAYMODE displayMode = DISPLAYMODE.ABSOLUTE;
     private ArrayList<String> directoryEntries = new ArrayList<String>();
     private File currentDirectory = new File("/");

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle icicle) {
          super.onCreate(icicle);
          // setContentView() gets called within the next line,
          // so we do not need it here.
          browseToRoot();
     }
     
     /**
      * This function browses to the
      * root-directory of the file-system.
      */
     private void browseToRoot() {
          browseTo(new File("/"));
    }
     
     /**
      * This function browses up one level
      * according to the field: currentDirectory
      */
     private void upOneLevel(){
          if(this.currentDirectory.getParent() != null)
               this.browseTo(this.currentDirectory.getParentFile());
     }
     
     private void browseTo(final File aDirectory){
          if (aDirectory.isDirectory()){
               this.currentDirectory = aDirectory;
               fill(aDirectory.listFiles());
          }else{
               OnClickListener okButtonListener = new OnClickListener(){
                    // @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                         // Lets start an intent to View the file, that was clicked...
                   Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("file://" + aDirectory.getAbsolutePath()));
                   startActivity(myIntent);
                    }
               };
               OnClickListener cancelButtonListener = new OnClickListener(){
                    // @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                         // Do nothing
                    }
               };
               new AlertDialog.Builder(this)
               .setTitle("Question")
               .setMessage("Do you want to open that file?n"+ aDirectory.getName())
               .setPositiveButton("OK", okButtonListener)
               .setNegativeButton("Cancel", cancelButtonListener)
               .show();
          }
     }

     private void fill(File[] files) {
          this.directoryEntries.clear();
           
          // Add the "." and the ".." == 'Up one level'
          try {
               Thread.sleep(10);
          } catch (InterruptedException e1) {
               // TODO Auto-generated catch block
               e1.printStackTrace();
          }
          this.directoryEntries.add(".");
           
          if(this.currentDirectory.getParent() != null)
               this.directoryEntries.add("..");
           
          switch(this.displayMode){
               case ABSOLUTE:
                    for (File file : files){
                         this.directoryEntries.add(file.getPath());
                    }
                    break;
               case RELATIVE: // On relative Mode, we have to add the current-path to the beginning
                    int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();
                    for (File file : files){
                         this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
                    }
                    break;
          }
           
          ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                    R.layout.file_row, this.directoryEntries);
           
          this.setListAdapter(directoryList);
     }

     @Override
     protected void onListItemClick(ListView l, View v, int position, long id) {
          int selectionRowID = (int) this.getSelectedItemId();
          String selectedFileString = this.directoryEntries.get(selectionRowID);
          if (selectedFileString.equals(".")) {
               // Refresh
               this.browseTo(this.currentDirectory);
          } else if(selectedFileString.equals("..")){
               this.upOneLevel();
          } else {
               File clickedFile = null;
               switch(this.displayMode){
                    case RELATIVE:
                         clickedFile = new File(this.currentDirectory.getAbsolutePath()
                                                            + this.directoryEntries.get(selectionRowID));
                         break;
                    case ABSOLUTE:
                         clickedFile = new File(this.directoryEntries.get(selectionRowID));
                         break;
               }
               if(clickedFile != null)
                    this.browseTo(clickedFile);
          }
     }
}


I try to get the ACTION_VIEW work. maybe a permission to add in the manifest.
sr
Freshman
Freshman
 
Posts: 3
Joined: Tue Oct 28, 2008 3:34 pm

Postby pentace » Tue Oct 28, 2008 5:02 pm

I take it that we are in the same boat.. you are crashing as well when trying to view a file?
pentace
Junior Developer
Junior Developer
 
Posts: 19
Joined: Wed Oct 22, 2008 2:16 pm

Postby sr » Tue Oct 28, 2008 6:16 pm

sr
Freshman
Freshman
 
Posts: 3
Joined: Tue Oct 28, 2008 3:34 pm

Postby asifk1234 » Tue Nov 18, 2008 12:48 pm

Hi +-;

Is it possible to convert over listview based filebrowser to gridviewbased(Thumbnail).

I tried using

GridView g = (GridView) findViewById(R.id.grid);
g.setAdapter(new IconifiedTextAdapter(this));

in output I am not gettin g anything.(only blck screen).


Please reply as soon as possible.
asifk1234
Freshman
Freshman
 
Posts: 5
Joined: Tue Nov 18, 2008 8:14 am

Postby NightHawk » Tue Dec 16, 2008 9:23 pm

Thank you very much for the tutorial, it was very helpful. :D

I do have a question though. Can I pad the list items so I can more easily touch the list item without having to use the scroll wheel?
NightHawk
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Dec 16, 2008 9:18 pm
Location: Washington, DC

Postby TheChosen » Tue Jan 06, 2009 7:25 pm

Hi,

I am very new to android development. I got the files to open. For now, only music and image files are recognized but it is not hard to implement other types as well. Just edit the getMIMEType(File f) method.

This is the source of my FileBrowser class:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. package org.impressive.artworx.android.filebrowser;
  3.  
  4.  
  5.  
  6. import java.io.File;
  7.  
  8. import java.util.ArrayList;
  9.  
  10. import android.app.AlertDialog;
  11.  
  12. import android.app.ListActivity;
  13.  
  14. import android.content.DialogInterface;
  15.  
  16. import android.content.Intent;
  17.  
  18. import android.content.DialogInterface.OnClickListener;
  19.  
  20. import android.net.Uri;
  21.  
  22. import android.os.Bundle;
  23.  
  24. import android.util.Log;
  25.  
  26. import android.view.View;
  27.  
  28. import android.widget.ArrayAdapter;
  29.  
  30. import android.widget.ListView;
  31.  
  32.  
  33.  
  34. public class AndroidFileBrowser extends ListActivity
  35.  
  36. {
  37.  
  38.         private enum DISPLAYMODE{ ABSOLUTE, RELATIVE};
  39.  
  40.         private final DISPLAYMODE mDisplayMode = DISPLAYMODE.ABSOLUTE;
  41.  
  42.         private ArrayList<String> mDirectoryEntries = new ArrayList<String>();
  43.  
  44.         private File mCurrentDirectory = new File("/");
  45.  
  46.        
  47.  
  48.     /** Called when the activity is first created. */
  49.  
  50.     @Override
  51.  
  52.     public void onCreate(Bundle savedInstanceState)
  53.  
  54.     {
  55.  
  56.         super.onCreate(savedInstanceState);
  57.  
  58.         // setContentView() gets called within the next line,
  59.  
  60.         // so we do not need it here.
  61.  
  62.         browseToRoot();
  63.  
  64.     }
  65.  
  66.    
  67.  
  68.     /**
  69.  
  70.      * This method browses to the root-directory of the file-system.
  71.  
  72.      */
  73.  
  74.     private void browseToRoot()
  75.  
  76.     {
  77.  
  78.         browseTo(new File("/"));
  79.  
  80.     }
  81.  
  82.    
  83.  
  84.     /**
  85.  
  86.      * Method browses to the given directory and either lists its files or asks the
  87.  
  88.      * user to open the file if it is not a directory but a file instead.
  89.  
  90.      *
  91.  
  92.      * @param dir the file or directory to browse to
  93.  
  94.      */
  95.  
  96.     private void browseTo(final File dir)
  97.  
  98.     {
  99.  
  100.         if(dir.isDirectory())
  101.  
  102.         {
  103.  
  104.                 mCurrentDirectory = dir;
  105.  
  106.                 fill(mCurrentDirectory.listFiles());
  107.  
  108.         }
  109.  
  110.         else
  111.  
  112.         {
  113.  
  114.                 OnClickListener okButtonListener = new OnClickListener()
  115.  
  116.                 {
  117.  
  118.                         @Override
  119.  
  120.                         public void onClick(DialogInterface arg0, int arg1)
  121.  
  122.                         {
  123.  
  124.                                 // Starts an intent to view the file that was clicked...
  125.  
  126.                                 openFile(dir);
  127.  
  128.                         }
  129.  
  130.                 };
  131.  
  132.                 OnClickListener cancelButtonListener = new OnClickListener(){
  133.  
  134.                         @Override
  135.  
  136.                         public void onClick(DialogInterface arg0, int arg1)
  137.  
  138.                         {
  139.  
  140.                                 // Do nothing
  141.  
  142.                         }
  143.  
  144.                 };
  145.  
  146.                 new AlertDialog.Builder(this)
  147.  
  148.             .setTitle("Question")
  149.  
  150.             .setMessage("Do you want to open that file?\n"+ dir.getName())
  151.  
  152.             .setPositiveButton("OK", okButtonListener)
  153.  
  154.             .setNegativeButton("Cancel", cancelButtonListener)
  155.  
  156.             .show();
  157.  
  158.         }
  159.  
  160.     }
  161.  
  162.    
  163.  
  164.     /**
  165.  
  166.      * Fills the list view with the file path (relative or absolut).
  167.  
  168.      *
  169.  
  170.      * @param files the files to be shown
  171.  
  172.      */
  173.  
  174.     private void fill(File[] files)
  175.  
  176.     {
  177.  
  178.         this.mDirectoryEntries.clear();
  179.  
  180.        
  181.  
  182.         // Add the "." == "current directory"
  183.  
  184.         // and the ".." == 'Up one level'
  185.  
  186.         this.mDirectoryEntries.add(getString(R.string.current_level));      
  187.  
  188.         if(this.mCurrentDirectory.getParent() != null)
  189.  
  190.              this.mDirectoryEntries.add(getString(R.string.up_one_level));
  191.  
  192.        
  193.  
  194.         switch(this.mDisplayMode)
  195.  
  196.         {
  197.  
  198.              case ABSOLUTE:
  199.  
  200.                   for (File file : files)
  201.  
  202.                   {
  203.  
  204.                        this.mDirectoryEntries.add(file.getPath());
  205.  
  206.                   }
  207.  
  208.                   break;
  209.  
  210.              case RELATIVE: // On relative Mode, we have to substract the current-path from the beginning
  211.  
  212.                   int currentPathStringLenght = this.mCurrentDirectory.getAbsolutePath().length();
  213.  
  214.                   for (File file : files)
  215.  
  216.                   {
  217.  
  218.                        this.mDirectoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
  219.  
  220.                   }
  221.  
  222.                   break;
  223.  
  224.         }
  225.  
  226.        
  227.  
  228.         // create an array list adapter and set it as the view
  229.  
  230.         ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
  231.  
  232.                 R.layout.file_row, this.mDirectoryEntries);
  233.  
  234.         this.setListAdapter(directoryList);
  235.  
  236.     }
  237.  
  238.        
  239.  
  240.     /**
  241.  
  242.      * Sends an intent to open the given file.
  243.  
  244.      *
  245.  
  246.      * @param f the file to be opened
  247.  
  248.      */
  249.  
  250.     private void openFile(File f)
  251.  
  252.     {
  253.  
  254.         // Create an Intent
  255.  
  256.         Intent intent = new Intent();
  257.  
  258.         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  259.  
  260.         intent.setAction(android.content.Intent.ACTION_VIEW);
  261.  
  262.        
  263.  
  264.         // Category where the App should be searched
  265.  
  266. //      String category = new String("android.intent.category.DEFAULT");
  267.  
  268.        
  269.  
  270.         // Setting up the data and the type for the intent
  271.  
  272.         String type = getMIMEType(f);
  273.  
  274.         intent.setDataAndType(Uri.fromFile(f), type);
  275.  
  276.                        
  277.  
  278.         // will start the activtiy found by android or show a dialog to select one
  279.  
  280.         startActivity(intent);
  281.  
  282.     }
  283.  
  284.    
  285.  
  286.     /**
  287.  
  288.      * Returns the MIME type for the given file.
  289.  
  290.      *
  291.  
  292.      * @param f the file for which you want to determine the MIME type
  293.  
  294.      * @return the detected MIME type
  295.  
  296.      */
  297.  
  298.     private String getMIMEType(File f)
  299.  
  300.     {
  301.  
  302.         String end = f.getName().substring(f.getName().lastIndexOf(".")+1, f.getName().length()).toLowerCase();
  303.  
  304.         String type = "";
  305.  
  306.         if(end.equals("mp3") || end.equals("aac") || end.equals("aac") || end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) type = "audio";
  307.  
  308.         else if(end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg")) type = "image";
  309.  
  310.        
  311.  
  312.         type += "/*";
  313.  
  314.         return type;
  315.  
  316.     }
  317.  
  318.    
  319.  
  320.     /**
  321.  
  322.      * This function browses up one level according to the field: mCurrentDirectory.
  323.  
  324.      */
  325.  
  326.     private void upOneLevel()
  327.  
  328.     {
  329.  
  330.          if(this.mCurrentDirectory.getParent() != null)
  331.  
  332.               this.browseTo(this.mCurrentDirectory.getParentFile());
  333.  
  334.     }
  335.  
  336.    
  337.  
  338.     @Override
  339.  
  340.     protected void onListItemClick(ListView l, View v, int position, long id) {
  341.  
  342.         int selectionRowID = position;
  343.  
  344.         String selectedFileString = this.mDirectoryEntries.get(selectionRowID);
  345.  
  346.         if (selectedFileString.equals(getString(R.string.current_level)))
  347.  
  348.         {
  349.  
  350.              // Refresh
  351.  
  352.              this.browseTo(this.mCurrentDirectory);
  353.  
  354.         } else if(selectedFileString.equals(getString(R.string.up_one_level)))
  355.  
  356.         {
  357.  
  358.              this.upOneLevel();
  359.  
  360.         }
  361.  
  362.         else
  363.  
  364.         {
  365.  
  366.              File clickedFile = null;
  367.  
  368.              switch(this.mDisplayMode){
  369.  
  370.                   case RELATIVE:
  371.  
  372.                        clickedFile = new File(this.mCurrentDirectory.getAbsolutePath()
  373.  
  374.                                                           + this.mDirectoryEntries.get(selectionRowID));
  375.  
  376.                        break;
  377.  
  378.                   case ABSOLUTE:
  379.  
  380.                        clickedFile = new File(selectedFileString);
  381.  
  382.                        break;
  383.  
  384.              }
  385.  
  386.              if(clickedFile != null)
  387.  
  388.              {
  389.  
  390.                  Log.d("AndroidFileBrowser", "File " + clickedFile + " exists? " +
  391.  
  392.                                   clickedFile.exists());
  393.  
  394.                  this.browseTo(clickedFile);
  395.  
  396.              }
  397.  
  398.         }
  399.  
  400.     }
  401.  
  402. }
  403.  
  404.  
Parsed in 0.058 seconds, using GeSHi 1.0.8.4
TheChosen
Experienced Developer
Experienced Developer
 
Posts: 62
Joined: Tue Jan 06, 2009 7:18 pm
Location: Germany

HI

Postby rajendrakumar » Thu Jan 08, 2009 12:28 pm

I am tryin to Update alist view in runtime.

Can you please tel me how to update the list viw at run time....


Bcoz am getting the Array when I enter a text un Edit Text box....


Before that I have listing some other data....

Its like Contact list in nokia Mobile....

IF you enter the string it will display the matching result rt...

its like that.....

Can you please help me out in this.....
rajendrakumar
Developer
Developer
 
Posts: 40
Joined: Thu Jan 01, 2009 7:57 am

Postby fawx » Mon Sep 07, 2009 10:12 am

HI
How do i start an activity from with the onClick(DialogInterface arg0, int arg1) method?

I tried
public void onClick(DialogInterface arg0, int arg1) {
Intent myIntent = new Intent();
myIntent.setClass(this, Read_File.class);
startActivity(new Intent());
}

but it does not work. Can someone please hep me. Thanks.
fawx
Junior Developer
Junior Developer
 
Posts: 11
Joined: Tue Aug 18, 2009 4:34 am

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests