Mark
Mark

Reputation: 95

How do I use System.IO to use ListView to show folders/Files on xamarin.android?

So this is a follow up to a previous question I asked Here

After following Jasons advice, I did a little resurch to use System.IO to use a listview to show folders on android.

I have the following example from the microsoft website...

    class PublicListViews : ListActivity
{
    public string ListCreate(string path)
    {

        ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.list_item, countries);

        ListView.TextFilterEnabled = true;

        ListView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args)
        {
            Toast.MakeText(Application, ((TextView)args.View).Text, ToastLength.Short).Show();
        };
        return path;
    }
}

From what I understand this line....(this, Resource.Layout.list_item, countries); will use the list_item.xml in the resourses folder in the android project and countries is an array on countries that will be listed.

And I have also found the following code to get the directories and files...

        public static void ProcessDirectory(string targetDirectory)
    {
        // Process the list of files found in the directory.
        string[] fileEntries = Directory.GetFiles(targetDirectory);
        foreach (string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach (string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

    // Insert logic for processing found files here.
    public static void ProcessFile(string path)
    {
        Console.WriteLine("Processed file '{0}'.", path);
    }

Could anyone help me on the implementation of listing the folders/files using the ListAdaptor, and how to call it via the MainPage.xaml?

Mark.

Upvotes: 0

Views: 765

Answers (1)

Cherry Bu - MSFT
Cherry Bu - MSFT

Reputation: 10346

According to your description, I guess that you want to get files from a folder, then display these files path in ListView in xamarin.android? Am I right?

If yes, I create simple that you can take a look:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content" 
    android:id="@+id/listView1"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content" 
    android:text="get files" android:id="@+id/button1"/>
</LinearLayout>

 public class MainActivity : AppCompatActivity
{
    private ListView listview1;
    private Button button1;
    private List<string> files;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);

        listview1 = FindViewById<ListView>(Resource.Id.listView1);
        button1 = FindViewById<Button>(Resource.Id.button1);
        files = new List<string>();
        button1.Click += delegate
          {
              getpermission();
              //var targetdic = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/testfolder";
              var targetdic = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "testfolder";
              if(Directory.Exists(targetdic))
              {
                  files = DirSearch(targetdic);

                  listview1.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, files);

                  listview1.ItemClick += (s, e) =>
                  {
                      var t = files[e.Position];
                      Android.Widget.Toast.MakeText(this, t, Android.Widget.ToastLength.Long).Show();
                  };
              }

          };
    }

    private void getpermission()
    {
        if (ActivityCompat.CheckSelfPermission(this, Android.Manifest.Permission.ReadExternalStorage) != Android.Content.PM.Permission.Granted)
        {

            ActivityCompat.RequestPermissions(this, new string[] { Android.Manifest.Permission.ReadExternalStorage }, 1);
            return;
        }
    }

    private List<String> DirSearch(string sDir)
    {
        List<string> folders = new List<string>();
        try
        {
            foreach (string f in Directory.GetFiles(sDir))
            {
                folders.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                folders.AddRange(DirSearch(d));
            }
        }
        catch (System.Exception excpt)
        {

        }

        return folders;
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Please don't forget to request READ_EXTERNAL_STORAGE permission

Upvotes: 1

Related Questions