I have a notepad app that restores notes and backs them up. When manually backing up, it usually on android 10 would delete the folder then create it again with new files. Now with saf i cant figure out how to delete a chosen tree folder.
Heres my code but it doesnt work.
try {
muri = t.getString("muri", "");
Uri uri = Uri.parse(muri);
DocumentsContract.deleteDocument
(getApplicationContext().getContentResolver(), uri);
} catch (Exception e) {}
Figured it out
try {
muri = t.getString("muri", "");
Uri uri = Uri.parse(muri);
DocumentFile dir = DocumentFile.fromTreeUri(this, uri);
DocumentFile dir2 = dir.findFile("Godisgood");
dir2.delete();
} catch (Exception e) {}
Related
I have a camera that I am grabbing values pixel-wise and I'd like to write them to a text file. The newest updates for Android 12 requires me to use storage access framework, but the problem is that it isn't dynamic and I need to keep choosing files directory. So, this approach it succesfully creates my files but when writting to it, I need to specifically select the dir it'll save to, which isn't feasible to me, as the temperature is grabbed for every frame and every pixel. My temperature values are in the temperature1 array, I'd like to know how can I add consistently add the values of temperature1 to a text file?
EDIT: I tried doing the following to create a text file using getExternalFilesDir():
private String filename = "myFile.txt";
private String filepath = "myFileDir";
public void onClick(final View view) {
switch (view.getId()){
case R.id.camera_button:
synchronized (mSync) {
if (isTemp) {
tempTureing();
fileContent = "Hello, I am a saved text inside a text file!";
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filepath), filename);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Log.e("TAG", "file: "+myExternalFile);
}
isTemp = false;
//Log.e(TAG, "isCorrect:" + mUVCCamera.isCorrect());
} else {
stopTemp();
isTemp = true;
}
}
break;
I can actually go all the way to the path /storage/emulated/0/Android/data/com.MyApp.app/files/myFileDir/ but strangely there is no such file as myFile.txt inside this directory, how come??
Working Solution:
public void WriteToFile(String fileName, String content){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File newDir = new File(path + "/" + fileName);
try{
if (!newDir.exists()) {
newDir.mkdir();
}
FileOutputStream writer = new FileOutputStream(new File(path, filename));
writer.write(content.getBytes());
writer.close();
Log.e("TAG", "Wrote to file: "+fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
The application is working in every phone except one. And that phone shows this error.
In other phones the image path seems like this /storage/emulated/0/Android/data/com.example.x/files/x/Photos/x_20200415111325.jpg and works well.
Here is the image creation function
File storageDir = getExternalFilesDir("Photos");
File image = new File(storageDir.getAbsolutePath() + File.separator + photoName);
try {
image.createNewFile();
} catch (IOException e) {
CustomUtility.showAlert(this, "Image Creation Failed. Please contact administrator", "Error");
}
currentPhotoPath = image.getAbsolutePath();
Log.e("image path",currentPhotoPath);
return image;
I have a simple gallery app in which user can take or delete photos. For taking photos this works in notifying MediaStore of the newly created file:
File file = new File(storageDir, createImageName());
final Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);
I delete photos but local gallery app still shows them as a blank file.
This does not work. I target minimum Android 5.0 :
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Folder where application stores photos");
final Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);
What I'm trying to do is to scan the folder my application creates when a file deleted to inform MediaStore of the images and folders deleted. How can I do this?
Here is a method that deletes any record(s) of a media file from the MediaStore.
Note that the DATA column in the MediaStore refers to the file's full path.
public static boolean deleteFileFromMediaStore(
Context context, String fileFullPath)
{
File file = new File(fileFullPath);
String absolutePath, canonicalPath;
try { absolutePath = file.getAbsolutePath(); }
catch (Exception ex) { absolutePath = null; }
try { canonicalPath = file.getCanonicalPath(); }
catch (Exception ex) { canonicalPath = null; }
ArrayList<String> paths = new ArrayList<>();
if (absolutePath != null) paths.add(absolutePath);
if (canonicalPath != null && !canonicalPath.equalsIgnoreCase(absolutePath))
paths.add(canonicalPath);
if (paths.size() == 0) return false;
ContentResolver resolver = context.getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
boolean deleted = false;
for (String path : paths)
{
int result = resolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?",
new String[] { path });
if (result != 0) deleted = true;
}
return deleted;
}
I have problem with my JEditorPane, cannot load URL, always show java.io.FileNotFoundException. Totally I am confused how to solve it.
JEditorPane editorpane = new JEditorPane();
editorpane.setEditable(false);
String backslash="\\";
String itemcode="a91000mf";
int ctr=6;
File file = new File("file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode+"&jumlah="+String.valueOf(ctr)+"&lokasi=../images");
if (file != null) {
try {
//editorpane.addPropertyChangeListener(propertyName, listener)
editorpane.setPage(file.toURL());
System.out.println(file.toString());
} catch (IOException e) {
System.err.println(e.toString());
}
} else {
System.err.println("Couldn't find file: TextSamplerDemoHelp.html");
}
I just put "file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode", but it will show its same error : cannot open file, but I can open it in my browser
File expects a local file path, but "file://...." is a URI... so try this:
URI uri = new URI("file:///C:/Development/project2/OfflineSales/test/index.html?item_code="+itemcode+"&jumlah="+String.valueOf(ctr)+"&lokasi=../images");
File file = new File(uri);
You should remove all usage of the File class.
A string which starts with "file:" is a URL, not a file name. It is not a valid argument to a File constructor.
You are calling the JEditor.setPage method which takes a URL, not a File. There is no reason to create a File instance:
try {
URL url = new URL("file:///C:/Development/project2/OfflineSales/test/index.html?item_code=" + itemcode + "&jumlah=" + ctr + "&lokasi=../images");
editorpane.setPage(url);
} catch (IOException e) {
e.printStackTrace();
}
JEditorPane also has a convenience method which does the conversion of a String into a URL for you, so you can even skip the use of the URL class entirely:
String url = "file:///C:/Development/project2/OfflineSales/test/index.html?item_code=" + itemcode + "&jumlah=" + ctr + "&lokasi=../images";
try {
editorpane.setPage(url);
} catch (IOException e) {
e.printStackTrace();
}
(Notice that String.valueOf is not needed. It is implicitly invoked whenever you concatenate a String with any object or primitive value.)
Here are things I have done:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and
public void createMyFolder(){
File directory = new File(Environment.getExternalStorageDirectory().getPath() + "/myfolder/");
directory.mkdir(); //I had also tried mkdirs()
File file= new File(Environment.getExternalStorageDirectory().getPath() + "/t1.dat");
try {
file.createNewFile();
} catch (IOException e) {}
}
I tested 3 devices and one of them threw exception:
java.io.IOException: Cannot create dir /mnt/sdcard/myfolder
t1.dat was created successfully in /mnt/sdcard/ but myfolder was not.
The device is Xperia Ion with Android version 4.0.4. What's wrong about it and how can I fix it?
Edit: I had tried to create folders by some applications, like File Manager.
And they also failed to create although the sdcard is writable and readable.
I think my phone has some "protections" which do not allow me to create folders in sd card.
But it's funny that my phone allows me to create files instead.
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Replace Environment.getExternalStorageDirectory() with directory and also "/myfolder" will be "/myfolder"
public void createMyFolder(){
File directory = new File(Environment.getExternalStorageDirectory().getPath() + "/myfolder");
directory.mkdir(); //I had also tried mkdirs()
File file= new File(directory.getPath() + "/t1.dat");
try {
file.createNewFile();
} catch (IOException e) {}
}