I'm downloading image to a folder on the SDCARD. Since the images and my folder is not immediately visible in the Gallery I'm trying to get the MediaScannerConnection to update and show the folder/images in the gallery.
Shows you how to do this in view code ?
private void downloadImage() {
if (future != null) {
//set the callback and start downloading
future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
#Override
public void onCompleted(Exception e, Response<InputStream> result) {
boolean success = false;
if (e == null && result != null && result.getResult() != null) {
try {
//prepare the file name
String url = mSelectedImage.getUrl();
String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
//create a temporary directory within the cache folder
File dir = Utils.getAlbumStorageDir("wall-tx");
//create the file
File file = new File(dir, fileName);
if (!file.exists()) {
file.createNewFile();
}
//copy the image onto this file
Utils.copyInputStreamToFile(result.getResult(), file);
//animate the first elements
animateCompleteFirst(true);
//Broadcast the Media Scanner Intent to trigger it
success = true;
} catch (Exception ex) {
Log.e("walltx", ex.toString());
}
//animate after complete
animateComplete(success);
} else {
animateReset(true);
}
}
});
}
}
MediaScannerConnection.scanFile(this, new String[]{file.getPath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// now visible in gallery
}
});
Related
In my Android project I have more than 100 xml layouts.
Is there a function in Android Studio where I can screenshot my layout?
I want to convert all my layouts to jpeg or png for my company report.
In this function you just have to pass the view it will give you bitmap you can store it or show it on imageview
public void takeScreenshot(View screenshotView) {
try {
View view = null;
Bitmap b = null;
if (screenshotView instanceof TextureView) {
b = ((TextureView) screenshotView).getBitmap();
} else {
view = screenshotView;
}
if (view != null) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
b = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
}
if (imageViewParentLayout != null) {
if (imageView != null) {
imageView.setVisibility(View.VISIBLE);
imageView.setImageBitmap(b);
}
}
String path = saveToAlbum(b);
Notify.INSTANCE.Toast("Image Saved :" + path);
scanfiles(path);
} catch (Exception e) {
e.printStackTrace();
Notify.INSTANCE.Toast("Something Went Wrong");
}finally {
hideImageView();
}
}
private void scanfiles(String path) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
File outputFile = new File(path);
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(outputFile);
scanIntent.setData(contentUri);
AppController.getAppContext().sendBroadcast(scanIntent);
} else {
final Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()));
AppController.getAppContext().sendBroadcast(intent);
}
} catch (Exception e) {
e.printStackTrace();
File file=new File(path);
MediaScannerConnection.scanFile(AppController.getAppContext(), new String[]{
file.getAbsolutePath()},
null, (path1, uri) -> {
});
}
}
I created an image gallery app.
My requirment: I want to select multiple images, click on button cut and come back to activity which displays all folders (ImageGallery.java). Now, I want to select a folder and paste all the selected images in that folder, on selecting the folder.
What is happening? I am able to select images using my app and come back to activity which displays all folders but not able to move them using my app.
I put the code for moving images in a background thread using task. I select images from one folder, come back to the activity which displays all the folders (ImageGallery.java) and select the folder to which the images are to be moved. But when I try to move images, selected images do not move to other folder being selected, on selecting a folder. I guess the code inside AsyncTask isn't even getting executed.
How do I fix it ?
PhotosActivity.java (Activity used to select images):
int int_position;
private GridView gridView;
GridViewAdapter adapter;
ArrayList<Model_images> al_menu = new ArrayList<>();
private ArrayList<Integer> mSelected = new ArrayList<>();
boolean boolean_folder;
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
if (mSelected.contains(position)) {
mSelected.remove(position);
view.setBackgroundColor(Color.TRANSPARENT);// remove item from list
// update view (v) state here
// eg: remove highlight
} else {
mSelected.add(position);
view.setBackgroundColor(Color.LTGRAY);// add item to list
// update view (v) state here
// eg: add highlight
}
buttoncut.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
button3.setVisibility(View.VISIBLE);
button4.setVisibility(View.VISIBLE);
button5.setVisibility(View.VISIBLE);
buttoncut.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
buttoncut.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
Intent moveIntent = new Intent(PhotosActivity.this, ImageGallery.class);
moveIntent.putIntegerArrayListExtra("selected_images", mSelected);
startActivity(moveIntent);
}
});
ImageGallery.java:
public static ArrayList<Model_images> al_images = new ArrayList<>();
ArrayList<Integer> selectedImages = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
int int_position;
selectedImages = getIntent().getIntegerArrayListExtra("selected_images");
if (selectedImages != null) {
Toast.makeText(ImageGallery.this, "This code gets executed", Toast.LENGTH_SHORT)
.show();
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int image : selectedImages) {
File sourceImage = new File(al_images.get(int_position).getAl_imagepath().get(image)); //returns the image File from model class to be moved.
File destinationImage = new File(al_images.get(int_position).getStr_folder(), ".jpeg");
try {
copyOrMoveFile(sourceImage, destinationImage, true);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//Method to move the file
private void copyOrMoveFile(File file, File dir, boolean isCopy) throws IOException {
File newFile = new File(dir, file.getName());
FileChannel outChannel = null;
FileChannel inputChannel = null;
try {
outChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(file).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outChannel);
inputChannel.close();
if (!isCopy)
file.delete();
} finally {
if (inputChannel != null) inputChannel.close();
if (outChannel != null) outChannel.close();
}
}
}
You have to use Intent.ACTION_MEDIA_SCANNER_SCAN_FILE for updating media store.
Inside AsyncTask -> onPostExecute method fetch latest images from MediaStore
private class LongOperation extends AsyncTask<String, Void, File> {
#Override
protected File doInBackground(String... params) {
for (String imagePath : selectedImages) {
File sourceImage = new File(imagePath); //returns the image File from model class to
// be// moved.
File destinationImage = new File(al_images.get(int_position).getDirectoryPath() +
File.separator + sourceImage.getName());
try {
moveFile(sourceImage, destinationImage, true);
return destinationImage;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
fn_imagespath(); // Call method to fetch latest images.
}
}, 1000); // additional delay time of 1 sec to update media scanner
}
}
Just a better method to move file
private void moveFile(File file_Source, File file_Destination, boolean isCopy) throws IOException {
FileChannel source = null;
FileChannel destination = null;
if (!file_Destination.exists()) {
file_Destination.createNewFile();
}
try {
source = new FileInputStream(file_Source).getChannel();
destination = new FileOutputStream(file_Destination).getChannel();
long count = 0;
long size = source.size();
while ((count += destination.transferFrom(source, count, size - count)) < size) ;
if (!isCopy) {
file_Source.delete();
}
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
Not much changes in code added MediaScannerConnection. Give it a try .
private class LongOperation extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
int movedCount=0;
for (int i=0;i<selectedImages.size();i++) {
File sourceImage = new File(al_images.get(int_position).getAl_imagepath().get(i));
File destinationImage = new File(al_images.get(int_position).getStr_folder(), ".jpeg");
try {
boolean isMoved= copyOrMoveFile(sourceImage, destinationImage, true);
if(isMoved) {
movedCount++;
callMediaScanner(ImageGallery.this, destinationImage.getAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
}
}
return movedCount;
}
#Override
protected void onPostExecute(Integer val) {
super.onPostExecute(val);
// Here you have to modify return type of doInBackground as per your convineance
if(val.intValue()==selectedImages.size()){
Log.e("Moved","Allfile moved");
}else{
Log.e("Moved","Some file missing");
}
}
public boolean copyOrMoveFile(File localFile, File destinationFile, boolean isCopy) {
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(destinationFile).getChannel();
inputChannel = new FileInputStream(localFile).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
if (!isCopy)
localFile.delete();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (inputChannel != null) inputChannel.close();
if (outputChannel != null) outputChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
}
public void callMediaScanner(Context context, String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,null);
}
I'm downloading image to a folder on the SDCARD. Since the images and my folder is not immediately visible in the Gallery I'm trying to get the Me update and show the folder/images in the gallery. Shows you how to do this in my code include?
private void downloadImage() {
if (future != null) {
//set the callback and start downloading
future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
#Override
public void onCompleted(Exception e, Response<InputStream> result) {
boolean success = false;
if (e == null && result != null && result.getResult() != null) {
try {
//prepare the file name
String url = mSelectedImage.getUrl();
String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
//create a temporary directory within the cache folder
File dir = Utils.getAlbumStorageDir("wall-tx");
//create the file
File file = new File(dir, fileName);
if (!file.exists()) {
file.createNewFile();
}
//copy the image onto this file
Utils.copyInputStreamToFile(result.getResult(), file);
//animate the first elements
animateCompleteFirst(true);
//Broadcast the Media Scanner Intent to trigger it
success = true;
} catch (Exception ex) {
Log.e("walltx", ex.toString());
}
//animate after complete
animateComplete(success);
} else {
animateReset(true);
}
}
});
}
}
When I download an image and save it to the Android device the image does not appear in the gallery, later after the phone is restarted the images are in the gallery.
Here is the code where I download the images and save them to the device:
private void downloadImage() {
if (future != null) {
//set the callback and start downloading
future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
#Override
public void onCompleted(Exception e, Response<InputStream> result) {
boolean success = false;
if (e == null && result != null && result.getResult() != null) {
try {
//prepare the file name
String url = mSelectedImage.getUrl();
String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
//create a temporary directory within the cache folder
File dir = Utils.getAlbumStorageDir("wall-tumbler");
//create the file
File file = new File(dir, fileName);
if (!file.exists()) {
file.createNewFile();
}
//copy the image onto this file
Utils.copyInputStreamToFile(result.getResult(), file);
//animate the first elements
animateCompleteFirst(true);
success = true;
} catch (Exception ex) {
Log.e("walltumbler", ex.toString());
}
//animate after complete
animateComplete(success);
} else {
animateReset(true);
}
}
});
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private void downloadAndSetOrShareImage(final boolean set) {
if (future != null) {
//set the callback and start downloading
future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
#Override
public void onCompleted(Exception e, Response<InputStream> result) {
boolean success = false;
if (e == null && result != null && result.getResult() != null) {
try {
//create a temporary directory within the cache folder
File dir = new File(DetailActivity.this.getCacheDir() + "/images");
if (!dir.exists()) {
dir.mkdirs();
}
//create the file
File file = new File(dir, "walltumbler.jpg");
if (!file.exists()) {
file.createNewFile();
}
//copy the image onto this file
Utils.copyInputStreamToFile(result.getResult(), file);
//get the contentUri for this file and start the intent
Uri contentUri = FileProvider.getUriForFile(DetailActivity.this, "com.mikepenz.fileprovider", file);
if (set) {
//get crop intent
Intent intent = WallpaperManager.getInstance(DetailActivity.this).getCropAndSetWallpaperIntent(contentUri);
//start activity for result so we can animate if we finish
DetailActivity.this.startActivityForResult(intent, ACTIVITY_CROP);
} else {
//share :D
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setData(contentUri);
shareIntent.setType("image/jpg");
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
//start activity for result so we can animate if we finish
DetailActivity.this.startActivityForResult(Intent.createChooser(shareIntent, "Share Via"), ACTIVITY_SHARE);
}
success = true;
} catch (Exception ex) {
Log.e("walltumbler", ex.toString());
}
//animate after complete
animateComplete(success);
} else {
animateReset(true);
}
}
});
}
}
Utils
/**
* http://developer.android.com/training/basics/data-storage/files.html
*
* #param albumName
* #return
*/
public static File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
boolean success = false;
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);
if (!file.exists()) {
success = file.mkdir();
}
if (!success)
Log.i("wall-tumbler", "Directory not created");
else
Log.i("wall-tumbler", "Directory created");
return file;
}
/**
* http://developer.android.com/training/basics/data-storage/files.html
*
* #return
*/
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
}
ScreenShot
http://i.stack.imgur.com/6dkp0.jpg
You should use the MediaStore content provider to add an image to the gallery.
ContentValues values = new ContentValues();
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, imagePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Hy,
I want to empty the internal Folder "/storage/emulated/0/DCIM/Camera"
This works for me with the following code
public void emptyDir()
{
File dir = new File("/storage/emulated/0/DCIM/Camera");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
Log.i(logTag,"Path " +dir +" cleared");
}
}
}
Can I access/read this path without hardcode it?
The code to Capture my Picture:
I think most of the code is pretty clear what i meant to do because i always try to comment anything I do even if I'm just testing something new. I hope that I can show what i created with this one.
public void takePhoto()
{
//Set the size of the Picture
Parameters params = mCamera.getParameters();
params.setPictureSize(640, 480);
mCamera.setParameters(params);
//Befehl um die möglichen Auflösungen auszuwählen/aufzulisten
//List<Camera.Size> sizes = params.getSupportedPictureSizes();
//Take the Picture
mCamera.takePicture(null, null, mPicture);
//SLEEP "sleeper value" SECONDS HERE ...
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
releaseCamera();
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.removeAllViews();
activateCamera();
}
}, sleeper);
}
/**
* Creates and Instance of Camera and adds CameraView to
* camera_preview FrameLayout
*/
public void activateCamera()
{
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
final PictureCallback mPicture = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null)
{
return;
}
try
{
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
path = pictureFile.getAbsolutePath();
System.out.println("Picture stored at: "+path);
MediaStore.Images.Media.insertImage(getContentResolver(), pictureFile.getAbsolutePath(), pictureFile.getName(), pictureFile.getName());
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
}
};
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try
{
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e)
{
System.out.println("Camera in use");
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause()
{
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera()
{
if (mCamera != null)
{
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(int type)
{
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
//File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MFI Webcam");
File rootsd = Environment.getExternalStorageDirectory();
File mediaStorageDir = new File(rootsd.getAbsolutePath() + "/MFI Webcam");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists())
{
if (! mediaStorageDir.mkdirs())
{
return null;
}
}
// Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "webcam"+ ".jpg");
} else
{
return null;
}
return mediaFile;
}
With getExternalStoragePublicDirectory(DIRECTORY_DCIM) you would probably get /storage/emulated/0/DCIM. But it is never a guarantee that the pictures will be there. They could as well be in /storage/emulated/1/DCIM. So better let the user indicate the right directory.