Issue
I am making an app which downloads files to download/sard/ folder in android. (Sard is a folder created by my app )
Please take time to read the whole
When the user closes and reopen the app I want it to check which files are downloaded
The problem is the files are in device downloads.And from Android 10 onwards I can't use the old methods like getExternalStiragePublicDurectory()
( I don't want to use legacy support ) . I found out that there is a method with mediastore,content resolver and cursor etc. But they only show how to use folders like my apps media folder ( android/media/myapp ) and pictures folder etc.
I have read the documentation and found you can read device downloads but don't know how.
I want to check if a file exist in downloads folder.
Don't recommend any documentation or mark as duplicate, I want someone to explain it to me with a simple example.( I use Java and don't know a single thing about kotlin )
And I don't want to save downloaded files to my media folder as this app is for my friend. And he don't know much beyond downloads folder and things like that.
Any answer is appreciated, and I will remember you whenever I work with files in android 10 above.
Solution
You can use the returned file to read or write as you wish. Of course i can explain it if needed.
private File getFile(String name) throws IOException {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.Q){
Uri uri= MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
String[] projection=new String[]{
MediaStore.Downloads.DISPLAY_NAME,
MediaStore.Downloads.RELATIVE_PATH,
MediaStore.Downloads._ID
};
String selection=MediaStore.Downloads.DISPLAY_NAME+"= ? AND "+MediaStore.Downloads.RELATIVE_PATH+"= ?";
String[] args = new String[]{
name, Environment.DIRECTORY_DOWNLOADS+"/SARD/"
};
Cursor cursor=getApplicationContext().getContentResolver().query(uri,projection,selection,args,null);
if(cursor!=null && cursor.getCount()>0){
cursor.moveToFirst();
int id=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID));
Uri ur=Uri.withAppendedPath(uri,String.valueOf(id));
cursor.close();
File file=new File(this.getFilesDir(),"temp.xls");
FileInputStream s= (FileInputStream) getApplicationContext().getContentResolver().openInputStream(ur);
byte[] b=new byte[(int) s.getChannel().size()];
FileOutputStream s2=new FileOutputStream(file);
s.read(b);
s2.write(b);
s.close();
s2.close();
return file;
}else{
cursor.close();
Toast.makeText(this, "An Error 5 has occurred, please restart the app again"+System.lineSeparator()+
"If the error continues contact the Developer", Toast.LENGTH_LONG).show();
return null;
}
}else{
return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"SEAD/"+batchName+"/excel/"+name);
}
}
You can use the returned file to read or write as you wish
Answered By - Binil George
Answer Checked By - Willingham (JavaFixing Volunteer)