Friday 25 May 2018

Droid asset files

When leveraging assets within an application we have the advantage that we don't need to request permissions within the app manifest for file read; keep in mind that Assets are readonly and cannot be written to, but what we have to make sure is that the asset's build action is marked as "AndroidAsset"


Now that we have our data.txt file let's take a look at our UI

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:a="http://schemas.android.com/apk/res/android"
              a:orientation="vertical" a:layout_width="match_parent"
              a:layout_height="match_parent">
  <EditText a:id="@+id/InputTextBox" a:hint="enter in value"
            a:layout_width="fill_parent" a:layout_height="wrap_content"/>
  <Button a:id="@+id/SaveButton" a:text="Save"
          a:layout_width="fill_parent" a:layout_height="wrap_content"/>
  <Button a:id="@+id/LoadButton" a:text="Load"
          a:layout_width="fill_parent" a:layout_height="wrap_content"/>
  <ListView a:id="@+id/DataListView"
            a:layout_width="fill_parent" a:layout_height="fill_parent" />

</LinearLayout>

simple enough

now compared to accessing the file system working with assets is far simpler, firstly let's take a look at the code needed to read from the assets file

private async Task<ArrayAdapter<string>> GetDataAsync()
{
    var content = String.Empty;
    using (var streamReader = new StreamReader(Assets.Open("data.txt")))
        content = await streamReader.ReadToEndAsync();

    var data = content.Contains(";") ? new List<string>(content.Split(';')) : new List<string>();

    return new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, data);

}

and that's it, the most complicated part is deciding on whether to parse the file, now to save to our list we can only save to it to the adapter, because assets are read-only

private void SaveButton_Click(object sender, EventArgs e)
{
    var value = InputTextBox.Text;
    if (!String.IsNullOrEmpty(InputTextBox.Text))
    {
        DataAdapter.Add(value);
        Toast.MakeText(this, $"added: {value}", ToastLength.Short).Show();
        InputTextBox.Text = String.Empty;
    }

}

however on strategy is to load your assets file into memory then write it to the file system and use that file for reading and writing.