Android Studio Video not displaying or recording - java

I am trying to record video using mediarecorder and display that video on other activity. It was working fine and the video was there but now a error is occuring that video cannot be displayed. Can someone help?
Here my code :
captureButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
isActionDown = true;
try {
if (isActionDown) {
initRecorder();
if (isActionDown)
prepareRecorder();
isPrepared = true;
}
if (isPrepared && isActionDown) {
Toast.makeText(getContext(), "startRecorder", Toast.LENGTH_LONG).show();
isRecording = true;
mediaRecorder.start();
} else {
releaseMediaRecorder();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("onLongPress Error ", e.toString());
}
return true;
}
});
captureButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
isActionDown = false;
try {
if (isRecording) {
if (mediaRecorder != null) {
mediaRecorder.stop();
releaseMediaRecorder(); // release the MediaRecorder object
camera.lock();
Toast.makeText(getContext(), "MediaRecoderNull", Toast.LENGTH_LONG).show();
}
isRecording = false;
if (fileUri != null) {
playVideo(getView());
}
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
return false;
}
});
Uri fileUri = null;
Uri ImageUri;
private void initRecorder() {
mediaRecorder = new MediaRecorder();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setOrientationHint(90);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
}
private void prepareRecorder() {
mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
try {
mediaRecorder.prepare();
isPrepared = true;
return;
} catch (IllegalStateException e) {
releaseMediaRecorder();
e.printStackTrace();
} catch (IOException e) {
releaseMediaRecorder();
e.printStackTrace();
}
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static 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), "MyCameraApp");
// 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()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public void playVideo(View view) {
Intent playIntent = new Intent(getActivity(), CapturedVideoActivity.class);
playIntent.putExtra("videoUri", fileUri.toString());
startActivity(playIntent);
}
so on the next screen while displaying this occurs enter image description here
Next screen code:
VideoView mVideoView = findViewById(R.id.videoCaptured);
videoUri = Uri.parse(getIntent().getExtras().getString("videoUri"));
mVideoView.setVideoURI(videoUri);
mVideoView.start();

Related

Best solution for background screenshot

I want the application in the background to be able to take a screenshot and save the result to the clipboard. Is there an optimal solution to this problem?
You can use the following code examples
public class HelperScreenShot {
public static Bitmap takeScreenshot(View v) {
v.setDrawingCacheEnabled(true);
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
return b;
}
public static Bitmap takeScreenshotOfRootView(View v) {
return takeScreenshot(v.getRootView());
}
public static boolean takeScreenshotAndSaveIi(View v, String filename) {
return storeScreenshot(takeScreenshot(v.getRootView()), filename);
}
public static boolean storeScreenshot(Bitmap bitmap, String filename) {
if (!isExternalStorageReadable()) {
return false;
}
if (!isExternalStorageWritable()) {
return false;
}
OutputStream out;
try {
File dir = getDownloadStorageDir("ScreenShots");
File imageFile = new File(dir, filename + ".jpg");
if (!imageFile.exists()) {
imageFile.createNewFile();
}
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
MediaScannerConnection.scanFile(G.context, new String[]{imageFile.getAbsolutePath()}, null, null);
out.flush();
out.close();
return true;
} catch (FileNotFoundException e) {
// manage exception ...
return false;
} catch (IOException e) {
// manage exception ...
return false;
}
}
/* Checks if external storage is available for read and write */
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
/* Checks if external storage is available to at least read */
private static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
private static File getDownloadStorageDir(String fileName) {
// Get the directory for the user's public pictures directory.
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
if (!Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).exists()) {
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()).mkdirs();
}
if (!storageDir.exists()) {
storageDir.mkdir();
}
return storageDir;
}
}
private Single<Boolean> loadImage() {
Date date = new Date();
filename = "receipt" + date.getTime();
return Single.just(HelperScreenShot.takeScreenshotAndSaveIi(binding.v, filename));
}
private void getScreenshot() {
loadImage()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Boolean>() {
#Override
public void onSubscribe(#io.reactivex.annotations.NonNull Disposable d) {
disposables.add(d);
}
#Override
public void onSuccess(#io.reactivex.annotations.NonNull Boolean s) {
if (s) {
Snackbar snackbar = Snackbar.make(binding.v, getResources().getString(R.string.picture_save_to_galary), Snackbar.LENGTH_LONG);
snackbar.setAction(getResources().getString(R.string.navigation_drawer_open), new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ScreenShots/" + filename + ".jpg");
Log.d("amini", "onClick: " + file.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_VIEW).setDataAndType(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?
FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", file) :
Uri.fromFile(file), "image/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
});
snackbar.show();
} else {
Snackbar snackbar = Snackbar.make(binding.v, getResources().getString(R.string.str_frag_sync_error), Snackbar.LENGTH_LONG);
snackbar.setAction(getResources().getString(R.string.ok), v -> snackbar.dismiss());
snackbar.show();
}
}
#Override
public void onError(#io.reactivex.annotations.NonNull Throwable e) {
}
});
}

How to capture a square size photo in android app

I'm now developing an android app. In this app, user can take a photo and then upload it. But in the user interface, I want the photo be square size and also be displayed as square size. The following is my camerapreview code, I don't know where to add size parameters:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera;
public static final int MEDIA_TYPE_IMAGE = 1;
private Uri outputMediaFileUri;
private String outputMediaFileType;
public File pic;
public Uri uri;
public CameraPreview(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
}
private static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
Log.d(TAG, "camera is not available");
}
return c;
}
public void surfaceCreated(SurfaceHolder holder) {
mCamera = getCameraInstance();
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mHolder.removeCallback(this);
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
int rotation = getDisplayOrientation();
mCamera.setDisplayOrientation(90);
}
private File getOutputMediaFile(int type) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), TAG);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"prescription" + ".jpg");
outputMediaFileType = "image/*";
} else {
return null;
}
outputMediaFileUri = Uri.fromFile(mediaFile);
return mediaFile;
}
public Uri getOutputMediaFileUri() {
return outputMediaFileUri;
}
public String getOutputMediaFileType() {
return outputMediaFileType;
}
public void takePicture() {
mCamera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
Log.i("camera", "file done");
if (pictureFile == null) {
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}
try {
Log.i("camera", "do outputstream");
FileOutputStream fos = new FileOutputStream(pictureFile);
Log.i("camera", "after outputstream");
s = getOutputMediaFileUri().toString();
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
});
}
public int getDisplayOrientation() {
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
android.hardware.Camera.CameraInfo camInfo =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo);
int result = (camInfo.orientation - degrees + 360) % 360;
return result;
}
}
If I want to make sure the size of the photo and the camera preview are square size, where should I modify? Thanks.
I use Picasso to work with images, it is very effective.
implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
Picasso.get()
.load(url)
.resize(50, 50)//resize image
.centerCrop()
.into(imageView)
http://square.github.io/picasso/
Regards!

The image uri didn't update after I first call the camera in my app

When I want to get the image uri after I captured a photo, it always got nothing, but after I captured again, it returns the first one, not the current one. It seems like it always get the one before the latest. The following is my camerapreview code:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera;
public static final int MEDIA_TYPE_IMAGE = 1;
private Uri outputMediaFileUri;
private String outputMediaFileType;
public File pic;
public Uri uri;
public CameraPreview(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
}
private static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
Log.d(TAG, "camera is not available");
}
return c;
}
public void surfaceCreated(SurfaceHolder holder) {
mCamera = getCameraInstance();
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mHolder.removeCallback(this);
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
int rotation = getDisplayOrientation();
mCamera.setDisplayOrientation(90);
}
private File getOutputMediaFile(int type) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), TAG);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"prescription" + ".jpg");
outputMediaFileType = "image/*";
} else {
return null;
}
outputMediaFileUri = Uri.fromFile(mediaFile);
return mediaFile;
}
public Uri getOutputMediaFileUri() {
return outputMediaFileUri;
}
public String getOutputMediaFileType() {
return outputMediaFileType;
}
public void takePicture() {
mCamera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
Log.i("camera", "file done");
if (pictureFile == null) {
Log.d(TAG, "Error creating media file, check storage permissions");
return;
}
try {
Log.i("camera", "do outputstream");
FileOutputStream fos = new FileOutputStream(pictureFile);
Log.i("camera", "after outputstream");
s = getOutputMediaFileUri().toString();
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
});
}
public int getDisplayOrientation() {
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
android.hardware.Camera.CameraInfo camInfo =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo);
int result = (camInfo.orientation - degrees + 360) % 360;
return result;
}
}
After I call camerapreview.takepicture(), I tried to call camerapreview.outputMediaFileUri.toString(), but it doesn't work. Can someone help me?
Updated:
I found that in the main activity, mPreview.takePicture() is always run at the end of all the precedures:
Button buttonCapturePhoto = (Button) findViewById(R.id.button_capture_photo);
buttonCapturePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPreview.takePicture();
path = mPreview.geturi;
goToFourthActivity(path);
}
}
});
At each time, "path" will read the image uri FIRST, and then do mPreview.takePicture(). So it would always be the previous uri, I don't know why, how can I fix it?
Your code
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"prescription" + ".jpg");
unconditionally reuses the same file name. No wonder you get the same URI.

Difference between triggering camera.take picture from button click[Working] and through function call[Not working]

I am stuck at this. MY application clicks multiple images programmatically.
Issue is my take picture call is inside button listener click function.
1. When i do button click it triggers the thread for take picture that works.
2. If i directly call that obj.run() it does not-> shows take picture failed at run time.
3. If i do btn.perform click - still fails.
I am building an application that listens on a socket and on a trigger click multiple images n save them to create .gif.
code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// android.support.v7.appcompat.R.layout.activity_main;
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
myContext = this;
initialize();
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findFrontFacingCamera());
// mCamera.Parameters.class.
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
capture.performClick();
Log.d("naval", "onresume- clicked performed");
}
}
public void initialize() {
cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
capture = (Button) findViewById(R.id.button_capture);
// capture.setVisibility(View.GONE);
capture.setOnClickListener(captrureListener);
// capture.performClick();
switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
switchCamera.setVisibility(View.GONE); // JUST CHANGE THIS TO MAKE SWITCH CAMERA WORKS
switchCamera.setOnClickListener(switchCameraListener);
Log.d("naval", "initialize");
}
OnClickListener switchCameraListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get the number of cameras
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber > 1) {
//release the old camera instance
//switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
};
public void chooseCamera() {
//if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
protected void onPause() {
super.onPause();
//when on Pause, release camera in order to be used from other applications
releaseCamera();
Log.d("naval", "onpause");
}
private boolean hasCamera(Context context) {
//check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private PictureCallback getPictureCallback() {
PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//make a new picture file
File pictureFile = getOutputMediaFile();
Log.d("naval", "picture call back start");
if (pictureFile == null) {
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
Log.d("naval", "picture call back stream creation");
fos.write(data);
fos.close();
Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
Log.d("naval", "picture call back toast");
toast.show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
//refresh camera to continue preview
mPreview.refreshCamera(mCamera);
//cameraPreview.start();
}
};
return picture;
}
OnClickListener captrureListener = new OnClickListener() {
#Override
public void onClick(View v) {
try {
Thread.sleep(1000);
}catch (Exception e)
{
e.printStackTrace();
}
CaptureThread captureThread = new CaptureThread();
captureThread.start();
/* String str = "";
while(true)
{
Log.d("naval","waiting for start inside file loop");
str = readFromFile();
if(str.equals("start")) {
Log.d("naval","calling capture object");
str = "";
CaptureThread captureThread = new CaptureThread();
captureThread.start();
}
else
{
try {
Log.d("naval","sleeping inside str loop");
Thread.sleep(1000);
}catch(Exception e)
{
e.printStackTrace();
}
continue;
// put sleep here
}
// read text file here at location /sdcard/info/info.txt
}*/
}
};
private String readFromFile() {
String ret = "";
try {
FileInputStream fis = new FileInputStream (new File("/storage/emulated/0/info/info.txt")); // 2nd line
// InputStream inputStream = openFileInput("/storage/emulated/0/info/info.txt");
if ( fis != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
fis.close();
ret = stringBuilder.toString();
Log.d("naval- string",ret);
if(!ret.isEmpty())
{
Log.d("naval","str is not null");
//delete file or clear file and create one
File fil = new File("/storage/emulated/0/info/info.txt");
fil.delete();
// create
File file = new File("/storage/emulated/0/info/info.txt");
file.createNewFile();
}
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
//make picture and save to a folder
private static File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
File mediaStorageDir = new File("/sdcard/", "pics");
Log.d("naval", "save picture function");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
Log.d("naval", "cave picture betweent");
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
//and make a media file:
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "pic" + glo + ".png");
Log.d("naval", "File path above");
glo++;
return mediaFile;
}
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
class CaptureThread extends Thread {
#Override
public void run() {
int count = 0;
while(count < 6) {
**mCamera.takePicture(null, null, mPicture);**
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
createGif();
}
public void createGif()
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 6;
encoder.setDelay(100);
encoder.start(bos);
for(int i = 0;i<6;i++){
Bitmap bMap = BitmapFactory.decodeFile("/storage/emulated/0/pics/pic"+i+".png",options);
Log.d("naval","added image");
encoder.addFrame(bMap);
}
encoder.finish();
writeToFile(bos.toByteArray());
}
public void writeToFile(byte[] array) {
try {
String path = Environment.getExternalStorageDirectory() + "/gif/gif.gif";
FileOutputStream stream = new FileOutputStream(path);
stream.write(array);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
ok the answer is from button click it comes from UI thread. But the function call does not. to run this call the function from UI thread . It will work!!

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

Categories

Resources