I am Working email attachment .I am facing one problem while attachment .Problem Is that i want to sent a mail with attachment .I have one file on this path sdcard0 then fgg then hh.html.When I debug
on this File file = new File(attachments.getString(i));
it show file:/storage/sdcard0/fgg/hh.html
But After this it not go to if condition why ?
File file = new File(attachments.getString(i));
if (file.exists()) {
Uri uri = Uri.fromFile(file);
uris.add(uri);
}
Here is my hole code
JSONArray attachments = parameters.getJSONArray("attachments");
if (attachments != null && attachments.length() > 0) {
ArrayList<Uri> uris = new ArrayList<Uri>();
//convert from paths to Android friendly Parcelable Uri's
for (int i=0; i<attachments.length(); i++) {
try {
File file = new File(attachments.getString(i));
if (file.exists()) {
Uri uri = Uri.fromFile(file);
uris.add(uri);
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error adding an attachment: " + e.toString());
}
}
if (uris.size() > 0) {
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
}
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling attachments param: " + e.toString());
}
Uri to file will need triple slashes :
file:///storage/sdcard0/fgg/hh.html
As you can see here.
But i twill probably not work, so try to remove the "file:" part of your string :
File file = new File(attachments.getString(i).replace("file:","");
in a URI, you have different parts.
First the scheme:
http://
file://
ftp://
Then the path you want to access:
myfile.txt
videos/myvideo.avi
/storage/sdcard0/fgg/hh.html
So your complete URI should be:
file:///storage/sdcard0/fgg/hh.html
More information here:
http://developer.android.com/reference/java/net/URI.html
You can then build your File and check if it exist with this snippet
Uri.Builder builder = new Uri.Builder();
builder.scheme("file");
builder.path(myFilePath);
Uri uri = builder.build();
File file = new File(uri.getPath());
if (file.exists()) {
uris.add(uri);
// do whatever you want
}
EDIT:
If your JSON send you complete URI path, use this code instead:
Uri uri = Uri.parse(attachments.getString(i));
File file = new File(uri.getPath());
if (file.exists()) {
uris.add(uri);
// do whatever you want
}
Try two forward slashes after :
file://storage/sdcard0/fgg/hh.html
edit:
should be 3 forward slashes
Related
I need to upload files using multipart form.
I can upload images from path below:
/storage/emulated/0/Pictures/Screenshots/Screenshot_20160614-224624.png
However, when I try to upload a PDF file, it fails. PDF file path is :
/storage/emulated/0/Android/data/com.google.android.apps.docs/cache/projector/pdf.pdf
Can any one tell me why it is work with image and fail with pdf ??
This is my code :
try {
MultipartUtility multipart = new MultipartUtility(ForSaleConstants.EXTRA_FILE_UPLOADER, ForSaleNetworkManager.CHARACTER_SET);
multipart.addFormField(ForSaleConstants.DEVICE_ID, deviceId);
String uriString = extraFileUri.toString();
Log.e("File_URI", uriString);
uriString = Uri.decode(uriString);
if (uriString.contains("file://")) {
uriString = uriString.replace("file://", "");
File uploadFile = new File(uriString);
multipart.addFilePart(("file"), uploadFile);
} else if (uriString.contains("content://")) {
uriString = FileManager.getInstance().getRealPathFromImageUri(context, Uri.parse(uriString));
File uploadFile = new File(uriString);
multipart.addFilePart(("file"), uploadFile);
} else {
try {
File uploadFile = new File(uriString);
multipart.addFilePart(("file"), uploadFile);
}catch (Exception e) {
}
}
List<String> response = multipart.finish();
if(response != null && response.size() > 0) {
mStopTime = System.nanoTime();
PerformanceManager.getInstance().showCalculatedTime("uploadExtraFile [doInBackground]", mStartTime, mStopTime);
JSONObject json = ForSaleNetworkManager.convertStringToJSONObject(response.get(0));
BaseResponse response1 = new BaseResponse(json, null);
return response1;
}
} catch (Exception e) {
e.printStackTrace();
uiListener.onUploadExtraFileCompleted(null, AppError.DATA_ERROR);
return null;
}
Is this your application package ?
com.google.android.apps.docs
/storage/emulated/0/Android/data/com.google.android.apps.docs/cache/projector/pdf.pdf
If not you cannot access it because of sandboxing.
Update
Each android application run in its own linux process hence you cannot access files in different application unless its stored in the common location. Like your image is. Hence you are not able to upload the pdf file
Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(video_path+".***"), "video/*");
startActivity(tostart);
Let's say I have a file path
/mnt/sdcard/video/my_birthday_moovie001
'my_birthday_moovie001' can be either .mkv, .mpg or .mkv. I've tried to add ".***" to the file path but I still can't open the file.
Well i read the comments you have stored your path in db without extensions there are many extensions that exists so android cant automatically pick the extension you have to create some way to detect extension.
following is a robust way that is best match in your case but not recommended in proper cases where extensions are known
public String chk_path(String filePath)
{
//create array of extensions
String[] ext=new String[]{".mkv",".mpg"}; //You can add more as you require
//Iterate through array and check your path which extension with your path exists
String path=null;
for(int i=0;i<ext.Length;i++)
{
File file = new File(filePath+ext[i]);
if(file.exists())
{
//if it exists then combine the extension
path=filePath+ext[i];
break;
}
}
return path;
}
now to play a song in your code
if(chk_path(video_path)!=null)
{
Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(video_path), "video/*");
startActivity(tostart);
}
else
//tell user that although the path in database but file on this path do not exists
Well as I put on comments
You could compare if the path matches with any filename(it doesn't contains the extension) and then if it does you got it.
You can simply do this :
Get the directory path
File extStore = Environment.getExternalStorageDirectory();
Set the file name my_birthday_moovie001 on my example I put unnamed but change it as your like
String NameOfFile = "unnamed";
Add the videos, I put it Downloads but you can change it
String PathWithFolder = extStore + "/Download/";
Create a method that lists all the files from your path
private List<String> getListFiles(File parentDir) {
ArrayList<String> inFiles = new ArrayList<String>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
String AbsolutePath = file.getAbsolutePath();
//Get the file name ex : unnamed.jpg
String nameofFile = AbsolutePath.substring(AbsolutePath.lastIndexOf("/") + 1, AbsolutePath.length());
//Remove the .jpg --> Output unnamed
String fileNameWithoutExtension = nameofFile.substring(0, nameofFile.lastIndexOf('.'));
//Add each file
inFiles.add(fileNameWithoutExtension);
}
}
return inFiles;
}
You got the names of the files doing this
List<String> files = getListFiles(new File(PathWithFolder));
Simply add a for that looks for a match of your file
for (int i = 0; i<=files.size()-1; i++){
if(PathWithFolder.equals(files.get(i))) {
Toast.makeText(MainActivity.this, "You got it!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "You don't.", Toast.LENGTH_SHORT).show();
}
}
If you want to get the path as well and do what #Zain Ul Abidin proposed and compare it on getListFiles() method add this :
String fileExtension = nameofFile.substring(nameofFile.lastIndexOf("."));
Hope it helps.
From the other question :
Consider DirectoryScanner from Apache Ant:
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
You'll need to reference ant.jar (~ 1.3 MB for ant 1.7.1).
And then, run on files array and check
if files[i].include(yourfile)
yourfile= files[i]
You may try in this way , first getting the name of file and extension then finally compare and implement. like this :
Example file name is 04chamelon and extension is .png:
File f = new File("/mnt/storage/sdcard/Pictures/04chameleon");
File yourDir = new File("/mnt/storage/sdcard/Pictures");
nametwo = f.getName();
for (File fa : yourDir.listFiles()) {
if (fa.isFile())
fa.getName();
String path = fa.getName(); // getting name and extension
filextension = path.substring(path.lastIndexOf(".") + 1); // seperating extension
name1 = fa.getName();
int pos = name1.lastIndexOf(".");
if (pos > 0) {
name1 = name1.substring(0, pos);
}
}
if (name1.equals(nametwo)) {
Intent tostart = new Intent(Intent.ACTION_VIEW);
tostart.setDataAndType(Uri.parse(f + "." + filextension), "image/*");
//tostart.setDataAndType(Uri.parse(f + "." + filextension), "video/*");
startActivity(tostart);
}
With the latest ContentResolver, you can easily make this work using the contentResolver.getType(uri) function which detects the filetype.
private fun getIntentForFile(intent: Intent, filePath: String, context: Context): Intent {
val uri = FileProvider.getUriForFile(
context,
context.applicationContext.packageName + ".fileprovider",
File(filePath)
)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(uri, context.contentResolver.getType(uri))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent
}
I've coded my own file explorer and now I want to start to Implement capabilities to open various files. I have implemented Mime Types and all other things but how can I parse specific selected file to specific "viewer activity"? I know by using intents but how to receive it in that viewer app and use it. Many thanks guys :)
Something like this should work. Change file to whatever you want.
File file = new File(Environment.getExternalStorageDirectory(), "movie.mp4");
int index = file.getName().lastIndexOf(".") + 1;
String extension = null;
if (index > 0) {
extension = file.getName().substring(index);
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri u = Uri.parse("file://" + file.getAbsolutePath());
String mimeType = null;
if (extension != null) {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
if (mimeType == null) {
mimeType = "*/*";
}
intent.setDataAndType(u, mimeType);
try {
startActivity(Intent.createChooser(intent, "Open with..."));
} catch (ActivityNotFoundException e) {
// handle the exception
}
A'm working on Android project.
I need to provide ContentProvider to provide access to some directory.
FileProvider it is good solution for me.
Is it possible to retrieve list of files in directory using FileProvider?
User ACTION_SEND_MULTIPLE to send multiple URI
// Set up an Intent to send back to apps that request files
mResultIntent = new Intent("com.yourpacakgename.ACTION_SEND_MULTIPLE");
// Get the files/res subdirectory;
File mResDir = new File(getFilesDir(), "res");
// Get the files in the res subdirectory
File[] mResFiles = mResDir.listFiles();
// Uri list
ArrayList<Uri> uriArrayList = new ArrayList<Uri>();
// Set the Activity's result to null to begin with
setResult(Activity.RESULT_CANCELED, null);
Uri fileUri = null;
for (int i = 0; i < mResFiles.length; i++) {
Log.i(TAG, mResFiles[i].getName());
// Use the FileProvider to get a content URI
try {
fileUri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", mResFiles[i]);
// add current file uri to the list
uriArrayList.add(fileUri);
} catch (Exception e) {
Log.e(TAG, "The selected file can't be shared: " + mResFiles[i].getPath());
fileUri = null;
}
}
if (uriArrayList.size() != 0) {
// Put the UriList Intent
mResultIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriArrayList);
mResultIntent.setType("application/*");
// Grant temporary read permission to all apps
mResultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// if you want send this to a specific app
//grantUriPermission("pacakgename of client app", fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Set the result
this.setResult(Activity.RESULT_OK, mResultIntent);
} else {
// Set the result to failed
mResultIntent.setDataAndType(null, "");
this.setResult(RESULT_CANCELED, mResultIntent);
}
// Finish Activity and return Result to Caller
finish();
I wish I could open any file type using mobile applications.
Here is the code :
File mFile = new File( file.getLocalPath() + file.getFileName() );
Log.i("path", file.getLocalPath() + file.getFileName());
if( mFile.exists() )
{
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(mFile.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Log.i("type", type);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri data = Uri.fromFile(mFile);
Log.i("uri", data.toString());
intent.setDataAndType( data, type );
try {
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
}
}
Logs :
Path : /data/data/com.package.name/files/sbx/523/filename.jpg
Type : image/jpeg
Uri : file:///data/data/com.package.name/files/sbx/523/filename.jpg
All logs are displayed therefore the file exists.
However, during the opening of the gallery, I get an "Unable to find item".
Where is the problem ? Are there other solutions ?
The problem is that you are trying to open file which is in android private area thats why during the opening of the gallery, you get an "Unable to find item". You have to put your file in local. If you want to open a file of android private area you should be rooted.