17

I have set a FileProvider with the following res/xml/file_paths.xml:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="suggestions" path="Android/data/com.example.app.dev/files/suggestions" />
</paths>

The problem is, I have many product flavors that change the applicationId. Is there any way to replace that value with the proper applicationId without creating a filepath for each product flavor? Like replacing a tag like this Android/data/{appId}/files/suggestions? Or even using a relative path... (I've tried everything but only this full path worked).

Cœur
  • 37,241
  • 25
  • 195
  • 267
Fabricio
  • 7,705
  • 9
  • 52
  • 87

2 Answers2

22

I managed to solve this issue by using Gradle to dynamically create a string resource value in the build.gradle file to represent the file path:

defaultConfig {
    applicationId "com.example.myapp"
    ...
    resValue 'string', 'images_file_path', "Android/data/" + applicationId + "/files/Pictures"
}

You can then reference this string resource value in the res/xml/file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" android:path="@string/images_file_path" />
</paths>
Gambit
  • 286
  • 3
  • 8
  • 2
    FileProvider won't read the value of `path` attribute if you put `android:` namespace. Here is what URI will look like if you write `path="Android/data/com.example.myapp/files/Pictures"`: content://com.example.myapp.photos_provider/my_images/my_file.jpg. This is the correct one. But if you write `android:path="Android/data/com.example.myapp/files/Pictures"` (or use string from resources like in your answer) you get: content://com.example.myapp.photos_provider/my_images/Android/data/com.example.myapp/files/Pictures/my_file.jpg. So you get no profit of using FileProvider. – RustamG Jan 18 '17 at 05:07
  • 1
    android:path does not work here. it needs to contain path attrebute. – Amin Jan 25 '21 at 10:19
13

You don't need to use applicationId in your file_paths.xml at all. Just replace the external_path clause with:

<external-files-path name="my_images" path="Pictures" />

This will require 24.0.0 or higher of the support libraries.

Solution copied from https://stackoverflow.com/a/40563179/1033645.

Community
  • 1
  • 1
javaxian
  • 1,815
  • 1
  • 21
  • 26