android Get file name and path from Download directory - android

I'm trying to copy a file from download folder to another directory.
i used this code to get the file path
int PICKFILE_RESULT_CODE=1;
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult( chooseFile,PICKFILE_RESULT_CODE);
I also used
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
returnUri = returnIntent.getData();
String src = returnUri.getPath();
Toast.makeText(this, src, Toast.LENGTH_SHORT).show();
}
}
The code works fine if the file is outside the download directory, when in it the path which i get is in the form of number not the actual name of the file like:
/document/2399
this gives an error of file not found
while the path from the root is:
/storage/emulated/0/myDB.db3
this works fine
pls help me to fix this

The code works fine if the file is outside the download directory
No, it does not. It works fine if the scheme of the Uri happens to be file. Most of the time, it will be content.
I'm trying to copy a file from download folder to another directory.
Use openInputStream() on a ContentResolver to get an InputStream on the content identified by the Uri. This works for both file and content schemes. Then, use standard Java I/O to copy the content from the InputStream to your desired location.

Here is the new code:
int PICKFILE_RESULT_CODE=1;
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult( chooseFile,PICKFILE_RESULT_CODE);
And used:
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
InputStream is = null;
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
// Get the file's content URI from the incoming Intent
Uri returnUri = returnIntent.getData();
try {
is = getContentResolver().openInputStream(returnUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
BackUpHelper.importDB(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void importDB(InputStream is) throws IOException {
OutputStream os = null;
try {
String currentDBPath = DataBaseHelper2.DB_PATH+DataBaseHelper2.DB_NAME;
File outPut = new File(currentDBPath);
os = new FileOutputStream(outPut);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
Toast.makeText(context, R.string.export_successful,
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, R.string.export_failed, Toast.LENGTH_SHORT)
.show();
}finally {
os.flush();
os.close();
is.close();
}
}

Related

Android 11 scooped storage manage_external_storage permission is not accepted by google play console

my app is working fine below the 10 version but android 11 and higher versions do not support external storage. my picker is not picking any document file. but after giving manage_external_storage permission in manifest google play store did not approve my app. please help if you know any alternate solution for all file access permission.
Try like below. Create global variable as needed or refactor as per your need. This is tested upto Android 11.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private void OpenCamera() {
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createFile();
} catch (Exception ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getApplicationContext().getPackageName() + ".fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 3);
}
// }
} catch (Exception e) {
}
}
private File createFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */".jpg", /* suffix */storageDir /* directory */);
// Save a file: path for use with ACTION_VIEW intents
ImageLoc = image.getAbsolutePath();
return image;
}
// Open Gallery
private void OpenGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), 1);
}
// onActivityResult handles gallery pics, camera pics and pdf.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
if (data.getData() != null) {
try {
Uri imageUri = data.getData();
File file = new File(Path_from_Uri.getPath(getActivity(), imageUri));
} catch (Exception e) {
Toast.makeText(getActivity(), "Please Select Image from Gallery", Toast.LENGTH_LONG).show();
}
}
}
} else if (requestCode == 3) {
try {
File file = new File(ImageLoc);
} catch (Exception e) {
Log.d("TAG", e.toString());
}
}
}

I want take uri from selected file

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Copy"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
this code lead me to select file and i want take uri of selected file,
Hi once you get your image you need to trigger and retrieve image data using onActivityResult like this, have a dedicated result code for this operation. rough example below to give u idea
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getData(); // ur raw file data convert to anything u want
try {
//for images
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
imageView.set(bitmap) //example , you can choose what you want to with bitmap
//for files
InputStream inputStream;
File file = null;
try {
inputStream = getContentResolver().openInputStream(Uri.parse(your URI));
file = new File(String.valueOf(inputStream));
}catch (Exception e){
}
}catch (IOException e) {
e.printStackTrace();
}

File Object is Not Getting Created

I am giving file browser to user to select file. On onActivityResult I am getting file path as - /file/sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt. When I try to create file object on this I am not able to create. When I remove /file/ and create file object on sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt its getting created. But I cant hardcode to remove /file/ from filepath as on other device it will be giving some other path. below is the code
private void readContactFromFile(String path) {
StringBuilder text = new StringBuilder();
try {
String st = "/file/sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt";
File file = new File(st);
if (file.exists()) {
Log.v("TTT", "file exist");
}
Log.v("TTT", file.toString());
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("Test", "text : " + text + " : end");
text.append('\n');
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
and I am getting path on OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_PICK_FILE:
Uri uri = data.getData();
String path = data.getData().getPath();
Log.v("PATH", path);
readContactFromFile(path);
break;
}
}
}
And this is how I am calling for opening file browser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*"); //all files
//intent.setType("text/xml"); //XML file only
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), REQUEST_PICK_FILE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
How can I get the perfect path or How can I remove this issue?
Thanks in Advance
Because of the circumstance that the path differs on different devices you should use the frameworks api to retrieve the appropiate path for you.
Have a look at the Environment class.
Instead of using hardcoded string path get the path using Environment class
File file=new File(String.valueOf(Environment.getExternalStorageDirectory())+"YOUR_REQUIRED_FILE_PATH");
It will not defer from device to device.
Hope this helps :)

Android CSV file choose from Storage and get its path

I want to import csv from external storage and then update my database but when i am selecting that csv from downloaded folder FileNotFoundExpception comes. Here is the exception System.err: java.io.FileNotFoundException: /document/primary:Download/GuestCSV.csv: open failed: ENOENT (No such file or directory)
Here is my code. Kindly review my code and help me to find a solution.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(Intent.createChooser(intent, "Open CSV"), ACTIVITY_CHOOSE_FILE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
onImport(new File(data.getData().getPath()));
}
}
}
}
public void onImport(File files) {
try {
CSVReader reader = new CSVReader(new FileReader(files));
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
String emailID = nextLine[0];
String guestName = nextLine[1];
String guestSource = nextLine[2];
String guestPhone = nextLine[3];
String guestCount = nextLine[4];
String guestCreatedDate = nextLine[5];
String guestModifiedDate = nextLine[6];
GuestDetails guestDetails = new GuestDetails();
guestDetails.setEmail(emailID);
guestDetails.setUsername(guestName);
guestDetails.setPhone(guestPhone);
guestDetails.setSource(guestSource);
guestDetails.setCount(Integer.valueOf(guestCount));
guestDetails.setCreatedDate(guestCreatedDate);
guestDetails.setModifiedDate(guestModifiedDate);
try {
helper.insertGuest(guestDetails);
} catch (SQLiteConstraintException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Data inserted into table...", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
i hope this code help you!!
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/YourFolder/");
intent.setDataAndType(uri, "text/csv");
startActivity(Intent.createChooser(i, "Open folder"));

Android CSV Path is throwing FileNotFoundExpception

I want to import csv from external storage and then update my database but when I am selecting that csv from downloaded folder FileNotFoundExpception comes. Here is the exception System.err:
java.io.FileNotFoundException: /document/primary:Download/GuestCSV.csv: open failed: ENOENT (No such file or directory)
Here is my code. Kindly review my code and help me to find a solution.
importDatabase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(Intent.createChooser(intent, "Open CSV"), ACTIVITY_CHOOSE_FILE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
onImport(new File(data.getData().getPath()));
Log.d(TAG, data.getData().getPath());
}
}
}
}
public void onImport(File files) {
try {
String[] nextLine;
try {
CSVReader reader = new CSVReader(new FileReader(files.getAbsolutePath()));
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
String emailID = nextLine[0];
String guestName = nextLine[1];
String guestSource = nextLine[2];
String guestPhone = nextLine[3];
String guestCount = nextLine[4];
String guestCreatedDate = nextLine[5];
String guestModifiedDate = nextLine[6];
GuestDetails guestDetails = new GuestDetails();
guestDetails.setEmail(emailID);
guestDetails.setUsername(guestName);
guestDetails.setPhone(guestPhone);
guestDetails.setSource(guestSource);
guestDetails.setCount(Integer.valueOf(guestCount));
guestDetails.setCreatedDate(guestCreatedDate);
guestDetails.setModifiedDate(guestModifiedDate);
try {
helper.insertGuest(guestDetails);
} catch (SQLiteConstraintException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Data inserted into table...", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
There is no guaranty that the URI you are receiving as result is a file (and thus that the path part is an actual filesystem path).
It may be a content: URI, in with case the path only makes sense for the corresponding ContentProvider.
This kind of URI should be read using ContentResolver.openInputStream() or queried via ContentResolver.query().
See A Uri Is Not (Necessarily) a File for more details.

Categories

Resources