Android dialog to choose a directory or file based on AlertDialog

This dialog could be used to let the user choose a file or directory. Since it is based on AlertDialog it doesn’t have to be instantiated through startActivity() and therefore could be used, for example, in a PrederenceDialog subclass. The provided code only selects the directories, but it is easy to modify it to select the specific files as well. This code is used in the Ulduzsoft Karaoke Player. Apache license.

/*
 * Copyright (C) 2011-2012 George Yunaev
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 */
public class DialogChooseDirectory implements OnItemClickListener, OnClickListener
{
	public interface Result
	{
		void onChooseDirectory( String dir );
	}

	List<File> m_entries = new ArrayList< File >();
	File m_currentDir;
	Context	m_context;
	AlertDialog m_alertDialog;
	ListView m_list;
	Result m_result = null;

	public class DirAdapter extends ArrayAdapter< File >
	{
		public DirAdapter( int resid )
		{
			super( m_context, resid, m_entries );
		}

		// This function is called to show each view item
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			TextView textview = (TextView) super.getView( position, convertView, parent );

			if ( m_entries.get(position) == null )
			{
				textview.setText( ".." );
				textview.setCompoundDrawablesWithIntrinsicBounds( m_context.getResources().getDrawable( R.drawable.icon_parentdir ), null, null, null );
			}
			else
			{
				textview.setText( m_entries.get(position).getName() );
				textview.setCompoundDrawablesWithIntrinsicBounds( m_context.getResources().getDrawable( R.drawable.fileicon_dir ), null, null, null );
			}

			return textview;
		}
	}

	private void listDirs()
	{
		m_entries.clear();

		// Get files
		File[] files = m_currentDir.listFiles();

		// Add the ".." entry
		if ( m_currentDir.getParent() != null )
			m_entries.add( new File("..") );

		if ( files != null )
		{
			for ( File file : files )
			{
				if ( !file.isDirectory() )
					continue;

				m_entries.add( file );
			}
		}

		Collections.sort( m_entries, new Comparator<File>() { 
				public int compare(File f1, File f2)
				{
					return f1.getName().toLowerCase().compareTo( f2.getName().toLowerCase() );
				}
		} );
	}

	public DialogChooseDirectory( Context ctx, Result res, String startDir )
	{
		m_context = ctx;
		m_result = res;

		if ( startDir != null )
			m_currentDir = new File( startDir );
		else
			m_currentDir = Environment.getExternalStorageDirectory();

		listDirs();
		DirAdapter adapter = new DirAdapter( R.layout.listitem_row_textview );

		AlertDialog.Builder builder = new AlertDialog.Builder( ctx );
		builder.setTitle( R.string.dlg_choosedir_title );
		builder.setAdapter( adapter, this );

		builder.setPositiveButton( "Ok", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	   if ( m_result != null )
	        		   m_result.onChooseDirectory( m_currentDir.getAbsolutePath() );
	        	   dialog.dismiss();
	           }
	       });

		builder.setNegativeButton( "Cancel", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	                dialog.cancel();
	           }
	       });

		AlertDialog m_alertDialog = builder.create();
		m_list = m_alertDialog.getListView();
		m_list.setOnItemClickListener( this );
		m_alertDialog.show();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View list, int pos, long id )
	{
		if ( pos < 0 || pos >= m_entries.size() )
			return;

		if ( m_entries.get( pos ).getName().equals( ".." ) )
			m_currentDir = m_currentDir.getParentFile();
		else
			m_currentDir = m_entries.get( pos );

		listDirs();
		DirAdapter adapter = new DirAdapter( R.layout.listitem_row_textview );
		m_list.setAdapter( adapter );
	}

	public void onClick(DialogInterface dialog, int which)
	{
	}
}
This entry was posted in Uncategorized.

4 Responses to Android dialog to choose a directory or file based on AlertDialog

  1. Pingback: 【未解决】Android中实现对应的文件夹选择 | 在路上

  2. Pingback: Saving files to the SD Card. : Android Community - For Application Development

  3. Aditya Sagam says:

    Could you please explain the code for ANdroid file Dialog.I am new to Android programming and I understanding it is difficult for me.Thanx for the code.

  4. zeray says:

    it is not clear for me. would you help.I want to implement an android file chooser dialog.That returns selected file

Leave a Reply to Aditya Sagam Cancel reply

Your email address will not be published. Required fields are marked *


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/ulduzs/public_html/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048