Include media refresh my code? - java

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);
}
}
});
}
}

Related

Android , ndk, write willfully to a sd card file

After Android 4.4, the SD card needs permission to write files.
You can request to write to the SD card by StorageVolume. createAccessIntent ().
The stream is then accessed using ContentResolver().openoutputstream (file.geturi ()) to write data to the file.
How do I write data in the NDK?
public void startRequestPermissions(Context context) {
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
if (mStorageManager != null) {
StorageVolume volume = mStorageManager.getStorageVolume(new File(timePath));
if (volume != null) {
intent = volume.createAccessIntent(null);
}
}
}
if (intent == null) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
}
((Activity) context).startActivityForResult(intent, FileBrowserConfig.OPEN_DOCUMENT_TREE_CODE);
}
public OutputStream getOutputStream(Context context, File destFile) {
OutputStream out = null;
try {
DocumentFile file = getDocumentFile(destFile, false, context);
out = context.getContentResolver().openOutputStream(file.getUri());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return out;
}
Can write data in sd card with NDK!
Instead of openOutputStream(), you can get a file descriptor with openAssetFileDescriptor().

Images are not being saved in my camera app

I'm trying to make an app that detects motion and takes picture when the motion is detected. Its saving the picture when I don't try to save it in the directory(folder). But when I try it with the directory, the picture is not being saved even though the directory is being created successfully.
What changes should I make to the following code in order to make it work:
private void createDirectoryAndSaveFile(String name, Bitmap bitmap) {
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "XYX APP");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
File photo = new File(new File(Environment.getExternalStorageDirectory()+"XYZ APP/"), name+ ".jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream out = new FileOutputStream(photo.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Note: The file name is generated in the following instruction:
String name = "MotDet_"+String.valueOf(System.currentTimeMillis());
if (bitmap != null) createDirectoryAndSaveFile(name, bitmap);
Update
It works with the following code but not with the code above :
private void save(String name, Bitmap bitmap) {
File photo = new File(Environment.getExternalStorageDirectory(), name + ".jpg");
if (photo.exists()) photo.delete();
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
}
First of all you missed the FileSeperator before xyz
File photo = new File(folder.getAbsolutePath()+"/XYZ APP/"+ name+ ".jpg");
And your Function becomes
private void createDirectoryAndSaveFile(String name, Bitmap bitmap) {
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "XYZ APP");//here you have created different name
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
File photo = new File(folder.getAbsolutePath(), name+ ".jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream out = new FileOutputStream(photo.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Marshmello comes with RuntimePermissions in order for you to save file in external directory you need to ask permission first, like below code
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
permission result callback
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}
before saving call isStoragePermissionsGranted() if it returns true proceed saving file.
Try this code :
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bp, partFilename);
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This code is work for me..Save image to directory.
You have to get permission of external storage at run time in android 6.0 and above to write in SDCard
Read Run time Permission
add in manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
replace your function with below one
private void createDirectoryAndSaveFile(String name, Bitmap bitmap) {
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "XYZ APP");//here you have created different name
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
File photo = new File(folder.getAbsolutePath(), name+ ".jpg"); //use path of above created folder
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream out = new FileOutputStream(photo.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

How to use MediaScannerConnection scanFile?

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
}
});

I can not see download image in gallery until I restart the phone

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);

Empty the internal DCIM Folder - Android Java

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.

Categories

Resources