Friday 13 December 2013

Android File or Folder listing from Sd Card | Android File explorer |Android folder listing | List file from sd card android

Hello Friends,
            This sample helps you in browsing your Sd Card folder and files. List all your music folder, file and images programmatically .



Here are the code:

1.ListFolder.Java
package com.android.sdcard.folder;

import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;

import com.example.fileexplorer.R;

import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;

public class ListFolder extends ListActivity {

 private File currentDir;
 private FileArrayAdapter adapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  currentDir = new File("/sdcard/");
  fill(currentDir);
 }

 private void fill(File f) {
  File[] dirs = f.listFiles();
  this.setTitle("Current Dir: " + f.getName());
  List dir = new ArrayList();
  List fls = new ArrayList();
  try {
   for (File ff : dirs) {
    String name = ff.getName();
    Date lastModDate = new Date(ff.lastModified());
    DateFormat formater = DateFormat.getDateTimeInstance();
    String date_modify = formater.format(lastModDate);
    /*
     * Note: Remove this
     * name.equalsIgnoreCase("Covenant and Augment Softsol" if u
     * want to list all ur sd card file and folder
     */
    if (ff.isDirectory()
              && name.equalsIgnoreCase("Covenant and Augment Softsol")) {

     File[] fbuf = ff.listFiles();
     int buf = 0;
     if (fbuf != null) {
      buf = fbuf.length;
     } else
      buf = 0;
     String num_item = String.valueOf(buf);
     if (buf == 0)
      num_item = num_item + " item";
     else
      num_item = num_item + " items";

     // String formated = lastModDate.toString();
     dir.add(new Albumb(ff.getName(), num_item, date_modify, ff
       .getAbsolutePath(), "directory_icon"));
    } else {
     /*
      * Note: Remove this
      * f.getName().equalsIgnoreCase("Covenant and Augment Softsol"
      * if u want to list all ur sd card file and folder
      */
     if (f.getName().equalsIgnoreCase(
       "Covenant and Augment Softsol")) {
      fls.add(new Albumb(ff.getName(), ff.length() + " Byte",
        date_modify, ff.getAbsolutePath(), "file_icon"));
     }
    }
   }
  } catch (Exception e) {

  }
  Collections.sort(dir);
  Collections.sort(fls);
  dir.addAll(fls);
  if (!f.getName().equalsIgnoreCase("sdcard"))
   dir.add(0, new Albumb("..", "Parent Directory", "", f.getParent(),
     "directory_up"));
  adapter = new FileArrayAdapter(ListFolder.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);
  Albumb o = adapter.getItem(position);
  if (o.getImage().equalsIgnoreCase("directory_icon")
    || o.getImage().equalsIgnoreCase("directory_up")) {
   currentDir = new File(o.getPath());
   fill(currentDir);
  }
 }

}



2. Albumb.java

package com.android.sdcard.folder;

 public class Albumb implements Comparable{
 private String name;
 private String data;
 private String date;
 private String path;
 private String image;
 
 public Albumb(String name,String date, String dt, String path, String image)
 {
  this.name = name;
  this.data = date;
  this.path = path; 
  this.image = image;
  
 }
 public String getName()
 {
  return name;
 }
 public String getData()
 {
  return data;
 }
 public String getDate()
 {
  return date;
 }
 public String getPath()
 {
  return path;
 }
 public String getImage() {
  return image;
 }
 
 public int compareTo(Albumb o) {
  if(this.name != null)
   return this.name.toLowerCase().compareTo(o.getName().toLowerCase()); 
  else 
   throw new IllegalArgumentException();
 }
}



3. FileArrayAdapter.java

package com.android.sdcard.folder;

import java.util.List;

import com.example.fileexplorer.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class FileArrayAdapter extends ArrayAdapter {

 private Context c;
 private int id;
 private List items;

 public FileArrayAdapter(Context context, int textViewResourceId,
   List objects) {
  super(context, textViewResourceId, objects);
  c = context;
  id = textViewResourceId;
  items = objects;
 }

 public Albumb 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);
  }

  /* create a new view of my layout and inflate it in the row */
  // convertView = ( RelativeLayout ) inflater.inflate( resource, null );

  final Albumb item = items.get(position);
  if (item != null) {
   TextView t1 = (TextView) v.findViewById(R.id.TextView01);
   TextView t2 = (TextView) v.findViewById(R.id.TextView02);
   TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
   /* Take the ImageView from layout and set the city's image */
   ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);

   String type = item.getImage();
   if (type.equalsIgnoreCase("directory_icon")) {
    String uri = "drawable/" + item.getImage();
    int imageResource = c.getResources().getIdentifier(uri, null,
      c.getPackageName());
    Drawable image = c.getResources().getDrawable(imageResource);
    imageCity.setImageDrawable(image);
   } else {
    Bitmap bmp = BitmapFactory.decodeFile(item.getPath());
    imageCity.setImageBitmap(bmp);
   }
   if (t1 != null)
    t1.setText(item.getName());
   if (t2 != null)
    t2.setText(item.getData());
   if (t3 != null)
    t3.setText(item.getDate());

  }
  return v;
 }

}


4. AndroidManifest,xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fileexplorer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.android.sdcard.folder.ListFolder"
            android:label="@string/title_activity_fileexplorer"
            android:theme="@android:style/Theme.Holo" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



Download complete code here



Hope this will helps some one.
Enjoy Coidng :)

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

8 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. amazing code :) keep it up

    ReplyDelete
  4. Hello Mukesh

    Your code is nice. I used that and it is worked fine. I have one query regrading that.
    I want to display folders of gallery in this way, so how can i do that?

    Please give me any idea...

    ReplyDelete
  5. sir can please tell me how to create fast scroller for sdcard list

    ReplyDelete

 

Copyright @ 2013 Android Developers Blog.