I am trying to generate a Uri with a given file name that does not exist yet. I have asked for permission from the user to access this folder.
Basically, I have a tree Uri and a name, say "untitled.abc".
If untitled.abc already exists in the given directory, I want to check if untitled1.abc exists, then untitled2.abc and so on.
What I have currently doesn't work and is probably the wrong way to do this:
static Uri getUniqueDocumentUri(Context c, String name, Uri myTreeUri){
DocumentFile folder = DocumentFile.fromTreeUri(c, myTreeUri);
if(folder != null) {
DocumentFile dFile = folder.createFile(".abc", name + ".abc");
int count = 1;
if(dFile == null) return null; //dFile IS ALWAYS NULL
while (dFile.exists()) {
dFile = folder.createFile(".abc", name + count + ".abc");
}
return dFile.getUri();
}
return null;
}
I don't actually want to create the files but I can't figure out how to create a uri for a file that does not exist yet. This is very easy with the normal File class:
static public String getUniqueFileName(Context c, String name, String mybasePath){
File folder = new File(mybasePath);
if(!folder.exists()) folder.mkdir();
File file = new File(basePath + name + ".abc");
int count = 1;
while(file.exists()){
file = new File(basePath + name + count + ".abc");
count++;
}
return file.getName();
}
but I just don't know how to achieve the same with DocumentFile and Uri. There must be a better way to do this, surely?
Edit: I guess what I am trying to do is create a Uri with a given name and folder.
Edit2: I have also tried this:
static Uri getUniqueDocumentUri(Context c, String name, Uri myTreeUri){
DocumentFile folder = DocumentFile.fromTreeUri(c, Uri.parse(mytreeUri));
if(folder != null) {
String name1 = name + ".abc";
int count = 1;
while (folder.findFile(name1) != null) {
name1 = name + count + ".abc";
count++;
}
DocumentFile newdf = folder.createFile(".abc", name1);
if(newdf == null) return null;
return newdf.getUri(); //THIS RETURNS NULL
}
return null;