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) {
}
});
}
Related
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();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
I am using Silicompressor library for video compression.
My video size is 15 MB and compressed video size is coming to 500 kb
since the compressed size is very very small and when clicked on play button of compressed video it shows an error as "Failed to play video."
How do I get a compressed size in MB?
Here is my code after compressing
File imageFile = new File(compressedFilePath);
float length = imageFile.length() / 1024f; // Size in KB
System.out.println("length = " + length);
String value;
if (length >= 1024)
value = length / 1024f + " MB";
else
value = length + " KB";
Any other alternative library which works well for video compression ?
you can use LightCompressor library
LightCompressor
call compressVideo class and pass to it the video path and the desired compressed video location
selectedVideo = data.getData();
compressVideo(getMediaPath(QabaelAdd.this,selectedVideo));
fpath=saveVideoFile(QabaelAdd.this,path).getPath(); //the compressed video location
private static File saveVideoFile(Context context, String filePath) throws IOException {
if (filePath != null) {
File videoFile = new File(filePath);
String videoFileName = "" + System.currentTimeMillis() + '_' + videoFile.getName();
String folderName = Environment.DIRECTORY_MOVIES;
if (Build.VERSION.SDK_INT < 30) {
File downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File desFile = new File(downloadsPath, videoFileName);
if (desFile.exists()) {
desFile.delete();
}
try {
desFile.createNewFile();
} catch (IOException var61) {
var61.printStackTrace();
}
return desFile;
}
ContentValues var10 = new ContentValues();
boolean var11 = false;
boolean var12 = false;
var10.put("_display_name", videoFileName);
var10.put("mime_type", "video/mp4");
var10.put("relative_path", folderName);
var10.put("is_pending", 1);
ContentValues values = var10;
Uri collection = MediaStore.Video.Media.getContentUri("external_primary");
Uri fileUri = context.getContentResolver().insert(collection, values);
Void var10000;
if (fileUri != null) {
boolean var13 = false;
Closeable var18 = (Closeable)context.getContentResolver().openFileDescriptor(fileUri, "rw");
boolean var19 = false;
boolean var20 = false;
Throwable var73 = (Throwable)null;
try {
ParcelFileDescriptor descriptor = (ParcelFileDescriptor)var18;
if (descriptor != null) {
boolean var24 = false;
boolean var25 = false;
Closeable var28 = (Closeable)(new FileOutputStream(descriptor.getFileDescriptor()));
boolean var29 = false;
boolean var30 = false;
Throwable var74 = (Throwable)null;
try {
FileOutputStream out = (FileOutputStream)var28;
Closeable var33 = (Closeable)(new FileInputStream(videoFile));
boolean var34 = false;
boolean var35 = false;
Throwable var76 = (Throwable)null;
try {
FileInputStream inputStream = (FileInputStream)var33;
byte[] buf = new byte[4096];
while(true) {
int sz = inputStream.read(buf);
if (sz <= 0) {
Unit var77 = Unit.INSTANCE;
break;
}
out.write(buf, 0, sz);
}
} catch (Throwable var62) {
var76 = var62;
throw var62;
} finally {
//CloseableKt.closeFinally(var33, var76);
}
Unit var75 = Unit.INSTANCE;
} catch (Throwable var64) {
var74 = var64;
throw var64;
} finally {
//CloseableKt.closeFinally(var28, var74);
}
Unit var72 = Unit.INSTANCE;
} else {
var10000 = null;
}
} catch (Throwable var66) {
var73 = var66;
throw var66;
} finally {
//CloseableKt.closeFinally(var18, var73);
}
values.clear();
values.put("is_pending", 0);
context.getContentResolver().update(fileUri, values, (String)null, (String[])null);
return new File(QabaelAdd.getMediaPath(context, fileUri));
}
var10000 = (Void)null;
}
return null;
}
#NotNull
public static String getMediaPath(#NotNull Context context, #NotNull Uri uri) throws IOException {
Intrinsics.checkNotNullParameter(context, "context");
Intrinsics.checkNotNullParameter(uri, "uri");
ContentResolver resolver = context.getContentResolver();
String[] projection = new String[]{"_data"};
Cursor cursor = (Cursor)null;
String var30;
try {
File file;
String var57;
try {
cursor = resolver.query(uri, projection, (String)null, (String[])null, (String)null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow("_data");
cursor.moveToFirst();
var57 = cursor.getString(columnIndex);
Intrinsics.checkNotNullExpressionValue(var57, "cursor.getString(columnIndex)");
} else {
var57 = "";
}
return var57;
} catch (Exception var53) {
String filePath = context.getApplicationInfo().dataDir + File.separator + System.currentTimeMillis();
file = new File(filePath);
InputStream var10000 = resolver.openInputStream(uri);
if (var10000 != null) {
Closeable var13 = (Closeable)var10000;
InputStream inputStream = (InputStream)var13;
Closeable var18 = (Closeable)(new FileOutputStream(file));
FileOutputStream outputStream = (FileOutputStream)var18;
byte[] buf = new byte[4096];
while(true) {
int var25 = inputStream.read(buf);
if (var25 <= 0) {
break;
}
outputStream.write(buf, 0, var25);
}
}
}
var57 = file.getAbsolutePath();
Intrinsics.checkNotNullExpressionValue(var57, "file.absolutePath");
var30 = var57;
} finally {
if (cursor != null) {
cursor.close();
}
}
return var30;
}
private void compressVideo(String path){
VideoCompressor.start(path,fpath , new CompressionListener() {
#Override
public void onStart() {
// Compression start
}
#Override
public void onSuccess() {
// On Compression success
Uri uploadUri = Uri.fromFile(new File(fpath));
Log.e("is dir", String.valueOf(new File(fpath).isDirectory()));
uploadVideoMethod(uploadUri); //upload the video
}
#Override
public void onFailure(String failureMessage) {
// On Failure
Log.e("fail", failureMessage);
Toast.makeText(QabaelAdd.this, "failed to compress video", Toast.LENGTH_LONG).show();
}
#Override
public void onProgress(float v) {
// Update UI with progress value
runOnUiThread(new Runnable() {
public void run() {
progressDialog.setMessage(" جاري تهيئة الفيديو "+String.valueOf(Math.round(v))+"%");
Log.e("progress", String.valueOf(v));
}
});
}
#Override
public void onCancelled() {
// On Cancelled
}
}, VideoQuality.MEDIUM, false, false);
}
Can you go with SiliCompressor. It's nice and simple library and give good result. I have used it.
Try to implement this. If you get any error let me know.
https://github.com/Tourenathan-G5organisation/SiliCompressor
Edit:
This way you can call the async task.
class VideoCompressAsyncTask extends AsyncTask<String, String, String> {
Context mContext;
public VideoCompressAsyncTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... paths) {
String filePath = null;
try {
filePath = SiliCompressor.with(mContext).compressVideo(paths[0], paths[1]);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return filePath;
}
#Override
protected void onPostExecute(String compressedFilePath) {
super.onPostExecute(compressedFilePath);
File videoFile = new File(compressedFilePath);
}
}
Then now call it.
new VideoCompressAsyncTask(getActivity()).execute(selectedVideoPath, f.getPath());
selectedVideoPath is the video source path and f.getPath() is the destination path.
Try this way.
I want to add feature in my app to download a GIF Image from url to my phones storage.
How can I do this into my application
public class Download {
Context context;
String url;
ProgressDialog progressDailog;
public void saveImage(Context context, String url) {
this.context = context;
this.url = url;
progressDailog = new ProgressDialog(context);
progressDailog.setMax(100);
progressDailog.setMessage("Please wait...");
progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDailog.setCanceledOnTouchOutside(false);
progressDailog.show();
Glide.with(context).asBitmap()
.load(url)
.apply(new RequestOptions()
.diskCacheStrategyOf(DiskCacheStrategy.ALL)
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
progressDailog.dismiss();
storeImage(resource);
//Log.d(TAG, "Image : " + resource);
}
});
}
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
Toast.makeText(context, "Image Downloaded", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs())
return null;
}
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS.jpg");
return mediaFile;
}
}
From this code I can download the normal Image but it did not works on GIF. The GIF image downloaded and it remains static
This snippet will help you to download gif using GLIDE
Glide.with(context)
.download(url)
.listener(new RequestListener<File>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
progressDailog.dismiss();
Toast.makeText(context, "Error saving", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
progressDailog.dismiss();
try {
saveGifImage(context, getBytesFromFile(resource), createName(url));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}).submit();
createName function
public String createName(String url) {
String name = url.substring( url.lastIndexOf('/')+1, url.length());
String NoExt = name.substring(0, name.lastIndexOf('.'));
if(!ext.equals(".gif")){
name = NoExt + ".jpg";
}
return name;
}
getBytesFromFile function
public byte[] getBytesFromFile(File file) throws IOException {
long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("File is too large!");
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
InputStream is = new FileInputStream(file);
try {
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
return bytes;
}
saveGifImage function
public void saveGifImage(Context context, byte[] bytes, String imgName ) {
FileOutputStream fos = null;
try {
File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File customDownloadDirectory = new File(externalStoragePublicDirectory, "Merry_Christmas");
if (!customDownloadDirectory.exists()) {
boolean isFileMade = customDownloadDirectory.mkdirs();
}
if (customDownloadDirectory.exists()) {
File file = new File(customDownloadDirectory, imgName);
fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();
if (file != null) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, file.getName());
values.put(MediaStore.Images.Media.DISPLAY_NAME, file.getName());
values.put(MediaStore.Images.Media.DESCRIPTION, "");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/gif");
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
ContentResolver contentResolver = context.getContentResolver();
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(context, "Image saved to " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
For getting GIF using Glide:
Glide.with(MainActivity.this).asFile()
.load(url)
.apply(new RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new Target<File>() {
#Override
public void onStart() {
}
#Override
public void onStop() {
}
#Override
public void onDestroy() {
}
#Override
public void onLoadStarted(#Nullable Drawable placeholder) {
}
#Override
public void onLoadFailed(#Nullable Drawable errorDrawable) {
}
#Override
public void onResourceReady(#NonNull File resource, #Nullable Transition<? super File> transition) {
storeImage(resource);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
#Override
public void getSize(#NonNull SizeReadyCallback cb) {
}
#Override
public void removeCallback(#NonNull SizeReadyCallback cb) {
}
#Override
public void setRequest(#Nullable Request request) {
}
#Nullable
#Override
public Request getRequest() {
return null;
}
});
For Saving Image:
private void storeImage(File image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream output = new FileOutputStream(pictureFile);
FileInputStream input = new FileInputStream(image);
FileChannel inputChannel = input.getChannel();
FileChannel outputChannel = output.getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
output.close();
input.close();
Toast.makeText(MainActivity.this, "Image Downloaded", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs())
return null;
}
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS_"+Calendar.getInstance().getTimeInMillis() +".gif");
return mediaFile;
}
Glide can get File, worked with me:
Glide.with(context).asFile()
.load(url)
.apply(new RequestOptions()
.diskCacheStrategyOf(DiskCacheStrategy.ALL)
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new SimpleTarget<File>() {
#Override
public void onResourceReady(#NonNull File resource, #Nullable Transition<? super File> transition) {
progressDailog.dismiss();
storeImage(resource);
//Log.d(TAG, "Image : " + resource);
}
});
I want to save image from url to storage through picasso, but i have a problem with my code.
i've a variable to save image.
String urlImage = "http://mylink/buzz/test2.jpg";
this one is worked
but when i use
fileUrl = fileName +"." + fileType;
String urlImage = "http://mylink/buzz/" + fileUrl;
not worked
content of fileUrl is test2.jpg
here is my code to save image
private Target picassoImageTarget(Context context, final String imageDir, final String imageName) {
Log.d("picassoImageTarget", " picassoImageTarget");
ContextWrapper cw = new ContextWrapper(context);
final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
return new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
final File myImageFile = new File(directory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath());
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {}
}
};
}
and its code for call picasso.
Picasso.with(DrawerActivity.this).load(url).into(picassoImageTarget(getApplicationContext(), "imageDir", fileUrl));
having one text and audio(recording) and saving the name and path in db.while clicking the name that audio has to play its playing also.But while editing if i supposed to change the name alone,it will not take the old file name of the respective one,its make that one as null.
How to take the old audio file name if people will not update the audio(recording)
audioactivity.java
private void saveState() {
String audioname = et1.getText().toString();
String audiofilename = gfilename;
String audiocount = et2.getText().toString();
if(audiocount.equals("")){
audiocount ="1";
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String audiodate = sdf.format(new Date());
if (mRowId == null || mRowId.longValue() == 0)
{
long id = mDbHelper.createProject4(audioname, audiofilename, audiocount, audiodate);
if (id > 0) {
mRowId = id;
}
} else {
audiofilename=gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
}
public View.OnClickListener btnClick = new View.OnClickListener()
{
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:{
AppLog.logString("Start Recording");
enableButtons(true);
startRecording();
break;
}
case R.id.btnstop:{
AppLog.logString("Start Recording");
enableButtons(false);
stopRecording();
break;
}
}
}
};
public MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
AppLog.logString("Error: " + what + ", " + extra);
}
};
public MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
AppLog.logString("Warning: " + what + ", " + extra);
}
};
public void setButtonHandlers() {
((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnstop)).setOnClickListener(btnClick);
}
public void enableButton(int id,boolean isEnable){
((Button)findViewById(id)).setEnabled(isEnable);
}
public void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart,!isRecording);
enableButton(R.id.btnstop,isRecording);
}
#SuppressLint("NewApi")
private void startRecording(){
//displayFormatDialog();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = {"MPEG 4", "3GPP", "AMR"};
builder.setTitle(getString(R.string.choose_format_title))
.setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
dialog.dismiss();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
//recorder.setOnErrorListener(errorListener);
//recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.show();
}
private void stopRecording(){
if(null != recorder)
{
//mDbHelper.updateProject4FileName(mRowId, gfilename);
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
else
{
recorder.stop();
recorder.release();
}
}
public String getFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
gfilename = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
return (gfilename);
}
#Override
public void onCompletion (MediaPlayer arg0)
{
}
public void playSong(String gfilename){
// Play song
try
{
mp.reset();
mp.setDataSource(gfilename);
mp.prepare();
mp.start();
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I checked in debugging also,if we didnt update the recording its taking that place as null only.
Here i attached my db updated code also
public boolean updateProject4(long _id, String audioname, String audiofilename,String audiocount,String audiodate) {
ContentValues args = new ContentValues();
args.put(CATEGORY_COLUMN_AUDIONAME, audioname );
args.put(CATEGORY_COLUMN_AUDIOFILENAME, audiofilename );
args.put(CATEGORY_COLUMN_AUDIOCOUNT, audiocount );
args.put(CATEGORY_COLUMN_AUDIODATE, audiodate );
return mDb.update(DATABASE_TABLE_AUDIOPRAYER, args, CATEGORY_COLUMN_ID4 + "=" + _id, null) > 0;
}
Actually i got the way for my question.
Want to fetchfile from db if my filename becomes null while updating
private void saveState() {
String audioname = et1.getText().toString();
String audiofilename = gfilename;
String audiocount = et2.getText().toString();
if(audiocount.equals("")){
audiocount ="1";
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String audiodate = sdf.format(new Date());
//String reqname= spin.getSelectedItem().toString();
//Log.i(" save state mathod "," values are "+title+Desc+Body+reqname);
if (mRowId == null || mRowId.longValue() == 0)
{
long id = mDbHelper.createProject4(audioname, audiofilename, audiocount, audiodate);
if (id > 0) {
mRowId = id;
}
} else {
if(audiofilename.equals("")){
Cursor filename = mDbHelper.fetchProject4FileName(mRowId, audiofilename);
startManagingCursor(filename);
gfilename =filename.getString(filename.getColumnIndexOrThrow(GinfyDbAdapter.CATEGORY_COLUMN_AUDIOFILENAME));
//mDbHelper.fetchProject4FileName(mRowId, audiofilename);
audiofilename = gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
else
{
audiofilename = gfilename;
mDbHelper.updateProject4(mRowId, audioname, audiofilename, audiocount,audiodate);
}
}
we have to fetch the filename from db and check whether our audiofilename is null means,we have to set the older filename