List files from internal memory in the ListView

2

I want to create an app that when clicking on the "Lists" option, create a list using ListView based on the files found in a particular folder (path)     

asked by anonymous 29.04.2015 / 00:03

1 answer

1

Thinking a little bit, you can make multiple internal and external device listings in one application using Environment and Context .

First, as an example, you need to give your directories permission to manifest.xml if you want to do a listing of external files using READ_EXTERNAL_STORAGE . If by chance you use getRootDirectory() this permission is not required. And if you're using Android API 6.0 + , you'll have to read a little more about Requesting Permissions at Run Time .

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

In your main.xml , you will enter your ListView so that all files are listed:

<ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
</ListView>

And finally in your class Main is going to do this:

    ListView listView ;
    ArrayList<String> list = new ArrayList<String>();
    listView = (ListView) findViewById(R.id.list);

    String path = Environment.getRootDirectory().toString();
    Log.d("Files", "Path: " + path);
    File directory = new File(path);
    File[] files = directory.listFiles();
    Log.d("Files", "Size: "+ files.length);
    for (int i = 0; i < files.length; i++)
    {
        list.add(files[i].getName());
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, list);
    // Assign adapter to ListView
    listView.setAdapter(adapter);

If you want to list other directories in a specific folder, just put the folder name in your path :

String path = Environment.getRootDirectory().toString()+"/"+diretorioEspecifico;
    
16.10.2016 / 16:01