Android: Deleted file but user data not free up. How can fix? - java

My app can get image add in to folder "photo" and delete it, but after deleted image in folder "photo" user data not free up although i checked files explorer in android studio and log really deleted. I save the file in internal storage (app private storage) not external. How i can fix?
public class InternalStorageHelper {
public static String saveToInternalStorage(Bitmap bitmapImage, Context context, String fileName) {
File directory = new File(context.getApplicationInfo().dataDir, "photo");
if (!directory.exists()) {
directory.mkdirs();
}
// Create imageDir
File myPath = new File(directory, fileName+ ".jpg");
FileOutputStream fos = null;
if (myPath.exists()) {
myPath.delete();
}
try {
fos = new FileOutputStream(myPath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
return myPath.getAbsolutePath();
}
public static Bitmap loadImageFromStorage(String path) {
try {
File f = new File(path);
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static void deleteFile(String path) {
File fdelete = new File(path);
if (fdelete.exists()) {
if (fdelete.delete()) {
Log.d("progress", "file Deleted :" + path);
} else {
Log.d("progress", "file not Deleted :" + path);
}
}
}
}

Related

The Pic's corrupted in screenshotting programmatically in Android Studio

this is the code for the screenshot that redirect the screenshot in /Pictures/Lones but the picture is corrupted every time that it is getting uploaded.
public void Saves(View view){
int count = 0;
File sdDirectory = Environment.getExternalStorageDirectory();
File subDirectory = new File(sdDirectory.toString() + "/Pictures/Lones");
if (subDirectory.exists()) {
File[] existing = subDirectory.listFiles();
for (File file : existing) {
if (file.getName().endsWith(".jpg") || file.getName().endsWith(".png")) {
count++;
}
}
} else {
subDirectory.mkdir();
}
if (subDirectory.exists()) {
File image = new File(subDirectory, "/drawing_" + (count + 1) + ".png");
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(image);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
this is the result every time it is getting screenshotted

Camera2, Images get saved to gallery as blank images with exclamation mark

Don't know why it's doing this, here's my code, maybe I did something wrong and don't realize it?
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage()));
}
};
private class ImageSaver implements Runnable{
private final Image mImage;
public ImageSaver(Image image){
mImage = image;
}
#Override
public void run(){
ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes= new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
FileOutputStream fileOutputStream = null;
try{
fileOutputStream = new FileOutputStream(mImageFileName);
fileOutputStream.write(bytes);
}
catch(IOException e){
e.printStackTrace();
}
finally{ //finally cleans up the resources created in this runnable
mImage.close();
if (fileOutputStream !=null){
try{
fileOutputStream.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
}
private void createImageFolder() {
File imageFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
mImageFolder = new File(imageFile, "camera2VideoImage");
if (!mImageFolder.exists()) {
mImageFolder.mkdirs();
}
}
private File createImageFileName() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String prepend = "IMAGE_" + timestamp + "_";
File imageFile = File.createTempFile(prepend, ".jpg", mImageFolder);
mImageFileName = imageFile.getAbsolutePath();
return imageFile;
}
This code should work, I receive no error in Log-cat. I take my pictures but when I look at what's saved in gallery, the picture appears as a grey screen with a white encircled exclamation mark. What have I done wrong or not included?

Images corrupt on local storage after bringing them in from a URL

So I have it that when an in-app item is purchased the image they purchased is downloaded onto the phone. Works fine on external storage but I want it on INTERNAL storage. I'm using Picasso to load it into a bitmap then put into a PNG file. I'm not sure why it's getting corrupted along the way on internal storage. When the SD card is perfectly fine.
Anyone have any ideas why this is happening? Thanks!
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
//Internal storage
String path = getFilesDir().getAbsolutePath();
File imageFile = new File(path, "image.png");
FileOutputStream fos = null;
//TO SD Storage
File file = new File(
Environment.getExternalStorageDirectory().getPath());
File fileName = new File(file, "scrone.png");
if (isSDPresent) {
if (!fileName.getName().equals("scrone.png")) {
try {
FileOutputStream ostream = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
} else if (fileName.getName().equals("scrone.png")) {
try {
fileName = new File(file, "scrtwo.png");
FileOutputStream ostream = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//I'm sorry for the mess you're about to witness
else if(!imageFile.exists()){
try {
Log.d(TAG, "File doesn't exist");
fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
else if(imageFile.exists())
{
try
{
Log.d(TAG, "File does exist");
imageFile = new File("image2.png");
fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 75, fos);
fos.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}).start();
}

Java save mp3 file

I am trying to create import images and mp3 files from one directory using a file chooser and save them to another . The images went fine but I cant seem to find out how to save the mp3 file .
Images
#Override
public void saveFile(File file) {
//Get image path
String imagePath = file.getAbsolutePath();
String imageName = file.getName();
System.out.println(imagePath);
//Read image
try {
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bufferedImage = ImageIO.read(new File(imagePath));
System.out.println("Reading complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
//write image
try {
f = new File("H:\\TestFolder\\images\\" + imageName); //output file path
ImageIO.write(bufferedImage, "jpg", f);
System.out.println("Writing complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
Mp3
#Override
public void saveFile(File file) {
try{
f = new File(file, "H:\\TestFolder\\test.mp3"); //file.getAbsolutePath();
}catch (Exception e) {
e.printStackTrace();
}
}
Use Files.copy(source, target, REPLACE_EXISTING);
https://docs.oracle.com/javase/tutorial/essential/io/copy.html
Try it like this:
File f = new File("H:\\TestFolder\\test.mp3");
InputStream is = new FileInputStream(f);
OutputStream outstream = new FileOutputStream(new File("H:\\TestFolder2\\blabla.mp3"));
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
outstream.close();

merge audio and video file in android

i'm using mp4parser to merge audio and video files, here is below example i have tried but i'm getting null pointer exception at the very first line itself. i have kept audio and video files at desired location in my phone internal memory. if i debug, first line take lots of time & just halts after mins with null pointer error
try
{
H264TrackImpl h264Track = new H264TrackImpl(new FileDataSourceImpl("/mnt/sdcard/myvideo/video.mp4"));
AACTrackImpl aacTrack = new AACTrackImpl(new FileDataSourceImpl("/mnt/sdcard/myvideo/audio.acc"));
Movie movie = new Movie();
movie.addTrack(h264Track);
movie.addTrack(aacTrack);
Container mp4file = new DefaultMp4Builder().build(movie);
FileChannel fc = new FileOutputStream(new File("output.mp4")).getChannel();
mp4file.writeContainer(fc);
fc.close();
} catch (Exception ee)
{
Toast.makeText(this,ee.getMessage(),Toast.LENGTH_LONG).show();
}
whats wrong in my above code?
**Try this
I have follow few things to merge audio and video.
1)Capture Blank Video Dont use any audio source like
"mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);"
2)save it to the sd card
3)it does not support MIME type=mp3.
4)so if we have to merge video and video. audio must be mp4 or aac
.**
5)call the method on button click or On Crete
String audiopath = "/sdcard/audio.m4a";
String videopath = "/sdcard/video.mp4";
String outputpath = "/sdcard/output.mp4";
mux(video, audio, output);
6)Main Code is here pass it only path where you store your video, audio(m4a,aac),Output path.
public boolean mux(String videoFile, String audioFile, String outputFile) {
Movie video;
try {
video = new MovieCreator().build(videoFile);
} catch (RuntimeException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Movie audio;
try {
audio = new MovieCreator().build(audioFile);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
Track audioTrack = audio.getTracks().get(0);
video.addTrack(audioTrack);
Container out = new DefaultMp4Builder().build(video);
FileOutputStream fos;
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
try {
out.writeContainer(byteBufferByteChannel);
byteBufferByteChannel.close();
Log.e("Audio Video", "11");
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private static class BufferedWritableFileByteChannel implements WritableByteChannel {
// private static final int BUFFER_CAPACITY = 1000000;
private static final int BUFFER_CAPACITY = 10000000;
private boolean isOpen = true;
private final OutputStream outputStream;
private final ByteBuffer byteBuffer;
private final byte[] rawBuffer = new byte[BUFFER_CAPACITY];
private BufferedWritableFileByteChannel(OutputStream outputStream) {
this.outputStream = outputStream;
this.byteBuffer = ByteBuffer.wrap(rawBuffer);
Log.e("Audio Video", "13");
}
#Override
public int write(ByteBuffer inputBuffer) throws IOException {
int inputBytes = inputBuffer.remaining();
if (inputBytes > byteBuffer.remaining()) {
Log.e("Size ok ", "song size is ok");
dumpToFile();
byteBuffer.clear();
if (inputBytes > byteBuffer.remaining()) {
Log.e("Size ok ", "song size is not okssss ok");
throw new BufferOverflowException();
}
}
byteBuffer.put(inputBuffer);
return inputBytes;
}
#Override
public boolean isOpen() {
return isOpen;
}
#Override
public void close() throws IOException {
dumpToFile();
isOpen = false;
}
private void dumpToFile() {
try {
outputStream.write(rawBuffer, 0, byteBuffer.position());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Categories