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();
}
Related
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();
}
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();
}
}
So I found a function that would prompt the use to open the gallery of the device. But upon searching around I couldn't find anything that would help me modify this to return an image path. They say something about onActivityResult() which I put on the void itself and is then rejected. Any help on this?
public void chooser() {
AlertDialog.Builder myDialog
= new AlertDialog.Builder(IPAddress.this);
myDialog.setTitle("Import Menu Images");
LinearLayout layout = new LinearLayout(IPAddress.this);
layout.setOrientation(LinearLayout.VERTICAL);
myDialog.setView(layout);
myDialog.setPositiveButton("Open Folder", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
}
});
myDialog.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
myDialog.show();
}
I would like it to return the path of the image selected and then I would use that path to copy the said file and save it to a directory I have created on OnCreate of the activity.
Also, I can't seem to be able to debug the said function as when I click the "Open Folder" button, it would give an error saying
The application Camera(process.com.android.gallery) has stopped unexpectedly. Please try again.
which I've tried multiple times. I even added a front camera to the emulator.
The function is called here :
Button menu_image = (Button) findViewById(R.id.menu_image);
menu_image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
chooser();
}
});
So I would like the chooser to return a string(?) type if it is possible which I would then use to File Copy and then rename.
A default app chooser can be queried by following way.
Button galleryBtn = (Button) view.findViewById(R.id.gallery_btn);
galleryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), 2);
}
});
And you'll receive the selected file's URi in onActivityResult() of your activity/fragment.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriString = null;
if (requestCode == 2 && resultCode == RESULT_OK) {
Uri uri = data.getData();
if (uri != null) {
Cursor cursor = getActivity().getContentResolver()
.query(uri,
new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
null, null, null);
cursor.moveToFirst();
Bitmap bm = BitmapFactory.decodeFile(cursor.getString(0));
File file = new File(cursor.getString(0));
uriString = Uri.fromFile(file);
// do processing with the uri here
cursor.close();
}
}else{
Log.e("RDT", "Something went wrong.");
return;
}
}
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();
}
}
}
}
}
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);
}
}
}
}