How can I rename a video gotten from mediastore without deleting or corrupting it?
I tried using this code gotten from a similar question but it deletes or corrupts the video whose name I changed.
String title = editTextTitle.getText().toString().trim();
video.setTitle(title);
File parentFile = videoFile.getParentFile();
if (parentFile != null) {
String path = parentFile.getAbsolutePath();
String extension = videoFile.getAbsolutePath(); extension = extension.substring(extension.lastIndexOf("."));
String newPath = path + "/" + title + extension;
File newFile = new File(newPath);
boolean rename = videoFile.renameTo(newFile); if (rename) {
ContentResolver resolver = context.getContentResolver(); resolver.delete(MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?", new String[]{videoFile.getAbsolutePath()});
Toast.makeText(context, "renamed", Toast.LENGTH_SHORT). show();
}
}
Finally solved it
textViewRename.setOnClickListener(v1 -> { String title = editTextTitle.getText().toString().trim(); video.setTitle(title);
String extension = videoFile.getAbsolutePath(); extension = extension.substring(extension.lastIndexOf("."));
ContentValues values = new ContentValues(2); values.put(MediaStore.Video.Media.TITLE, title);
values.put(MediaStore.Video.Media.DISPLAY_NAME, title + extension );
context.getContentResolver().update(MediaStore.Video.Media. EXTERNAL_CONTENT_URI, values,
MediaStore.MediaColumns.DATA + "=?", new String[]{videoFile. getAbsolutePath()});
if (videoOptionListener != null) { videoOptionListener.onEdit();
} dialogRenameVideo.dismiss(); });
Related
Hey I'm trying to delete a image (file) but I can't :(
That how I upload the image:
try {
List<String> imagesPaths = new ArrayList<>();
for (String image : imagesBytes)
{
String base64Image = image.split(",")[1];
byte[] imageByte = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
String folder = "C:/images/" + LoggedInUser.UserId();
File newDirectory = new File(folder);
if (!newDirectory.exists())
{
newDirectory.mkdirs();
}
long timeMilli = new Date().getTime();
String imageType = image.substring("data:image/".length(), image.indexOf(";base64"));
String path = timeMilli + "." + imageType;
Files.write(Paths.get(folder, path), imageByte);
String newPath = LoggedInUser.UserId() + "/" + path;
imagesPaths.add(newPath);
}
logger.debug("uploadImages() in ImageService Ended by " + LoggedInUser.UserName());
return new ResponseEntity<>(imagesPaths, HttpStatus.OK);
} catch (Exception e) {
throw new ApiRequestException(e.getMessage());
}
And this how I delete it :
List<ImageJpa> images = imageRepository.findByStatus(Image.UNUSED.status);
System.out.println(images.size() + ": Images are not used");
images.forEach(image -> {
String imagePath = "C:/images/" + image.getPath();
System.out.println(imagePath);
File imagePathFile = new File(imagePath);
if (imagePathFile.exists())
{
boolean isDeleted = imagePathFile.delete();
if (isDeleted)
{
imageRepository.deleteById(image.getId());
System.out.println("Deleted the file: " + imagePathFile.getName());
} else {System.out.println("Failed to delete the file. :" + imagePathFile.getName());}
}else {
System.out.println("Already Deleted");
}
});
Always I got (Failed to delete the file ...)
Note : The image will deleted if I ReRender the the project again or close and open the IDE.
The problem was on other function :\
I was open the files after save it without CLOSE the connection after it !
This one what was messing on the read files
inputStream.close();
I'm working on scanner app. My problem is while retrieve saved image from scoped storage in Android 10 and 11. Image is saved successfully but I am not able to retrieve it. When I get path of save image bitmap is null.
Here is the code to save the image in Android 11:
File dirDest = new File(Environment.DIRECTORY_PICTURES, context.getString(R.string.app_name));
Long date = System.currentTimeMillis();
String extension = ".jpg";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, date + extension);
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/" + extension);
contentValues.put(MediaStore.Images.Media.DATE_ADDED, date);
contentValues.put(MediaStore.Images.Media.DATE_MODIFIED, date);
contentValues.put(MediaStore.Images.Media.SIZE, bitmap.getByteCount());
contentValues.put(MediaStore.Images.Media.WIDTH, bitmap.getWidth());
contentValues.put(MediaStore.Images.Media.HEIGHT, bitmap.getHeight());
contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, dirDest + File.separator);
Uri newImageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
FileOutputStream fos = (FileOutputStream) resolver.openOutputStream(Objects.requireNonNull(newImageUri));
callback.write(fos);
fos.flush();
fos.close();
return String.valueOf(dirDest) + date + extension;
Here is the code to retrieve the save image from shared storage in scoped storage in Android 11. I am getting issue in this part of code, bitmap is null. I am not getting the main point of the problem. In the end the problem is FileNotFoundException.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
String[] file = {MediaStore.Images.Media._ID,
MediaStore.Images.Media.RELATIVE_PATH,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.SIZE,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.WIDTH,
MediaStore.Images.Media.HEIGHT,
MediaStore.Images.Media.DATE_MODIFIED};
if (uri != null) {
cursor = context.getContentResolver().query(uri, file, null, null, null);
if (cursor != null) {
try {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(file[0]);
File path = new File(uri.getPath());
bitmap = BitmapFactory.decodeFile(path.getAbsolutePath());
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You can query them all with the help of SimpleStorage:
val images: List<MediaFile> = MediaStoreCompat.fromMediaType(applicationContext, MediaType.IMAGE)
images.forEach {
println(it.absolutePath)
}
Hello guys i am trying to get the absolute path of audio file in android api level 29 i.e, Q but the problem is that DATA is deprecated so how to resolve this problem and also using the absolute path (e.x : storage/sdcard/music.mp3) we can get the embedded picture to that audio but in content uri (content://) that we can get using the _ID Column by appending the id of the file.But if we are not able to to get the absolute path then how to play an audio file using content:// Uri ?
The previous codes that i am using is :
public ArrayList<Song> FolderFilesList(Context context, String FolderPath) {
//folder-exclude-sub-folders
ArrayList<Song> songs = new ArrayList<>();
String[] columns = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.TRACK,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.DISPLAY_NAME,
};
String selection = MediaStore.Audio.Media.DATA + " LIKE ? AND " + MediaStore.Audio.Media.DATA + " NOT LIKE ? ";
String[] selectionArgs = new String[]{
"%" + FolderPath + "%",
"%" + FolderPath + "/%/%"
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
columns(), selection, selectionArgs, null);
if (cursor.moveToFirst()) {
do {
Song song = new Song(
cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)),
cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.TRACK)),
cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
);
//File f = new File(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
// if (f.isFile() && f.exists()) {
songs.add(song);
//}
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return songs;
}
You won't be able to get the absolute path now but you can get content uri and using that content uri means (content://) and use it to write file in your cache directory of your package folder using the below code :
String filePath = new File(resolver.openFileDescriptor(contentUri, "r");
And then use InputStream and OutputStream to store it in cache directory and use this filePath to as a File.
Use this line in application in the Manifest file
android:requestLegacyExternalStorage="true"
I am using the MediaStore and ContentResolver API to save image files (jpg/png/gif) using MediaStore.Images.
It works, but the problem is that all the files are saved with the .jpg extension and the file name is always "the current time in millis.jpg".
Here is an example of what I put in the ContentValues:
date_added=1575480356 _display_name=2067623.gif date_modified=1575480356 mime_type=image/gif
But after inserting it to the ContentResolver and writing the file, the display name changes to 2067623.jpg and the file name to 1575480356.jpg.
How do I get it to keep the file name and extension?
Code:
ContentResolver resolver = activity.getContentResolver();
Uri mediaCollection;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
mediaCollection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
} else {
mediaCollection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues mediaDetails = new ContentValues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
final String relativeLocation = Environment.DIRECTORY_PICTURES + File.separator + "my_folder";
mediaDetails.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
mediaDetails.put(MediaStore.Images.Media.IS_PENDING, 1);
mediaDetails.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation);
}
String mimeType = "image" + "/" + getExtension(p); // jpg/png/gif
mediaDetails.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
mediaDetails.put(MediaStore.Images.Media.MIME_TYPE, mimeType);
mediaDetails.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
mediaDetails.put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000);
Uri contentUri = resolver.insert(mediaCollection, mediaDetails);
write(contentUri, resolver, p, fileName); // Write the file content using resolver.openOutputStream(contentUri)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
mediaDetails.clear();
mediaDetails.put(MediaStore.Images.Media.IS_PENDING, 0);
resolver.update(contentUri, mediaDetails, null, null);
}
Did you find a soution? I did not, so I end up doing this:
private void addImageToGalleryLegacy(#NonNull final String imagePath, #NonNull final String fileName) throws IOException {
File fIn = new File(imagePath);
String outPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File fOut = new File(outPath, fileName);
FileInputStream in = new FileInputStream(fIn);
FileOutputStream out = new FileOutputStream(fOut);
copy(in, out);
}
Basically (as we are in pre Q) we can copy the image straight to the gallery.
"imagePath" is "Android/data/[package name]/files/Pictures" in my case.
I am working on java project. In this I have done the code to convert ods file to html and then open that converted file in browser.
Below is my code :-
private String ConvertOdtAndOdsToHTML(String sDocPath, String finalDestinationPath, String downloadImagePath, String returnPath) {
try {
String root = finalDestinationPath;
int lastIndex = sDocPath.lastIndexOf(File.separator);
String sFileName = sDocPath.substring(lastIndex + 1, sDocPath.length());
String fileNameWithOutExt = FilenameUtils.removeExtension(sFileName);
String fileOutName = root + File.separator + fileNameWithOutExt + ".html";
InputStream in = new FileInputStream(new File(sDocPath));
String ext = FilenameUtils.getExtension(sDocPath);
OdfTextDocument document = null;
OdfSpreadsheetDocument odfSpreadsheetDocument = null;
if (ext.equalsIgnoreCase("odt")) {
document = OdfTextDocument.loadDocument(in);
}
else if (ext.equalsIgnoreCase("ods")) {
odfSpreadsheetDocument = OdfSpreadsheetDocument.loadDocument(in);
}
org.odftoolkit.odfdom.converter.xhtml.XHTMLOptions options = org.odftoolkit.odfdom.converter.xhtml.XHTMLOptions.create();
// Extract image
String sLocalSystemImagePath = finalDestinationPath + File.separator+"images"+File.separator;
File imageFolder = new File(sLocalSystemImagePath);
options.setExtractor( new org.openskye.resource.FileImageExtractor( imageFolder ) );
// URI resolver
String localHostImagePath = downloadImagePath + File.separator+"images"+File.separator;
FileResolverOdt fileURIResolver = new FileResolverOdt(new File(localHostImagePath));
options.URIResolver(fileURIResolver);
// URI resolver
OutputStream out = new FileOutputStream(new File(fileOutName));
if (ext.equalsIgnoreCase("odt")) {
org.odftoolkit.odfdom.converter.xhtml.XHTMLConverter.getInstance().convert(document, out, options);
}
else if (ext.equalsIgnoreCase("ods")) {
org.odftoolkit.odfdom.converter.xhtml.XHTMLConverter.getInstance().convert(odfSpreadsheetDocument, out, options);
}
return returnPath + File.separator + fileNameWithOutExt + ".html";
} catch (Exception e) {
return "Failed to open the document: " + sDocPath + " due to error:" + e.getMessage();
}
}
I am able to convert ods file to html and file is getting open in browser also but it is displaying some question marks ???? and date and time in browser.
I just want to display the file as it gets open in open office without displaying date time and any special character. Also I want to differentiate the sheets.
Here is ods file which I want to convert Link
Below is attached screenshot for the ods file that is converted to html
I would be thankful if anyone could help me in finding the solution.