andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Building an Android FileBrowser (list-based) !

Goto page Previous  1, 2, 3  Next
 
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials
Author Message
bjreddi
Junior Developer
Junior Developer


Joined: 03 Apr 2008
Posts: 17

PostPosted: Wed Apr 09, 2008 2:01 pm    Post subject: Reply with quote

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()
Back to top
View user's profile Send private message
Stephen.Ada
Junior Developer
Junior Developer


Joined: 10 Mar 2008
Posts: 10

PostPosted: Thu Apr 10, 2008 8:18 pm    Post subject: Reply with quote

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)
Back to top
View user's profile Send private message Send e-mail Visit poster's website
nikRbokR
Freshman
Freshman


Joined: 11 Apr 2008
Posts: 4
Location: United States

PostPosted: Sat Apr 19, 2008 6:14 am    Post subject: Reply with quote

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.
Back to top
View user's profile Send private message
nikRbokR
Freshman
Freshman


Joined: 11 Apr 2008
Posts: 4
Location: United States

PostPosted: Tue Apr 29, 2008 11:28 pm    Post subject: Reply with quote

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

anything would b greatly appreciated

thanks!

_________________
Let's Go Sharks!!!
Nabby for Vezina.
Back to top
View user's profile Send private message
pentace
Junior Developer
Junior Developer


Joined: 22 Oct 2008
Posts: 19

PostPosted: Wed Oct 22, 2008 2:27 pm    Post subject: android os 1.0 Reply with quote

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:
    Intent myIntent = new Intent(android.content.Intent.VIEW_ACTION,


error: Android intent VIEW_ACTION could not be resolved


Code:
               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:
 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?
Back to top
View user's profile Send private message
sr
Freshman
Freshman


Joined: 28 Oct 2008
Posts: 3

PostPosted: Tue Oct 28, 2008 3:47 pm    Post subject: Reply with quote

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:
               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 :
Quote:
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:
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!!!
Back to top
View user's profile Send private message
pentace
Junior Developer
Junior Developer


Joined: 22 Oct 2008
Posts: 19

PostPosted: Tue Oct 28, 2008 3:56 pm    Post subject: Reply with quote

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?
Back to top
View user's profile Send private message
sr
Freshman
Freshman


Joined: 28 Oct 2008
Posts: 3

PostPosted: Tue Oct 28, 2008 4:56 pm    Post subject: Reply with quote

Here is the code of the main .java file (other files remain unchanged):
Code:
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.
Back to top
View user's profile Send private message
pentace
Junior Developer
Junior Developer


Joined: 22 Oct 2008
Posts: 19

PostPosted: Tue Oct 28, 2008 5:02 pm    Post subject: Reply with quote

I take it that we are in the same boat.. you are crashing as well when trying to view a file?
Back to top
View user's profile Send private message
sr
Freshman
Freshman


Joined: 28 Oct 2008
Posts: 3

PostPosted: Tue Oct 28, 2008 6:16 pm    Post subject: Reply with quote

i guess we have a begining of answer here:
http://groups.google.com/group/android-developers/browse_thread/thread/ce4d71f4521b80cf/b65adb71d32d552f?lnk=raot
Back to top
View user's profile Send private message
asifk1234
Freshman
Freshman


Joined: 18 Nov 2008
Posts: 5

PostPosted: Tue Nov 18, 2008 12:48 pm    Post subject: Reply with quote

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.
Back to top
View user's profile Send private message
NightHawk
Once Poster
Once Poster


Joined: 16 Dec 2008
Posts: 1
Location: Washington, DC

PostPosted: Tue Dec 16, 2008 9:23 pm    Post subject: Reply with quote

Thank you very much for the tutorial, it was very helpful. Very Happy

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?
Back to top
View user's profile Send private message
TheChosen
Experienced Developer
Experienced Developer


Joined: 06 Jan 2009
Posts: 62
Location: Germany

PostPosted: Tue Jan 06, 2009 7:25 pm    Post subject: Reply with quote

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:

Java:

package org.impressive.artworx.android.filebrowser;

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.util.Log;
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 mDisplayMode = DISPLAYMODE.ABSOLUTE;
     private ArrayList<String> mDirectoryEntries = new ArrayList<String>();
     private File mCurrentDirectory = new File("/");
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // setContentView() gets called within the next line,
        // so we do not need it here.
        browseToRoot();
    }
   
    /**
     * This method browses to the root-directory of the file-system.
     */

    private void browseToRoot()
    {
     browseTo(new File("/"));
    }
   
    /**
     * Method browses to the given directory and either lists its files or asks the
     * user to open the file if it is not a directory but a file instead.
     *
     * @param dir the file or directory to browse to
     */

    private void browseTo(final File dir)
    {
     if(dir.isDirectory())
     {
          mCurrentDirectory = dir;
          fill(mCurrentDirectory.listFiles());
     }
     else
     {
          OnClickListener okButtonListener = new OnClickListener()
          {
               @Override
               public void onClick(DialogInterface arg0, int arg1)
               {
                    // Starts an intent to view the file that was clicked...
                    openFile(dir);
               }
          };
          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"+ dir.getName())
            .setPositiveButton("OK", okButtonListener)
            .setNegativeButton("Cancel", cancelButtonListener)
            .show();
     }
    }
   
    /**
     * Fills the list view with the file path (relative or absolut).
     *
     * @param files the files to be shown
     */

    private void fill(File[] files)
    {
        this.mDirectoryEntries.clear();
       
        // Add the "." == "current directory"
        // and the ".." == 'Up one level'
        this.mDirectoryEntries.add(getString(R.string.current_level));      
        if(this.mCurrentDirectory.getParent() != null)
             this.mDirectoryEntries.add(getString(R.string.up_one_level));
       
        switch(this.mDisplayMode)
        {
             case ABSOLUTE:
                  for (File file : files)
                  {
                       this.mDirectoryEntries.add(file.getPath());
                  }
                  break;
             case RELATIVE: // On relative Mode, we have to substract the current-path from the beginning
                  int currentPathStringLenght = this.mCurrentDirectory.getAbsolutePath().length();
                  for (File file : files)
                  {
                       this.mDirectoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
                  }
                  break;
        }
       
        // create an array list adapter and set it as the view
        ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                R.layout.file_row, this.mDirectoryEntries);
        this.setListAdapter(directoryList);
    }
       
    /**
     * Sends an intent to open the given file.
     *
     * @param f the file to be opened
     */

    private void openFile(File f)
    {
     // Create an Intent
     Intent intent = new Intent();
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     intent.setAction(android.content.Intent.ACTION_VIEW);
     
     // Category where the App should be searched
//        String category = new String("android.intent.category.DEFAULT");
     
     // Setting up the data and the type for the intent
     String type = getMIMEType(f);
     intent.setDataAndType(Uri.fromFile(f), type);
               
     // will start the activtiy found by android or show a dialog to select one
     startActivity(intent);
    }
   
    /**
     * Returns the MIME type for the given file.
     *
     * @param f the file for which you want to determine the MIME type
     * @return the detected MIME type
     */

    private String getMIMEType(File f)
    {
     String end = f.getName().substring(f.getName().lastIndexOf(".")+1, f.getName().length()).toLowerCase();
     String type = "";
     if(end.equals("mp3") || end.equals("aac") || end.equals("aac") || end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) type = "audio";
     else if(end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg")) type = "image";
     
     type += "/*";
     return type;
    }
   
    /**
     * This function browses up one level according to the field: mCurrentDirectory.
     */

    private void upOneLevel()
    {
         if(this.mCurrentDirectory.getParent() != null)
              this.browseTo(this.mCurrentDirectory.getParentFile());
    }
   
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
     int selectionRowID = position;
        String selectedFileString = this.mDirectoryEntries.get(selectionRowID);
        if (selectedFileString.equals(getString(R.string.current_level)))
        {
             // Refresh
             this.browseTo(this.mCurrentDirectory);
        } else if(selectedFileString.equals(getString(R.string.up_one_level)))
        {
             this.upOneLevel();
        }
        else
        {
             File clickedFile = null;
             switch(this.mDisplayMode){
                  case RELATIVE:
                       clickedFile = new File(this.mCurrentDirectory.getAbsolutePath()
                                                          + this.mDirectoryEntries.get(selectionRowID));
                       break;
                  case ABSOLUTE:
                       clickedFile = new File(selectedFileString);
                       break;
             }
             if(clickedFile != null)
             {
                Log.d("AndroidFileBrowser", "File " + clickedFile + " exists? " +
                           clickedFile.exists());
                this.browseTo(clickedFile);
             }
        }
    }
}
Back to top
View user's profile Send private message Visit poster's website
rajendrakumar
Developer
Developer


Joined: 01 Jan 2009
Posts: 40

PostPosted: Thu Jan 08, 2009 12:28 pm    Post subject: HI Reply with quote

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.....
Back to top
View user's profile Send private message
fawx
Junior Developer
Junior Developer


Joined: 18 Aug 2009
Posts: 11

PostPosted: Mon Sep 07, 2009 10:12 am    Post subject: Reply with quote

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.
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials All times are GMT + 1 Hour
Goto page Previous  1, 2, 3  Next
Page 2 of 3

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.