• (3 Pages)
  • +
  • 1
  • 2
  • 3

Creating Simple File Chooser

#16 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Posted 07 November 2011 - 07:42 PM

When i run it just crashes why is this happening???
I am using 2.2 and API 8

You think this is the problem?????
Was This Post Helpful? 0
  • +
  • -

#17 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Posted 07 November 2011 - 07:43 PM

That should not be a problem. What errors are you getting in LogCat?
Was This Post Helpful? 0
  • +
  • -

#18 Hellbroth  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 190
  • Joined: 15-August 09

Posted 08 November 2011 - 03:51 AM

It doesn't say anything but apparently it crashes cause i change Active to extends ListActivity.

I even made a new project an just changed that line and it still crashes this is crazy there is no
reason :S
Was This Post Helpful? 0
  • +
  • -

#19 PriskAprilia  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 13-November 11

Posted 13 November 2011 - 09:07 PM

Hi,

Thank you for this amazing tutorial. I have tried out your code.
When I clicked the file, I got a message that file clicked.
How can I get the file path and return the path to the caller ( I mean I'm going to use an button, when the button is clicked the file chooser class will show, and then when a file is chosen the file choose activity will return the path to the caller (main activity)).

How can we specify only particular files can be chosen (with specific extension like .jpg, .png, .tiff, and .bmp ) ? where do to it on the project code?

I need the image path to do some image processing.


Regards,

Priska
Was This Post Helpful? 0
  • +
  • -

#20 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Posted 13 November 2011 - 09:30 PM

to filter for a specific file type you can modify the following method:
private void fill(File f)
    {
        File[]dirs = f.listFiles();
         this.setTitle("Current Dir: "+f.getName());
         List<Option>dir = new ArrayList<Option>();
         List<Option>fls = new ArrayList<Option>();
         try{
             for(File ff: dirs)
             {
                if(ff.isDirectory())
                    dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
                else if( ff.getName().endsWith(".jpg")||ff.getName().endsWith(".png"))// you get the idea...
                {
                    fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
                }
             }
         }catch(Exception e)
         {
             
         }
         Collections.sort(dir);
         Collections.sort(fls);
         dir.addAll(fls);
         if(!f.getName().equalsIgnoreCase("sdcard"))
             dir.add(0,new Option("..","Parent Directory",f.getParent()));
    }



This post has been edited by H3R3T1C: 13 November 2011 - 09:30 PM

Was This Post Helpful? 0
  • +
  • -

#21 PriskAprilia  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 13-November 11

Posted 13 November 2011 - 10:39 PM

I figure it out now.

Thanks for your fast reply :D
Was This Post Helpful? 0
  • +
  • -

#22 gquinet  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 29-January 12

Posted 29 January 2012 - 03:53 AM

Hi, THANKS, it works fine!!

Iwant to add two butttons on the bottom or top of the list, one for going back and one to select the current folder (i'm working in a small files in folder conversion tool), but by extending ListActivity, adding buttons in the layout give me as result to have button on each item! is ther a way to do this? looks i only can do this extending Activity and playing with ScrollView/ListView :(
Was This Post Helpful? 0
  • +
  • -

#23 andolasoft  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 23-February 12

Posted 23 February 2012 - 10:23 PM

Whenever did you use Android Phone?

Use that it's so imaging..
Was This Post Helpful? 0
  • +
  • -

#24 TheChucklingAtom  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 03-March 12

Posted 03 March 2012 - 10:16 PM

Hey, This tutorial was incredibly useful and the only working file chooser I was able to find after a bit of searching. I did have a question however. I was trying to run this after you press a button. It works up until the point when it runs the FileArrayAdapter super constructor, and for some reason terminates there. Almost all the code is the same, all I have changed is the FileChooser is created in the OnCreate and fill is called when the button is pressed. I did walk through the debugger in Netbeans, and that is when I found out it was crashing in FileArrayAdapter. The only error it displays is when I run the app, after I press the button I have set up it displays this "Sorry! The application DictionaryTest(process com.FVCC.CS) has stopped unexpectedly. Please try again." There is nothing that I see that shows up in the debugger window, or any other window. Any ideas why would be appreciated.

Thanks,
The Chuckling Atom
Was This Post Helpful? 0
  • +
  • -

#25 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Posted 04 March 2012 - 11:24 AM

Can you post the code your using?
Was This Post Helpful? 0
  • +
  • -

#26 TheChucklingAtom  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 03-March 12

Posted 04 March 2012 - 09:59 PM

Sure, I can do that. I am new to the whole android development field, but I like to believe I know java decently enough.

package com.FVCC.CS;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity
{
    
    Button addDictionary;
    FileChooser userSelection;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        userSelection = new FileChooser();
        
        addDictionary = (Button) findViewById(R.id.addDictionary);
        
        addDictionary.setonclickListener(new View.onclickListener() {

            public void onclick(View view) {
                addANewDictionary();
            }
        });
    }
    
    public void addANewDictionary()
    {
        userSelection.fill(userSelection.getCurrentDirectory());
    }
}



package com.FVCC.CS;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class FileChooser extends ListActivity{
    
    private File currentDir;
    private FileArrayAdapter adapter;
    
    public FileChooser()
    {
        currentDir = new File("/sdcard/");
    }
    
    public void fill(File f)
    {
    	File[]dirs = f.listFiles();
		 this.setTitle("Current Dir: "+f.getName());
		 List<Option>dir = new ArrayList<Option>();
		 List<Option>fls = new ArrayList<Option>();
		 try{
			 for(File ff: dirs)
			 {
				if(ff.isDirectory())
					dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
				else
				{
					fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
				}
			 }
		 }catch(Exception e)
		 {
			 
		 }
		 Collections.sort(dir);
		 Collections.sort(fls);
		 dir.addAll(fls);
		 if(!f.getName().equalsIgnoreCase("sdcard"))
			 dir.add(0,new Option("..","Parent Directory",f.getParent()));
		 adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_view,dir);
		 this.setListAdapter(adapter);
    }
    @Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Option o = adapter.getItem(position);
		if(o.getData().equalsIgnoreCase("folder")||o.getData().equalsIgnoreCase("parent directory")){
				currentDir = new File(o.getPath());
				fill(currentDir);
		}
		else
		{
			o.getPath();
		}
	}
    private void onFileClick(Option o)
    {
    	Toast.makeText(this, "File Clicked: "+o.getName(), Toast.LENGTH_SHORT).show();
    }
    
    public File getCurrentDirectory()
    {
        return currentDir;
    }
}



package com.FVCC.CS;

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.onclickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 *
 * @author Chuckling Atom
 */

public class FileArrayAdapter extends ArrayAdapter<Option>{
    
        private Context c;
	private int id;
	private List<Option>items;
	
	public FileArrayAdapter(Context context, int textViewResourceId,
			List<Option> objects) {
		super(context, textViewResourceId, objects);
		c = context;
		id = textViewResourceId;
		items = objects;
	}
        
	public Option getItem(int i)
	{
		 return items.get(i);
	}
        
	@Override
        public View getView(int position, View convertView, ViewGroup parent) {
            
               View v = convertView;
               
               if (v == null) {
                   LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                   v = vi.inflate(id, null);
               }
               
               final Option o = items.get(position);
               
               if (o != null) {
                       TextView t1 = (TextView) v.findViewById(R.id.TextView01);
                       TextView t2 = (TextView) v.findViewById(R.id.TextView02);
                       
                       if(t1!=null)
                       {
                       	   t1.setText(o.getName());
                       }
                       if(t2!=null)
                       {                       
                           t2.setText(o.getData());
                       }
                       
               }
               
               return v;
               
       }
         
}



package com.FVCC.CS;

public class Option implements Comparable<Option>{
    
    private String name;
	private String data;
	private String path;
	
	public Option(String n, String d, String p)
	{
		name = n;
		data = d;
		path = p;
	}
	public String getName()
	{
		return name;
	}
	public String getData()
	{
		return data;
	}
	public String getPath()
	{
		return path;
	}
	@Override
	public int compareTo(Option o) {
		if(this.name != null)
                {
			return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
                }
		else
                {
			throw new IllegalArgumentException();
                }
	}
    
}


Was This Post Helpful? 0
  • +
  • -

#27 geo3d  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 13-April 12

Posted 13 April 2012 - 05:34 AM

View PostHellbroth, on 07 November 2011 - 07:42 PM, said:

When i run it just crashes why is this happening???
I am using 2.2 and API 8

You think this is the problem?????


Did you ever get this working on API 8?
Was This Post Helpful? 0
  • +
  • -

#28 Nmidia  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 09-June 12

Posted 09 June 2012 - 06:45 AM

Excellent tutorial, thanks for sharing.

I have been able to implement this with an mp3 file filter and a simple "play" function.

I was wondering, would it be possible to get this set up so that it works with two views. What i'm thinking is that the screen could be split in two, with the left hand view showing the folder tree, the right hand showing the files within the directory that was clicked.

Any idea how to do that?
Was This Post Helpful? 0
  • +
  • -

#29 H3R3T1C  Icon User is offline

  • Android Expert
  • member icon

Reputation: 277
  • View blog
  • Posts: 757
  • Joined: 30-March 07

Posted 09 June 2012 - 07:26 AM

Look into using fragments! http://www.linuxforu...-fragments-api/
Was This Post Helpful? 0
  • +
  • -

#30 Nmidia  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 09-June 12

Posted 09 June 2012 - 01:43 PM

View PostH3R3T1C, on 09 June 2012 - 07:26 AM, said:

Look into using fragments! http://www.linuxforu...-fragments-api/



Hi, thanks for the tip. I tried to follow this through, but being a complete noob i failed.

I've also tried to set up file_view.xml with a table , with two linear layouts within it, containing two lists.

I've added a call in the main Java section that scan the currentDir for just mp3 files. This is called after the first Fill, and uses a second ArrayAdapter. However, something i've done doesn't work! I don't get anything returned in the list.

file_view.xml

 
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:stretchColumns="*">
        
<TableRow 
    android:id="@+id/tableRow1"
    android:layout_width="0dp"
    android:layout_height="fill_parent" 
    android:layout_weight = "9">


<LinearLayout
   android:id="@+id/Linear1"
  android:layout_height="wrap_content" 
  android:orientation="vertical" 
  android:layout_width="fill_parent">
<TextView 
    android:text="@+id/TextView01" 
    android:id="@+id/TextView01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:singleLine="true" 
    android:textStyle="bold" 
    android:layout_marginTop="5dip" 
    android:layout_marginLeft="5dip">
    
</TextView>

<TextView 
    android:text="@+id/TextView02" 
    android:id="@+id/TextView02" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="10dip">
    
</TextView>
</LinearLayout>

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/Linear2"
  android:layout_height="wrap_content" 
  android:orientation="vertical" 
  android:layout_width="fill_parent">
<TextView 
    android:text="@+id/TextView03" 
    android:id="@+id/TextView03" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:singleLine="true" 
    android:textStyle="bold" 
    android:layout_marginTop="5dip" 
    android:layout_marginLeft="5dip">
    
</TextView>

<TextView 
    android:text="@+id/TextView04" 
    android:id="@+id/TextView04" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="10dip">
    
</TextView>

</LinearLayout>

</TableRow>

<TableRow 
    android:id="@+id/tableRow2"
    android:layout_width="0dp"
    android:layout_height="fill_parent" 
    android:layout_weight = "1">
</TableRow>

</TableLayout> 


FileChooser.java
public class FileChooser extends ListActivity implements OnPreparedListener, MediaController.MediaPlayerControl{
	/** Called when the activity is first created. */
	private File currentDir;
    private FileArrayAdapter adapter;
    private FileArrayAdapter2 adapter2;
    
    
    public static final String AUDIO_FILE_NAME = "audioFileName";

	  private MediaPlayer mediaPlayer;
	  private MediaController mediaController;
	 

	  private Handler handler = new Handler();    
    
    @Override
	    public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    currentDir = new File(Environment.getExternalStorageDirectory(),"");
	    
	            fill(currentDir);
	            currentDir = new File("/sdcard/");  
	            fill_detail(currentDir);
	        }


	    private void fill(File f) {	    /** build array of all files and dirs in currentDir */
	    
	    	File[]dirs = f.listFiles();
	  	             this.setTitle("Current Dir: "+f.getName());
	  	           /** Build the dir list array */
	  	             List<Option>dir = new ArrayList<Option>();
	   	           /** Build the files list array */  
	  	             List<Option>fls = new ArrayList<Option>();
	   	             try{
	   	                 for(File ff: dirs)
	   	                 {
	   	                    if(ff.isDirectory())
	   	                        /** Scan the directory to see if it has mp3's */
	   	                    	
	   	                    	dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
	  	                    else
	   	                    {
	   	                    /** Only Add MP3's to the list    */
	  	                       String filename=ff.getName();
	  	                       String ext = filename.substring(filename.lastIndexOf('.')+1, filename.length());
	  	                       if(ext.equals("MP3")||ext.equals("mp3")||ext.equals("Mp3")||ext.equals("mP3"))
	  	                    	
	  	                    	fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
	  	                    	
	  	                    		 }
	   	                 }
	   	                  
	   	             }
	   	             
	   	             catch(Exception e)
	   
	             {
	   
	                  
	   
	             }
	   	  /** Sort the dir list alphabetically */           
	             Collections.sort(dir);
	      /** sort the files list alphabetically */
	             Collections.sort(fls);
	   
	             dir.addAll(fls);
	  
	             if(!f.getName().equalsIgnoreCase("sdcard"))
	     /** Add a link to the parent directory at the top of the list */
	                 dir.add(0,new Option("..","Parent Directory",f.getParent()));
	             adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_view,dir);
	      	   
	              this.setListAdapter(adapter); 
	             
	             
	             
	        }

	    Stack<File> dirStack = new Stack<File>();
	    
	    
	    
	    
	    private void fill_detail(File f_detail) {
		    /** build array of all files and dirs in currentDir */
		    
		    	File[]dirs_detail = f_detail.listFiles();
		  	             
		  	           /** Build the dir list array */
		  	             List<Option>dir_detail = new ArrayList<Option>();
		   	           /** Build the files list array */  
		  	             List<Option>fls_detail = new ArrayList<Option>();
		   	             try{
		   	                 for(File ff_detail: dirs_detail)
		   	                 {
		   	                    if(ff_detail.isDirectory())
		   	                        /** Scan the directory to see if it has mp3's 
		   	                    	
		   	                    	dir_detail.add(new Option(ff_detail.getName(),"Folder",ff_detail.getAbsolutePath())); */
		   	                    	;
		  	                    else
		   	                    {
		   	                    /** Only Add MP3's to the list    */
		  	                       String filename_detail=ff_detail.getName();
		  	                       String ext_detail = filename_detail.substring(filename_detail.lastIndexOf('.')+1, filename_detail.length());
		  	                       if(ext_detail.equals("MP3")||ext_detail.equals("mp3")||ext_detail.equals("Mp3")||ext_detail.equals("mP3"))
		  	                    	
		  	                    	fls_detail.add(new Option(ff_detail.getName(),"File Size: "+ff_detail.length(),ff_detail.getAbsolutePath()));
		  	                    	
		  	                    		 }
		   	                 }
		   	                  
		   	             }
		   	             
		   	             catch(Exception e)
		   
		             {
		   
		                  
		   
		             }
		   	  /** Sort the dir list alphabetically            
		       *      Collections.sort(dir_detail); */
		      /** sort the files list alphabetically */
		             Collections.sort(fls_detail);
		   
		             dir_detail.addAll(fls_detail);
		  
		             if(!f_detail.getName().equalsIgnoreCase("sdcard"))
		     /** Add a link to the parent directory at the top of the list 
		                 dir_detail.add(0,new Option("..","Parent Directory",f_detail.getParent())); */
		             adapter2 = new FileArrayAdapter2(FileChooser.this,R.layout.file_view,dir_detail);
		      	   
		              this.setListAdapter(adapter2);
		        }
	    
	    
	    @Override
	    
	    protected void onListItemClick(ListView l, View v, int position, long id) {
	    
	        // TODO Auto-generated method stub
	    
	        super.onListItemClick(l, v, position, id);
	    
	        Option o = adapter.getItem(position);
	    
	        if(o.getData().equalsIgnoreCase("folder")){
	    
	                dirStack.push(currentDir);
	    
	            currentDir = new File(o.getPath());
	    
	            fill(currentDir);
	           fill_detail(currentDir); 
	            }
	    
	        else
	        if(o.getData().equalsIgnoreCase("parent directory")){
	    
	            currentDir = dirStack.pop();
	    	                fill(currentDir);
	    	                fill_detail(currentDir); 
	            }
	        				
	   	        else
	    	        {
	    	            onFileClick(o);
	    
	        }
	    
	    }

	    public void onBackPressed() {
	    	
	    	     if (dirStack.size() == 0)
	    		         {
	    	  	         finish();
	    	   	         return;
	    	  	        }
	    	  	     currentDir = dirStack.pop();
	    	  	     fill(currentDir);
	    	  	   /**  fill_detail(currentDir); */
	    	    	 }

	    private void onFileClick(Option o)
	       {
	       
	     playSong(o.getPath());
	        }

	    private void playSong(String songPath) {
	    	
		    mediaPlayer = new MediaPlayer();
		    mediaPlayer.setOnPreparedListener(this);

		    mediaController = new MediaController(this);

		    try {
		      mediaPlayer.setDataSource(songPath);
		      mediaPlayer.prepare();
		      mediaPlayer.start();
		    } catch (IOException e) {
		      
		    }

		  } 



FileArrayAdapter2 is identical to FileArrayAdapter as set out here, but throws to TextView03 and TextView04


Any help greatly appreciated

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3