Android copy images to zip - java

I have a code here it pick image on the gallery and copy the images it pick and zip those. It run smoothly on copying the file. When i include the zip function it gets error on
Compress c = new Compress(path, targetPath+ picturename);.
Here is the code:
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_MULTIPLE = 100;
public static String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
//Setting a directory that is already created on the Storage to copy the file to.
public static String targetPath = ExternalStorageDirectoryPath + "BrokenDave" + File.separator;
String picturename = getPicturename();
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnClickGallery(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case PICK_IMAGE_MULTIPLE:
if (data != null && data.getData() != null) {
Uri uri = data.getData();
path = getPath(uri);
copyFileOrDirectory(path, targetPath + picturename);
Compress c =new Compress(path, targetPath + picturename); //first parameter is d files second parameter is zip file name
c.zip(); //call the zip function
Toast.makeText(this, "File zipped" + path, Toast.LENGTH_SHORT).show();
//get error on calling the zip function
} else {
// Select Multiple
ClipData clipdata = data.getClipData();
if (clipdata != null) {
for (int i = 0; i < clipdata.getItemCount(); i++) {
ClipData.Item item = clipdata.getItemAt(i);
Uri uri = item.getUri();
//ito un path
path = getPath(uri);
//ito un pag copy
copyFileOrDirectory(path, targetPath + picturename);
Compress c =new Compress(path, targetPath + picturename);
c.zip(); //call the zip function
Toast.makeText(this, "Files Deleted" + path, Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
public void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
if (destFile != null) {
// pag delete ng file
sourceFile.delete();
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(sourceFile));
sendBroadcast(scanIntent);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
private String getPicturename() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmm");
String timestamp = sdf.format(new Date());
return "Img" + timestamp + ".jpg";
}
}
Here is the compress.java
public class Compress {
private static final int BUFFER = 2048;
public static String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
//Setting a directory that is already created on the Storage to copy the file to.
public static String targetPath = ExternalStorageDirectoryPath + "BrokenDave" + File.separator;
private String[] _files;
// private String targetPath;
public Compress(String[] files, String targetPath) {
_files = files;
}
public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(targetPath);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for(int i=0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

Related

When i select image from recent then image is broken in android | Multiple images from recent

This error occurs mostly times when select images from recent folder
class com.bumptech.glide.load.engine.GlideException: Received null model
Call multiple images select
Sample Preview
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
*gallery*.launch(i);
gallery basically startActivityForResult(i,123) and OnActivityResult method is deprecated, the gallery is alternative which is defined below
ActivityResultLauncher<Intent> gallery = choosePhotoFromGallery();
and choosePhotoFromGallery() is method which is define below
private ActivityResultLauncher<Intent> choosePhotoFromGallery() {
return registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
try {
if (result.getResultCode() == RESULT_OK) {
if (null != result.getData()) {
if (result.getData().getClipData() != null) {
ClipData mClipData = result.getData().getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
String imageFilePathColumn = getPathFromURI(this, uri);
productImagesList.add(imageFilePathColumn);
}
} else {
if (result.getData().getData() != null) {
Uri mImageUri = result.getData().getData();
String imageFilePathColumn = getPathFromURI(this, mImageUri);
productImagesList.add(imageFilePathColumn);
}
}
} else {
showToast(this, "You haven't picked Image");
productImagesList.clear();
}
} else {
productImagesList.clear();
}
} catch (Exception e) {
e.printStackTrace();
showToast(this, "Something went wrong");
productImagesList.clear();
}
});
}
and getPathFromURI() is method which define below
public String getPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = getPath();
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
and the getPath() is
private File getPath() {
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
if (!folder.exists()) {
folder.mkdir();
}
return new File(folder.getPath(), System.currentTimeMillis() + ".jpg");
}
THANK YOU IN ADVANCE HAPPY CODING

How to create a video file path on Android 10

I tried to create a video file path as the follows :
String fileName = videoFileName = "VID" + System.currentTimeMillis() + ".mp4";
public static String createVideoPath(Context context, String fileName) {
File imageThumbsDirectory = context.getExternalFilesDir("FOLDER");
if (imageThumbsDirectory != null) {
if (!imageThumbsDirectory.exists()) {
imageThumbsDirectory.mkdir();
}
}
String appDir = context.getExternalFilesDir("FOLDER").getAbsolutePath();
File file = new File(appDir, fileName);
return file.getAbsolutePath();
}
I call the method above like this : String videoPath = createVideoPath(getApplicationContext(),fileName);
I use this library for edits :
EZFilter.input(mainBitmap).addFilter(null).enableRecord(videoPath, true, false).into(renderView);
After the edit finished, I try to save the final video to the gallery as follows :
private static Uri publicDirURI(Context context, String fileName, String dir) {
ContentValues valuesVideos;
valuesVideos = new ContentValues();
valuesVideos.put(MediaStore.Video.Media.RELATIVE_PATH, dir);
valuesVideos.put(MediaStore.Video.Media.TITLE, fileName);
valuesVideos.put(MediaStore.Video.Media.DISPLAY_NAME, fileName);
valuesVideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesVideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesVideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
valuesVideos.put(MediaStore.Video.Media.IS_PENDING, 1);
ContentResolver resolver = context.getContentResolver();
Uri collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri uriSavedVideo = resolver.insert(collection, valuesVideos);
return saveFileToPublicMovies(context, valuesVideos, uriSavedVideo, fileName);
}
private static Uri saveFileToPublicMovies(Context context, ContentValues contentValues, Uri uriSavedVideo, String fileName) {
ParcelFileDescriptor pfd;
try {
pfd = context.getContentResolver().openFileDescriptor(uriSavedVideo, "w");
FileOutputStream out = null;
if (pfd != null) {
out = new FileOutputStream(pfd.getFileDescriptor());
File videoFile = new File(context.getExternalFilesDir("FOLDER"), fileName);
FileInputStream in = new FileInputStream(videoFile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
pfd.close();
}
} catch (Exception e) {
e.printStackTrace();
}
contentValues.clear();
contentValues.put(MediaStore.Video.Media.IS_PENDING, 0);
context.getContentResolver().update(uriSavedVideo, contentValues, null, null);
return uriSavedVideo;
}
But I always get an empty saved video with 0.00b, I've tried the app with device running Android 9, but with getExternalStoragePublicDirectory, and everyting works just fine, so the issue is not related with the library.
Could anyone help me to solve this issue, I'm stuck on it almost 1 week, thank you
Edit :
private static Uri saveFileToPublicMovies(Context context, ContentValues contentValues, Uri uriSavedVideo, String fileName) {
ParcelFileDescriptor pfd;
try {
pfd = context.getContentResolver().openFileDescriptor(uriSavedVideo, "w");
FileOutputStream out = null;
if (pfd != null) {
out = new FileOutputStream(pfd.getFileDescriptor());
File videoFile = new File(context.getExternalFilesDir("AppName"), fileName);
FileInputStream in = new FileInputStream(videoFile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
out.getFD().sync();
out.close();
in.close();
pfd.close();
}
} catch (Exception e) {
e.printStackTrace();
}
contentValues.clear();
contentValues.put(MediaStore.Video.Media.IS_PENDING, 0);
context.getContentResolver().update(uriSavedVideo, contentValues, null, null);

How clear gallery thumbnails after deleting image from DCIM in Android

I am deleting image after capture and doing some work on it.But after deleting the image Gallery till hold the thumbnails. How clear gallery thumbnails after deleting image from DCIM in Android.
private boolean deleteLastFromDCIM() {
boolean success = false;
try {
File[] images = new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM"+File.separator+"Camera").listFiles();
File latestSavedImage = images[0];
for (int i = 1; i < images.length; ++i) {
if (images[i].lastModified() > latestSavedImage.lastModified()) {
latestSavedImage = images[i];
}
}
// OR JUST Use success = latestSavedImage.delete();
success = new File(Environment.getExternalStorageDirectory()
+ File.separator + "DCIM/Camera/"
+ latestSavedImage.getAbsoluteFile()).delete();
return success;
} catch (Exception e) {
e.printStackTrace();
return success;
}}
if(file.exists()){
Calendar time = Calendar.getInstance();
time.add(Calendar.DAY_OF_YEAR,-7);
//I store the required attributes here and delete them
Date lastModified = new Date(file.lastModified());
if(lastModified.before(time.getTime()))
{
//file is older than a week
}
file.delete();
}else{
file.createNewFile();
}
Just you need to write a method for delete file and replace the code file.delete(); with deleteFileFromMediaStore(this.getContentResolver(),file);
public void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[] {canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
}

downloading a file from server upon pressing button

Files of a certain location are added to another folder in the Server project.
project-FileShareServer
private boolean writefiletoServerfolder() throws IOException {
String filetype = categorycombo.getValue().toString();
// int i = 0;
File file = null;
File imagefile = null;
String imagename=null;
String filename=null;
FileChannel channel = null;
FileOutputStream fileOutputStream = null;
FileInputStream fileinputstream = null;
//map=new HashMap<>();
for (int i = 0; i < fileList.size(); i++) {
if (filetype.equals("Apps")) {
file = new File("D:\\SERVER\\Server Content\\Apps\\" + fileList.get(i).getName());
imagefile = new File("D:\\SERVER\\Server Content\\Apps\\icons\\" + imagelist.get(i).getName());
imagename=imagefile.getName();
filename=file.getName();
//map.put(filename, imagename);
} else if (filetype.equals("Games")) {
file = new File("D:\\SERVER\\Server Content\\Games\\" + fileList.get(i).getName());
imagefile = new File("D:\\SERVER\\Server Content\\Games\\icons\\" + imagelist.get(i).getName());
imagename=imagefile.getName();
filename=file.getName();
// map.put(filename, imagename);
} else if (filetype.equals("Movies")) {
file = new File("D:\\SERVER\\Server Content\\Movies\\" + fileList.get(i).getName());
imagefile = new File("D:\\SERVER\\Server Content\\Movies\\icons\\" + imagelist.get(i).getName());
imagename=imagefile.getName();
filename=file.getName();
//map.put(filename, imagename);
} else if (filetype.equals("Songs")) {
file = new File("D:\\SERVER\\Server Content\\Songs\\" + fileList.get(i).getName());
imagefile = new File("D:\\SERVER\\Server Content\\Songs\\icons\\" + imagelist.get(i).getName());
imagename=imagefile.getName();
filename=file.getName();
// map.put(filename, imagename);
}
}
List<File> fileandimagedest = new ArrayList();
fileandimagedest.add(file);
fileandimagedest.add(imagefile);
List<String> fileandimagesrc = new ArrayList();
fileandimagesrc.add(filepath);
fileandimagesrc.add(imagepath);
boolean bool = false;
for (String path : fileandimagesrc) {
for (File file1 : fileandimagedest) {
try {
fileinputstream = new FileInputStream(path);
fileOutputStream = new FileOutputStream(file1);
long starttime = System.currentTimeMillis();
byte[] buf = new byte[1024];
int byteRead;
while ((byteRead = fileinputstream.read(buf)) > 0) {
fileOutputStream.write(buf, 0, byteRead);
bool = true;
}
} finally {
if (bool) {
fileinputstream.close();
fileOutputStream.close();
}
}
}
}
return true;
}
what I require is to download a file from server to client upon pressing a button in client side.
project fileshare client.
public void downloadbuttonAction() {
downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
}
});
}
I have already implemented downloading a file from server.I need to do that simply when a button is pressed.
With calling your method on pressing the button doesn't work?
like:
public void downloadbuttonAction() {
downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
writefiletoServerfolder();
}
});
}

Copy File from File Array to Directory

I am trying to copy a file that is in a list of files. I want to copy the selected file when the user long clicks on the item in the list.
public class MainActivity extends ListActivity {
private File file;
private List<String> myList;
String rootsd = Environment.getExternalStorageDirectory().toString();
String old = "/Android/data/co.vine.android/cache/videos";
String dirNameSlash = "/videos/";
String path = Environment.getExternalStorageDirectory() + dirNameSlash;
String newDir = "/Saved";
String olddir2 = new String( rootsd + old );
String newdir2 = new String( rootsd + newDir);
File temp_dir = new File(newDir);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ListView lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int row, long arg3) {
String item = (String) getListAdapter().getItem(row);
// CopyFile
Toast.makeText(getApplicationContext(), "File has been copied", Toast.LENGTH_LONG).show();
return true;
}
});
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("MyApp", "No SDCARD");
} else {
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"Saved");
directory.mkdirs();
}
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( root_sd + "/videos" ) ;
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
setListAdapter(new ArrayAdapter<String>(this,
R.layout.row, myList ));
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String item = (String) getListAdapter().getItem(position);
Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW);
intentToPlayVideo.setDataAndType(Uri.parse(path + item), "video/*");
startActivity(intentToPlayVideo);
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
Any help would be great. All the files that the user selects will be saved to the same directory. I need help identifying what file the user selects, and then copy that. Thanks!
I recommend you use a FileChanel, is more efficient and fast. Example:
try {
String root_sd = Environment.getExternalStorageDirectory().toString();
String theFile = root_sd + "/" + (String) getListAdapter().getItem(row);
File file = new File(theFile);
FileInputStream source= new FileInputStream(file);
String targetDirectory = Environment.getExternalStorageDirectory().toString();
FileOutputStream destination = new FileOutputStream(targetDirectory + "/videos/" + file.getName);
FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();
long size = sourceFileChannel.size();
sourceFileChannel.transferTo(0, size, destinationFileChannel);
} catch (Exception ex) {
Logger.getLogger(Borrar.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
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.");
}
catch(FileNotFoundException ex)
{
//print in logcat
}
catch(IOException e)
{
//print in logcat
}

Categories

Resources