Hi there is a way to select folder where user want to save file in android . I check out http://code.google.com/p/android-file-dialog/
it has functionality to select file but i want to select folder , please provide me usable link or examples.
How about using OI File Manager? This App has the following Intents: PICK_FILE, PICK_DIRECTORY.
There is even sample code on the page for using the Intents.
I used the same source in my app (pretty sure), and there is a block of code:
protected void onListItemClick(ListView l, View v, int position, long id) {
if (file.isDirectory()) {
selectButton.setEnabled(false);
if (file.canRead()) {
lastPositions.put(currentPath, position);
getDir(path.get(position));
} else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(
"[" + file.getName() + "] "
+ getText(R.string.cant_read_folder))
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
} else {
selectedFile = file;
v.setSelected(true);
selectButton.setEnabled(true);
}
}
You just have to edit how it handle's if (file.isDirectory()). I would recommend declaring a boolean value in your Activity which you change to true if the file is a directory and it is already false. Then if said value is true, then traverse the directory. Also when you change said value to true, you would need to call selectButton.setEnabled(true). This would be quite a bit less complicated than making your own code, I would say.
Check out this answer https://stackoverflow.com/a/28479561/779140
I am mentioned library author so don't hesitate to ask any questions.
I encountered the same issue and I end up using NoNonsense-FilePicker
Add to gradle file
compile 'com.nononsenseapps:filepicker:4.0.0'
Trigger file/folder/dir pick
try {
Utils.makeHepticFeedback(getActivity());
Intent selectDirectoyIntent = new Intent(getActivity(), FilePickerActivity.class);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_DIR);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath());
startActivityForResult(selectDirectoyIntent, FILE_CODE);
} catch (Exception e) {
Log.e(LOG_TAG, "exception", e);
e.printStackTrace();
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_SHORT).show();
}
Handle Activity result to get selected file or files
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == CHOOSE_IMAGE_REQUEST_CODE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURI(selectedImageUri);
// NOW WE HAVE OUR WANTED STRING
if (selectedImagePath != null) {
System.out
.println("selectedImagePath is the right one for you!");
PreferenceHelper.getPreferenceHelperInstance().setString(getActivity(),
PreferenceHelper.PLAYER_BACKGROUND,
selectedImageUri.toString());
Glide.with(getActivity()).load(Uri.parse(
PreferenceHelper.getPreferenceHelperInstance().getString(getActivity(),
PreferenceHelper.PLAYER_BACKGROUND
, AppConstants.DEFAULT_BACKGROUND_URL))).
into((ImageView) ButterKnife.findById(getActivity(), R.id.play_back));
}
} else if (requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) {
if (null != data && !data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {
// The URI will now be something like content://PACKAGE-NAME/root/path/to/file
Uri uri = data.getData();
// A utility method is provided to transform the URI to a File object
File file = com.nononsenseapps.filepicker.Utils.getFileForUri(uri);
// If you want a URI which matches the old return value, you can do
Uri fileUri = Uri.fromFile(file);
// Do something with the result...
Snackbar.make(fileFormat, "Recording folder updated to" + fileUri.getPath() + " ¯\\_(ツ)_/¯ ", Snackbar.LENGTH_SHORT).show();
AppConfig.RECORDING_FOLDER = fileUri.getPath();
PreferenceHelper.getPreferenceHelperInstance().setString(getActivity(), PreferenceHelper.RECORDING_FOLDER, AppConfig.RECORDING_FOLDER);
setUpSettingValue();
} else {
// Handling multiple results is one extra step
ArrayList<String> paths = data.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS);
if (paths != null) {
for (String path : paths) {
Uri uri = Uri.parse(path);
// Do something with the URI
File file = com.nononsenseapps.filepicker.Utils.getFileForUri(uri);
// If you want a URI which matches the old return value, you can do
Uri fileUri = Uri.fromFile(file);
// Do something with the result...
Toast.makeText(getActivity(), "Selected dir" + fileUri.getPath(), Toast.LENGTH_SHORT).show();
}
}
}
}
}
Related
In devices below android 10 we can access any file like this::
File f = new File("storage/emulated/0/filename.txt");
But I want to do to same on android 10+ devices which are using something like scoped storage or mediastore class that I didn't understood in android studio I don't know exactly how to do it I want to access files any directories not only public directories like "Pictures" please help me
File f = new File("storage/emulated/0/file.jpg");
To get all the files of folder xyz (storage/emulated/0/xyz) below android 10:
File xyzFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "xyz");
File[] allFiles = xyzFolder.listFiles();
But for android 10 and above either use declare MANAGE_EXTERNAL_STORAGE (not recommended if it's not some kind of file manager app) or you can use below method:
1). First take folder permission
uriMain = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fmedia/document/primary%3Axyz");
private final int REQUEST_CODE = 100;
List<Object> filesList = new ArrayList<>();
private void aboveQFolderPermission() {
try {
Intent createOpenDocumentTreeIntent = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
createOpenDocumentTreeIntent = ((StorageManager) getSystemService(STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
}
assert createOpenDocumentTreeIntent != null;
String replace = createOpenDocumentTreeIntent.getParcelableExtra("android.provider.extra.INITIAL_URI").toString().replace("/root/", "/document/");
createOpenDocumentTreeIntent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(replace + "%3A" + "xyz"));
startActivityForResult(createOpenDocumentTreeIntent, REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace()
}
}
Now in onActivityResult(),
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (data != null) {
getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
//save shared preference to check whether app specific folder permission granted or not
sharedPreferences = getSharedPreferences("tree", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("treeUriString", String.valueOf(uriMain));
editor.apply();
new Thread(() -> {
getListAboveQ(uriMain);
handler. Post(() -> /*Some code here as per your need*/);
}).start();
}
}
}
2). Now get the List of files:
private void getListAboveQ(uriMain) {
ContentResolver contentResolver = getContext().getContentResolver();
Uri buildChildDocumentsUriUsingTree = DocumentsContract.buildChildDocumentsUriUsingTree(uriMain, DocumentsContract.getDocumentId(uriMain));
try (Cursor cursor = contentResolver.query(buildChildDocumentsUriUsingTree, new String[]{"document_id"}, null, null, null)) {
while (cursor.moveToNext()) {
filesList.add(DocumentsContract.buildDocumentUriUsingTree(uriMain, cursor.getString(0)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Edit:- You can use saved preferences like:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
sharedPreferences = getSharedPreferences("tree", Context.MODE_PRIVATE);
String uriString = sharedPreferences.getString("treeUriString", "");
if (uriString.matches("")) {
//ask for folder permission
aboveQFolderPermission()
} else {
//Permission is already granted
//TODO: Whatever you want
}
}
You'll need to request MANAGE_EXTERNAL_STORAGE permission. With that permission, you can access shared storage files with the File API.
Reference:
https://developer.android.com/training/data-storage/manage-all-files#all-files-access
None of the submissions here deal with negative result code. I know it means that the task failed, but I have no idea how or why it failed. The app opens the camera and I'm able to take a picture.
btnN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage(v);
}
});
The function definitions are as given below.
public void captureImage(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File imageFile = null;
try {
imageFile = getImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (imageFile != null) {
Uri imageUri = FileProvider.getUriForFile(this, "com.example.testingproject.fileprovider", imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, 1);
}
System.out.println("imageFile length:" + imageFile.length());
}
}
In the above function, I've even tried sending request code as 2. Same functionality, I'm able to click a picture, but same issue.
public File getImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmsss").format(new Date());
String imageName = "jpg_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(imageName, ".jpg", storageDir);
currentImagePath = imageFile.getAbsolutePath();
System.out.println("currImPath: " + currentImagePath);
return imageFile;
}
The much needed onActivityResult() code is below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
System.out.println("reqCode: "+requestCode+" resCode: "+resultCode);
switch (requestCode) {
case 0: {
if (resultCode == RESULT_OK) {
File file = new File(currentImagePath);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(MainActivity.this.getContentResolver(), Uri.fromFile(file));
if (bitmap != null) {
//...Do your stuffs
Toast.makeText(MainActivity.this, "Bitmap NOT null", Toast.LENGTH_SHORT).show();
imgView.setImageBitmap(bitmap);
}
else
{
Toast.makeText(MainActivity.this,"BitmapNull",Toast.LENGTH_SHORT).show();
}
}
break;
}
default: Toast.makeText(MainActivity.this,"result code not okay",Toast.LENGTH_SHORT).show(); break;
}
} catch (Exception error) {
error.printStackTrace();
}
}
The sysout in log is below
2020-05-01 13:52:24.644 10014-10014/com.example.testingproject I/System.out: reqCode: 1 resCode: -1
-1 is equal to RESULT_OK. It means the task completed successfully
When you look into the code. -1 is actully status code for RESULT_OK
public static final int RESULT_OK = -1;
Now you've set requestCode as 1 in this line
startActivityForResult(cameraIntent, 1);
So in your OnActivityResult which shows
reqCode: 1 resCode: -1
is Correct.
I have a filechooser that I call in a webview in order to upload a file.
The method allowing me to retrieve the file in my filechooser activity is as follows :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Option o = adapter.getItem(position);
if (o.isFolder() || o.isParent()) {
currentDir = new File(o.getPath());
fill(currentDir);
} else {
//onFileClick(o);
fileSelected = new File(o.getPath());
Intent intent = new Intent();
intent.putExtra("fileSelected", fileSelected.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
finish();
}
}
This only allows me to get the path in the onActivityResult of my webview (which calls my filechooser to upload file).
The method onActivityResult is given by the code below.
If I use another application installed in my phone other than my filechooser I use :
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
then the result is sent by:
this.mUploadMessage.onReceiveValue(uri);
Since then, it works normally. But with my filechooser intent.getData () equals to null.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
if (resultCode != RESULT_OK) {
mUploadMessage.onReceiveValue(null);
var = 0;
return;
}
// Toast.makeText(getApplicationContext() , "onActivityResult()" + String.valueOf(requestCode) ,Toast.LENGTH_LONG).show();
// Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
// this.mUploadMessage = null;
String fileSelected = intent.getStringExtra("fileSelected");
Bundle result = intent.getExtras();
//result = Uri.parse(fileSelected);
//this.mUploadMessage.onReceiveValue(result);
if (resultCode == RESULT_OK) {
if (intent != null) {
// Get the URI of the selected file
final Uri uri = intent.getData();
Log.i("TOTOTOT", "Uri = " + uri.toString());
Toast.makeText(this, fileSelected + " " + uri.toString() , Toast.LENGTH_SHORT).show();
this.mUploadMessage.onReceiveValue(uri);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
What should I return in my two methods in order to retrieve both data and path, not only the path of the sent file ? Should it be all the bundle or do you know how to get Data while using Intent.getData()?
What is need to get data from directory selected inside onActivityResult()
You got path selected so you can read file from there which you want ..
Use this method to read file as a string
private String readURLFromPath(File filePath){
String dataString = "";
// i have kept text.txt in the sd-card
if (file.exists()) // check if file exist
{
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e){
// You'll need to add proper error handling here
}
// Set the text
dataString = text.toString();
}
return dataString ;
}
this method will return data as a string now you can send this string data on server...
the solution is to Get content uri from file path in android as mentioned Get content uri from file path
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to make a file uploader. And I hence I need a file chooser but I don't want to write this by myself. I find OI file manager and I think it suits me.
But how can I force user to install OI file manager?
If I cannot , is there a better way to include a file manager in my app?
Thx
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} 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();
}
}
You would then listen for the selected file's Uri in onActivityResult() like so:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath() method in my FileUtils.java is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:
My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.
private void startCreation(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
intent.setDataAndType(startDir,
"vnd.android.cursor.dir/lysesoft.andexplorer.file");
intent.putExtra("browser_filter_extension_whitelist", "*.csv");
intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
intent.putExtra("browser_title_background_color",
getText(R.string.browser_title_background_color));
intent.putExtra("browser_title_foreground_color",
getText(R.string.browser_title_foreground_color));
intent.putExtra("browser_list_background_color",
getText(R.string.browser_list_background_color));
intent.putExtra("browser_list_fontscale", "120%");
intent.putExtra("browser_list_layout", "2");
try{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("lysesoft.andexplorer", 0 );
startActivityForResult(intent, PICK_REQUEST_CODE);
} catch( PackageManager.NameNotFoundException e ){
showInstallResultMessage(R.string.error_install_andexplorer);
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
This methos is just pick up a dialog and if user wants install the external application from market
private void showInstallResultMessage(int msg_id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(getText(msg_id));
dialog.setButton(getText(R.string.button_ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setButton2(getText(R.string.button_install),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
startActivity(intent);
finish();
}
});
dialog.show();
}
In my Android application, I want to rename the file name at runtime. How can I do it?
This is my code:
String[] command = {" mv", "sun moon.jpg"," sun_moon,jpg"};
try
{
Process process = Runtime.getRuntime().exec(command);
}
catch (IOException e)
{
Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();
}
I also used renameTo(File f) method but it does not work.
I would recommend using File.renameTo() rather than running the mv command, since I'm fairly sure the latter isn't supported..
Have you given your application permission to write to the SD Card?
You do this by adding the following to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If it doesn't work once the permission is added check the device log for errors when you try to rename the file (either using the adb command or in the logcat view in Eclipse).
When accessing the SD Card you shouldn't hard-code the path but instead use the Environment.getExternalStorageDirectory() method to get the directory.
The following code works for me:
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);
and if you want to check the process, you can do like:
boolean renamed = from.renameTo(to);
if (renamed) {
Log.d("LOG","File renamed...");
}else {
Log.d("LOG","File not renamed...");
}
you can also explicitly give the full path without specifying directory...
File file = new File("Path of file which you want to rename");
File file2 = new File("new name for the file");
boolean success = file.renameTo(file2);
I tried adding permissions. Even though it did not work, adding File1.setWritable(true); enabled me to rename the file.
Below is my code snippet:
if(from.setWritable(true))
Log.d("InsertFragmentTwo ", "FileName==> Is Writable");
File two = new File(sdcard,""+imageCount+"."+s.substring((s.lastIndexOf(".")+1)));
if (from.renameTo(two)) {
Log.d("InsertFragmentTwo ", "New FileName==> " + temp);
imageCount++;
retrofitImageUpload(temp);
} else
Log.d("InsertFragmentTwo ", "File Renaming Failed");
public void selectFile() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select file from internal storage"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
File from = new File(dir, String.valueOf(GALLERY));
File to = new File(dir,"filerename.txt");
if(from.exists())
from.renameTo(to);
}
}
}
}