How to delete all images saved in /Android/media/<package name> - android

I use FileProvider in my code, which automatically save images captured with camera into /Android/media/com.app.surveyapp, like this:
AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.app.surveyapp"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
CaptureActivity.java
btnCapture.setOnClickListener(v -> {
File file = new File(getExternalMediaDirs()[0], System.currentTimeMillis() + ".jpg");
});
How to empty that directory?

private void RemoveImageFiles()
{
try
{
String path = Constants.IMG_FILEPATH;
int FIndex;
File directory = new File(path);
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++)
{
FName = files[i].getName();
File FilesName=new File(path + File.separator + FName);
FilesName.delete();
}
}
catch(Exception ex)
{
seterror(ex.getMessage());
}
}

Related

Unable to attach text file to Gmail in Android

I am writing some texts to a file in cache memory. i want to sent email with that file as attachment. Tried below code but i am getting toast message says 'Unable to attach file'.
File creation and code to write data
String fileName="cachelog.txt";
File cacheFile = new File(context.getCacheDir(), fileName);
if (!cacheFile.exists())
{
cacheFile.createNewFile();
}
}
if(cacheFile.exists())
{
FileOutputStream fos = null;
fos = new FileOutputStream(cacheFile,true);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8");
BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(fos));
buf.append(logData);
buf.flush();
buf.close();
}
Email code
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
String[] to = {"testing#gmail.com"};
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
File file = new File(context.getCacheDir(), fileName);
Uri uri = FileProvider.getUriForFile(context,
context.getApplicationContext().getPackageName() + ".helper.ProviderClass", file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(intent)
Manifest file
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.test.medapp.helper.ProviderClass"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/cachefile" />
</provider>
<cache-path
name="cache"
path="." />
Create File
String fileName="cachelog.txt";
File file = null;
if(Build.VERSION.SDK_INT >= 30){ //Build.VERSION_CODES.R
file = new File(context.getFilesDir() + "/" + fileName);
}else {
file = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
}
if (!file.exists())
file.mkdirs();
if(file.exists())
{
FileOutputStream fos = null;
fos = new FileOutputStream(file,true);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8");
BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(fos));
buf.append(logData);
buf.flush();
buf.close();
}
Send File
String filePath = "/cachelog/cachelog.txt";
File file = null;
if(Build.VERSION.SDK_INT >= 30){ //Build.VERSION_CODES.R
file = new File(getActivity().getFilesDir() + "/" + filePath);
}else {
file = new File(Environment.getExternalStorageDirectory() + "/" + filePath);
}
String mimetype = getMimeType(file.getAbsoluteFile());
Uri uri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".provider_paths", file);
Intent intentaaa = ShareCompat.IntentBuilder.from((Activity) getActivity())
.setStream(uri) // uri from FileProvider
.getIntent()
.setAction(Intent.ACTION_SEND) //Change if needed
.setDataAndType(uri, mimetype)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getActivity().startActivity(intentaaa);
public static String getMimeType(File file) {
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
// Let's check the official map first. Webkit has a nice extension-to-MIME map.
// Be sure to remove the first character from the extension, which is the "." character.
if (extension.length() > 0) {
//String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
String webkitMimeType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (webkitMimeType != null)
return webkitMimeType;
}
return "*/*";
}
create provider_paths.xml
<files-path
name="share"
path="external_files" />
<external-path
path="Android/data/"
name="files_root" />
<external-path
name="pictures"
path="Pictures/" />
<external-path
name="storage/emulated"
path="." />
<root-path
name="root"
path="." />
Add provider_paths in AndroidManifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider_paths"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths"
tools:replace="android:resource" />
</provider>

Save file to internal storage and show in gallery

I should save an image (byte []) inside the internal memory and make it visible inside the gallery, but the following code does not work, what's wrong? the file is not saved and shown in the gallery but no error is generated
private void saveImageToDisk(final byte[] bytes) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-hh:mm");
String todayDate = dateFormat.format(new Date());
Log.d("Foto data: ",todayDate);
File file = new File(context.getFilesDir(), "image.jpg");
try (final OutputStream output = new FileOutputStream(file)) {
output.write(bytes);
output.close();
} catch (final IOException e) {
Log.e("TAG", "Exception occurred while saving picture to storage ", e);
}
Log.d("Foto","File salvato"+ file.getAbsolutePath());
addPicToGallery(file.getPath());
}
private void addPicToGallery(String photoPath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File(photoPath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
To save an image to internal storage you can use the function below:
String saveImage(Context context, Bitmap image) {
String savedImagePath = null;
// Create the new file in the external storage
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + ".jpg";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/YourAppName");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
// Save the new Bitmap
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(context, savedImagePath);
// Show a Toast with the save location
String savedMessage = context.getString(R.string.saved_message, savedImagePath);
Toast.makeText(context, savedMessage, Toast.LENGTH_SHORT).show();
}
return savedImagePath;
}
This function takes context and Bitmap image as the parameters and returns the path of the file stored.
And to make the image visible to default gallery:
static void galleryAddPic(Context context, String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
You need to pass the context and path of the image stored to this function. This second function is called inside the first function.
And I am not sure if you would need to actually make a FileProvider for these purposes, but if you do.
In you AndroidManifest.xml inside of the <application> tag , use following:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="<YOUR.PACKAGE.NAME>.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
And create a new Resource directory. Right click 'res'>>New Android Resource Directory. Choose 'xml' from the dropdown. Then right click the xml folder and create a file called file_paths wherein put:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-cache-path name="my_cache" path="." />
<external-path name="my_images" path="Pictures/" />
</paths>
Save file to internal storage and show in gallery
That is not possible, sorry.
but the following code does not work, what's wrong?
Third-party apps, including the MediaStore and galleries, have no rights to access your files on internal storage.

Android share app's apk using FileProvider

I've tried to share the app's apk file through intent.The provider in my manifest file:
`<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="package name"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/mypaths" />
and the mypaths file is:
<paths>
<external-path name="apk_folder"/>
</paths>
I set intent and the File path as below:
String packageName = getContext().getPackageName();
PackageManager pm = getContext().getPackageManager();
String apk = null;
try {
ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
apk = ai.publicSourceDir;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
File apkFile = new File(apk);
Uri uri = FileProvider.getUriForFile(getContext(), "package name", apkFile);
Intent intent = ShareCompat.IntentBuilder.from(getActivity())
.setType("*/*")
.setStream(uri)
.setChooserTitle("Share via")
.createChooserIntent()
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
I get IllegalArgumentException :
Failed to find configured root that contains /data/app/package name.edu-1/base.apk
Please help me to find out my mistakes.
change the "package name" in your code to activity.getPackageName() and cahnge path to root-path
or try This codes:
in Manifest
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"/>
</provider>
in res/xml/file_paths.xml
<paths>
<root-path
name="app"
path="/"/>
</paths>
Code :
public static void sendApkFile(Activity activity) {
try {
PackageManager pm = activity.getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(activity.getPackageName(), 0);
File srcFile = new File(ai.publicSourceDir);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
Uri uri = FileProvider.getUriForFile(context, activity.getPackageName(), srcFile);
intent.putExtra(Intent.EXTRA_STREAM, uri);
activity.grantUriPermission(activity.getPackageManager().toString(), uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
And IF you Want to APK File have any other name , not just base.APK , try this
public static void sendApplication(Activity activity) {
ApplicationInfo app = activity.getApplicationContext().getApplicationInfo();
String filePath = app.sourceDir;
Intent intent = new Intent(Intent.ACTION_SEND);
// MIME of .apk is "application/vnd.android.package-archive".
// but Bluetooth does not accept this. Let's use "*/*" instead.
intent.setType("*/*");
// Append file and send Intent
File originalApk = new File(filePath);
try {
//Make new directory in new location
File tempFile = new File(activity.getExternalCacheDir() + "/ExtractedApk");
//If directory doesn't exists create new
if (!tempFile.isDirectory()) {
if (!tempFile.mkdirs()) {
return;
}
}
//Get application's name and convert to lowercase
tempFile = new File(tempFile.getPath() + "/" + activity.getString(app.labelRes).replace(" ", "").toLowerCase() + ".apk");
//If file doesn't exists create new
if (!tempFile.exists()) {
if (!tempFile.createNewFile()) {
return;
}
}
//Copy file to new location
InputStream in = new FileInputStream(originalApk);
OutputStream out = new FileOutputStream(tempFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
//Open share dialog
Uri uri = FileProvider.getUriForFile(context, activity.getPackageName(), tempFile);
intent.putExtra(Intent.EXTRA_STREAM, uri);
activity.grantUriPermission(activity.getPackageManager().toString(), uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
i can solve exact this problem, only use:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<root-path path="data/app/" name="external_files"/>
</resources>
There is no available root in FileProvider that will handle your designated location. You would need to create your own ContentProvider for this.

How to see list of files stored in a directory

I have built an app that makes a folder in the storage of the device. Here is the code I'm using:
File wDirectory = new File("/sdcard/W/");
wDirectory.mkdirs();
File outputFile = new File(wDirectory, filename);
FileOutputStream fos = new FileOutputStream(outputFile);
Now I want to know how do I show files in a list view in this directory.
paste your folder path....
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}

I am unable to locate my saved text file in phone memory

I am using this code to store a text file with the name of the time the 'Start' button in the app is pressed and further read it. I am trying to save the file in the memory where the app is installed by the user (i.e. SD Card or Phone Memory). The file I am storing is read and displayed in the logcat just fine but I can't find where is it saved in the memory (Phone or SD).
public void write_data(String s, Queue<SeismicDataPoint> t) throws IOException {
String path = getBaseContext().getFilesDir().getAbsolutePath();
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
FileOutputStream fOut = getBaseContext().openFileOutput(s + ".txt", MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
SeismicDataPoint temp ;
for(int i = 0; i < bufferSize; i++)
{
temp=t.poll();
osw.append(temp.timestamp+" "+temp.x+" "+temp.y+" "+temp.z+"\n");
}
osw.flush();
osw.close();
}
public void read_data(String s) throws IOException {
BufferedReader b = new BufferedReader(new FileReader(s+".txt"));
while(true){
String osw = b.readLine();
if(osw==null)break;
}
Here is the manifest file too:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.falldetect" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
getFilesDir point to internal storage directory. If you want something to store externally, then you should use path as
String path = Environment.getExternalStorageDirectory().toString();
Read this too http://www.grokkingandroid.com/how-to-correctly-store-app-specific-files-in-android/
Update:Check this code
private void saveFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/files");
myDir.mkdirs();
File file = new File (myDir, "sample.txt");
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(out);
pw.println("my sample txt");
pw.flush();
pw.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Application private Data files are stored within <internal_storage>/data/data/<package>
If file is created as MODE_PRIVATE it is not possible to see/access that with apps such as a FileManager,etc.

Categories

Resources