So what i want is to delete file using URI
Do not flag is duplicate
I tried many answer but nothing worked here is the question i tried
How to delete file that is created using Uri?
Delete file using Uri
How to delete file that is created using Uri?
I write code to get images from gallery and then copy it to directory called ".blackhat" and delete original one (Kind of Move File Function)..But it's not working. even it is not generation Log so i can check the error.
this code working proper for copying file but not deleting after copying....
if(requestCode == 2 && data.getData() !=null){
if(cd == null){
path.add(data.getData());
Random rn = new Random();
if(copyFileFromUri(this,data.getData(),String.valueOf(rn.nextInt(500)))){
File fdelete = new File(data.getData().getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
Log.d("delete","deleted");
} else {
Log.d("delete","not deleted");
}
}
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
}
}else{
for(int i=0;i<data.getClipData().getItemCount();i++){
path.add(data.getClipData().getItemAt(i).getUri());
Log.d("RjList",path.get(i).toString());
Random rn=new Random();
if(copyFileFromUri(this,data.getClipData().getItemAt(i).getUri(),String.valueOf(rn.nextInt(500)))){
File fdelete = new File(data.getClipData().getItemAt(i).getUri().getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
Log.d("delete","deleted");
} else {
Log.d("delete","not deleted");
}
}
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
}
}
}
}
Where am i doing wrong ????
Thank in advance...
public static boolean delete(final Context context, final File file) {
final String pathone = MediaStore.MediaColumns.DATA + "=?";
final String[] selectedArgs = new String[] {
file.getAbsolutePath()
};
final ContentResolver contentResolver = context.getContentResolver();
final Uri fileUri = MediaStore.Files.getContentUri("external");
contentResolver.delete(fileUri, pathone, selectedArgs );
if (file.exists()) {
contentResolver.delete(fileUri, pathone, selectedArgs );
}
return !file.exists();
}
File fdelete = new File(data.getData().getPath(),"here you should pass the file name");
if (fdelete.exists()) {
if (fdelete.delete()) {
Log.d("delete","deleted");
} else {
Log.d("delete","not deleted");
}
}
Related
I've got the following code:
private int REQUEST_CODE_PERMISSIONS = 1001;
private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA", "android.permission.WRITE_EXTERNAL_STORAGE"};
public String getBatchDirectoryName() {
String app_folder_path = "";
if(allPermissionsGranted()){
Log.e("i enter this code","!");
app_folder_path = Environment.getExternalStorageDirectory().toString() + "/images";
File dir = new File(app_folder_path);
if (!dir.exists() && !dir.mkdirs()) { //both are false but why?
Log.e("failed to create:",app_folder_path); ///returns: storage/emulated/0/images
}
}else{
app_folder_path = "fail"; // i DONT enter this code t
}
return app_folder_path;
}
private boolean allPermissionsGranted(){
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(getContext(), permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}
I am trying to save a image so I use the function getBatchDirectoryName() to create a directory if it does not exsist,or else returning the exsisting directory.
The issue is that, the directory does not exsist I cant create it for some reason. Both functions exists and mkdirs return false.
What can the cause be? I check before If I have the permission for writing files.
I'm using google API v3 for check exist folder. If folder does not exist, then create the new folder. This is my code for creating folder
private void createFolderInDrive() throws IOException {
boolean existed = checkExistedFolder("MyFolder");
if (existed = false) {
File fileMetadata = new File();
fileMetadata.setName("MyFolder");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = mService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Log.e(this.toString(), "Folder Created with ID:" + file.getId());
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Folder is existed already", Toast.LENGTH_SHORT).show();
}
}
and here is the code for checking exist file
private boolean checkExistedFolder(String folderName) {
//File file = null;
boolean existedFolder = true;
// check if the folder exists already
try {
//String query = "mimeType='application/vnd.google-apps.folder' and trashed=false and title='" + "Evacuation Kit" + "'";
String query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='Evacuation Kit'";
// add parent param to the query if needed
//if (parentId != null) {
//query = query + " and '" + parentId + "' in parents";
// }
Drive.Files.List request = mService.files().list().setQ(query);
FileList fileList = request.execute();
if (fileList.getFiles().size() == 0 ) {
// file = fileList.getFiles().get(0);
existedFolder = false;
}
} catch (IOException e) {
e.printStackTrace();
}
return existedFolder;
fileList.getFiles().size() keep returning 3, even there is no folder on g drive. Can you guys tell me where am I doing wrong?
In the code you show, checkExistedFolder is always looking for the name "Evacuation Kit" and not using the argument folderName. Maybe this is the main reason you're always getting 3 from fileList.getFiles().size().
Also there's an assignment in if (existed = false), you should use if ( false == existed ) -using the static value in the left side of the comparison helps avoiding such mistakes-, or if (!existed). Note that it's important to check the nextPageToken when calling Files:list to check if there is more pages to look for the file. See more here https://developers.google.com/drive/api/v3/reference/files/list and Create folder if it does not exist in the Google Drive
This code will check if folder exist on drive. if exists, it will return id else create folder and returns id.
private DriveFile file;
GoogleApiClient mGoogleApiClient;
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.e(TAG, "connected");
new Thread(new Runnable() {
#Override
public void run() {
DriveId Id = getFolder(Drive.DriveApi.getRootFolder(mGoogleApiClient).getDriveId(), "FOLDER_NAME");
Log.e(TAG, "run: " + Id);
}
}).start();
}
DriveId getFolder(DriveId parentId, String titl) {
DriveId dId = null;
if (parentId != null && titl != null) try {
ArrayList<Filter> fltrs = new ArrayList<>();
fltrs.add(Filters.in(SearchableField.PARENTS, parentId));
fltrs.add(Filters.eq(SearchableField.TITLE, titl));
fltrs.add(Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE));
Query qry = new Query.Builder().addFilter(Filters.and(fltrs)).build();
MetadataBuffer mdb = null;
DriveApi.MetadataBufferResult rslt = Drive.DriveApi.query(mGoogleApiClient, qry).await();
if (rslt.getStatus().isSuccess()) try {
mdb = rslt.getMetadataBuffer();
if (mdb.getCount() > 0)
dId = mdb.get(0).getDriveId();
} catch (Exception ignore) {
} finally {
if (mdb != null) mdb.close();
}
if (dId == null) {
MetadataChangeSet meta = new MetadataChangeSet.Builder().setTitle(titl).setMimeType(DriveFolder.MIME_TYPE).build();
DriveFolder.DriveFolderResult r1 = parentId.asDriveFolder().createFolder(mGoogleApiClient, meta).await();
DriveFolder dFld = (r1 != null) && r1.getStatus().isSuccess() ? r1.getDriveFolder() : null;
if (dFld != null) {
DriveResource.MetadataResult r2 = dFld.getMetadata(mGoogleApiClient).await();
if ((r2 != null) && r2.getStatus().isSuccess()) {
dId = r2.getMetadata().getDriveId();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dId;
}
The code working for me with updated API on Kotlin:
override fun createFolder(name: String): Task<GoogleDriveFileHolder> {
check(googleDriveService != null) { "You have to init Google Drive Service first!" }
check(search(name, FOLDER_MIME_TYPE).not()){"folder already exist"}
return Tasks.call<GoogleDriveFileHolder>(
mExecutor,
Callable<GoogleDriveFileHolder> {
val metadata = File()
.setMimeType(FOLDER_MIME_TYPE)
.setName(name)
GoogleDriveFileHolder(
googleDriveService!!.files()
.create(metadata)
.setFields("id")
.execute() ?: throw IOException("Null result when requesting file creation.")
)
})
}
private fun search(name: String, mimeType:String): Boolean {
var pageToken: String? = null
do {
val result: FileList =
googleDriveService!!
.files()
.list()
.setQ("mimeType='$FOLDER_MIME_TYPE'")
.setSpaces("drive")
.setFields("nextPageToken, files(id, name)")
.setPageToken(pageToken)
.execute()
for (file in result.files) {
Log.d(TAG_UPLOAD_FILE , "Found file: %s (%s)\n ${file.name}, ${file.id} ")
if (name == file.name) return true
}
pageToken = result.nextPageToken
} while (pageToken != null)
return false
}
private const val FOLDER_MIME_TYPE= "application/vnd.google-apps.folder"
I am trying to create a option for the user to send the file from my application via email only. The file is internal to the application and is accessible via the FileProvider.
This is the contentURI looks like content://packagename.files/files/somefile.ext
Here as you can see that I am giving the user to share the file to PicsArt, Google Drive, OneDrive and EMail.
I am able to share the content to the first three clients successfully as they very specific applications. But when it comes to Email, I need to user to pick the client from the applications he has installed in his mobile.
Here are 2 set of codes I have created:
Code Option 1:
Intent EMail = ShareCompat.IntentBuilder.from(this)
.setType("message/rfc822")
.setSubject("Emailing: File Attached")
.setText("Hello")
.setStream(contentUri)
.setChooserTitle("Send via EMail").getIntent();
startActivity(Intent.createChooser(EMail, "Send via EMail"));
Above code shows me a chooser where there are many applications which can handle the files as shown in the image below.
This one works fine if I select any email client application or any other application.
But the problem with this is that there is an option for the user to select any application, which is not the desired behavior of the application. So, I modified the code as below:
final Intent _Intent = new Intent(Intent.ACTION_SENDTO);
_Intent.setType("text/html");
_Intent.setData(Uri.parse("mailto:"));
_Intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
_Intent.putExtra(Intent.EXTRA_STREAM, contentUri);
_Intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Emailing: File Attached");
_Intent.putExtra(android.content.Intent.EXTRA_TEXT,
"Hello");
startActivity(Intent.createChooser(_Intent, "Send via EMail"));
Here is the outcome of the code:
But, now the problem here is that I am not able to send the file from the content provider (FileProvider). The email client shows the message as below after selecting:
It is simply not attaching the file to the email in any client in the above list.
I will be greatfull, if anyone can help me out here. I think that, I have tried all the possible scenarios here, by changing the mime-type, setting content in different manner setting data setting stream etc, but not able to get the desired outcome.
Please let me know in case you need any other details on this.
Thanks again in advance.
You need to write the ContentProvider which will provide the InputStream to the client to which you have passed the ContentUri or may be you can directly provide the file path if its present in the SdCard or the Internal storage because you will need to handle the uri's and pass the InputStream . Note: ExtraStream is best for files that are not in device that is which is to be accessed from internet.
public class SampleContentProvider extends ContentProvider implements ContentProvider.PipeDataWriter<InputStream> {
static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//Uri matcher for different
}
/**
* Database specific constant declarations
*/
private SQLiteDatabase db;
#Override
public boolean onCreate() {
return true;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
throw new SQLException("Insert operation not supported for " + uri);
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
//condition just for files. You can try something else
if (uri.toString().contains("files")) {
//you get the file name
String lastSegment = uri.getLastPathSegment();
if (projection == null) {
projection = new String[]{OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};
}
File file = //Code to read the file as u have the directory, just get the file from the file name obtained from the uri
if (null == file) {
throw new IllegalArgumentException("Unknown File for Uri " + uri);
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
int i = 0;
for (String col : projection) {
if (OpenableColumns.DISPLAY_NAME.equals(col)) {
cols[i] = OpenableColumns.DISPLAY_NAME;
values[i++] = //file name;
} else if (OpenableColumns.SIZE.equals(col)) {
cols[i] = OpenableColumns.SIZE;
values[i++] = //file size;
}
}
cols = copyOf(cols, i);
values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
return super.query(uri, projection, selection, selectionArgs, sortOrder);
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return super.delete(uri, selection, selectionArgs);
}
private static String[] copyOf(String[] original, int newLength) {
final String[] result = new String[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
private static Object[] copyOf(Object[] original, int newLength) {
final Object[] result = new Object[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
#Nullable
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
File file = //read the file
if (file != null) {
try {
StrictMode.ThreadPolicy tp = StrictMode.ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
InputStream in = //Code to get the inputstream;
// Start a new thread that pipes the stream data back to the caller.
return openPipeHelper(uri, null, null, in, this);
} catch (IOException e) {
FileNotFoundException fnf = new FileNotFoundException("Unable to open " + uri);
throw fnf;
}
}
throw new IllegalArgumentException("Unknown URI " + uri);
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return super.update(uri, values, selection, selectionArgs);
}
#Override
public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
Bundle opts, InputStream args) {
// Transfer data from the asset to the pipe the client is reading.
byte[] buffer = new byte[8192];
int n;
FileOutputStream fout = new FileOutputStream(output.getFileDescriptor());
try {
while ((n = args.read(buffer)) >= 0) {
fout.write(buffer, 0, n);
}
} catch (IOException e) {
} finally {
try {
args.close();
} catch (IOException e) {
}
try {
fout.close();
} catch (IOException e) {
}
}
}
}
I have decided to copy the file from internal app storage to external app storage (not external public storage) and sharing the file from there. I am bit surprised though as the FileProvider is capable of sharing the files from the internal file storage with anything and every thing in the system but fails to do so when I want to filter the Intents which are email clients only.
It was kind of difficult for me to implement a custom provider at beginner's level.
try this snippet.
Intent testIntent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + "Feedback" + "&body=" + "Write Feedback here....." + "&to=" + "someone#example.com");
testIntent.setData(data);
startActivity(testIntent);
This question already has an answer here:
Android send mail with PDF file
(1 answer)
Closed 7 years ago.
I need send a PDF file attach on a message, I have a button that calls a function that open a Intent with message, email address and subject filled, but I need that the PDF file has been attached too.
This is my code and I can not find my error, someone can help me please?
public void initializeWebView() {
// Initialize the webview
webView.setResourceClient(new XWalkResourceClient(webView) {
#Override
public boolean shouldOverrideUrlLoading(XWalkView view, String stringUrl) {
if(stringUrl.equals(baseUrl)) {
return false;
}
// mailto links will be handled by the OS.
if (stringUrl.startsWith("mailto:")) {
Uri uri = Uri.parse(stringUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
String fileName = "bouhnik.pdf";
String filePath = (Configuration.getMagazineAssetPath()).toString()+ File.separator + fileName;
Context c = getActivity().getApplicationContext();
File file = null;
FileOutputStream fos = null;
try {
InputStream is = c.getAssets().open(filePath);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
fos = new FileOutputStream(file);
fos.write(buffer);
fos.close();
} catch (IOException e) {
Log.i("Ferrou",e.toString());
e.printStackTrace();
}
if (!file.exists() || !file.canRead()) {
return false;
}
intent.putExtra(intent.EXTRA_STREAM, file.getPath());
intent.setClassName("com.android.email", "com.android.mail.compose.ComposeActivity");
intent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
WebViewFragment.this.startActivity(Intent.createChooser(intent, "Send email..."));
} else {
try {
URL url = new URL(stringUrl);
// We try to remove the referrer string to avoid passing it to the server in case the URL is an external link.
String referrer = "";
if (url.getQuery() != null) {
Map<String, String> variables = Configuration.splitUrlQueryString(url);
String finalQueryString = "";
for (Map.Entry<String, String> entry : variables.entrySet()) {
if (entry.getKey().equals("referrer")) {
referrer = entry.getValue();
} else {
finalQueryString += entry.getKey() + "=" + entry.getValue() + "&";
}
}
if (!finalQueryString.isEmpty()) {
finalQueryString = "?" + finalQueryString.substring(0, finalQueryString.length() - 1);
}
stringUrl = stringUrl.replace("?" + url.getQuery(), finalQueryString);
}
// Remove referrer from query string
if (!url.getProtocol().equals("file")) {
if (referrer.equals(WebViewFragment.this.getActivity().getString(R.string.url_external_referrer))) {
Uri uri = Uri.parse(stringUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
WebViewFragment.this.startActivity(intent);
} else if (referrer.toLowerCase().equals(WebViewFragment.this.getActivity().getString(R.string.url_baker_referrer))) {
((IssueActivity) WebViewFragment.this.getActivity()).openLinkInModal(stringUrl);
return true;
} else {
return false;
}
} else {
stringUrl = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
int index = ((IssueActivity) WebViewFragment.this.getActivity()).getJsonBook().getContents().indexOf(stringUrl);
if (index != -1) {
Log.d(this.getClass().toString(), "Index to load: " + index + ", page: " + stringUrl);
((IssueActivity) WebViewFragment.this.getActivity()).getViewPager().setCurrentItem(index);
view.setVisibility(View.GONE);
} else {
// If the file DOES NOT exist, we won't load it.
File htmlFile = new File(url.getPath());
if (htmlFile.exists()) {
return false;
}
}
}
} catch (MalformedURLException | UnsupportedEncodingException ex) {
Log.d(">>>URL_DATA", ex.getMessage());
}
}
return true;
}
});
// Set UI Client (Start stop animations)
webView.setUIClient(new XWalkUIClient(webView) {
#Override
public void onPageLoadStopped(XWalkView view, String url, LoadStatus status) {
if(!url.isEmpty() && status == LoadStatus.FINISHED) {
if(isUserVisible) {
webView.resumeTimers();
}else{
webView.pauseTimers();
}
}
}
});
webView.load(baseUrl, null);
}
Thank's so much for everyone!!
I solve my problem change the type of Intent to:
Intent emailIntent = new Intent(Intent.ACTION_SEND);
Because this is better to email commands, and I define a emailUri where:
emailUri = Uri.fromFile(file.getAbsoluteFile());
because this get a absolute path with a file inside, and when the email client open, it open this file, not a path.
I add a type at my intent but I select the type of my attachment, so I define:
emailIntent.setType("application/pdf");
And finally:
emailIntent.putExtra(Intent.EXTRA_STREAM, uriMail);
startActivity(emailIntent);
It's works now!! Thanks :D
It looks like something is might be going wrong with your file path. Double check it. Then
1 - You need to add the package name of your application with context.getPackageName()
private String path = Environment.getExternalStorageDirectory().getPath() + context.getPackageName() + "books/"+fileName;
2 - Declare the permission inside your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I am doing a simple application that loads and saves files in java. I am trying to port it over to Android and am having trouble getting it to see the file.
The file path I am currently using is
private static final String SAVE_FILE_PATH = "data/save";
Here is the function that loads the data from the file:
public void loadData() throws FileNotFoundException {
File file = new File(SAVE_FILE_PATH);
Scanner scanner;
if (file.exists()) {
scanner = new Scanner(new FileInputStream(file));
try {
while (scanner.hasNextLine()) {
allPlayers.add(new Player(scanner.nextLine()));
}
} finally {
scanner.close();
}
}
else {
System.out.println("No file found");
}
} finally {
scanner.close();
}
}
}
While getExternalStorageDirectory() gets you the path to the SD card, consider using Activity.getExternalFilesDir() which will return (and create if necessary) a directory that's nominally private to your application. It also has the advantage that it will be auto-deleted for you if the application is uninstalled. This is new in API 8, so you might not want to use it if you're supporting older devices.
Otherwise, you'll have to follow ρяσѕρєя K's advice. Don't forget to create the storage directory you want to use. My code typically looks like this:
/**
* Utility: Return the storage directory. Create it if necessary.
*/
public static File dataDir()
{
File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory() ) {
// TODO: warning popup
Log.w(TAG, "Storage card not found " + sdcard);
return null;
}
File datadir = new File(sdcard, "MyApplication");
if( !confirmDir(datadir) ) {
// TODO: warning popup
Log.w(TAG, "Unable to create " + datadir);
return null;
}
return datadir;
}
/**
* Create dir if necessary, return true on success
*/
public static final boolean confirmDir(File dir) {
if( dir.isDirectory() ) return true;
if( dir.exists() ) return false;
return dir.mkdirs();
}
Now use this to specify your save file:
File file = new File(dataDir(), "save");
Scanner scanner;
if (file.exists()) {
// etc.
}