Show ProgressDialog while image downloading - android

my application have a download feature Take some time to download image for that i'm trying to add ProgressDialog while image downloading. ProgressDialog It never appears please help me
this my code for save image:
private String saveImage(Bitmap image) {
ProgressDialog pd = new ProgressDialog(Pop.this);
pd.setMessage("Downloading ...");
pd.show();
String savedImagePath = null;
String imageFileName = "vapor"+System.currentTimeMillis()+ ".png";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/vaporwave");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
Toast.makeText(Pop.this, "IMAGE SAVED", Toast.LENGTH_LONG).show();
pd.dismiss();
}
return savedImagePath;
}

you should use some background task like AsyncTask, you should not do complex task on your UI thread.(otherwise your UI will luck until task done , so your progressDialog never show)
you can read about AsyncTask Here
for example in async :
1) show your progressDialog on onPreExecute
2) and dismiss it in onPostExecute
3) and do your work(saving image) in doInBackground (return type in this method will pass to onPostExecute)
public class saveImage extends AsyncTask<Bitmap,Void,String>{
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(Pop.this);
pd.setMessage("Downloading ...");
pd.show();
}
#Override
protected String doInBackground(Bitmap... params) {
Bitmap image = params[0];
String savedImagePath = null;
String imageFileName = "vapor"+System.currentTimeMillis()+ ".png";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/vaporwave");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
Toast.makeText(Pop.this, "IMAGE SAVED", Toast.LENGTH_LONG).show();
pd.dismiss();
}
return savedImagePath;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//s is your savedImagePath
pd.dismiss();
}
}
you can call this task like this:
new saveImage().execute(yourBitmap);

Related

Save Image in External Storage By using Picasso from Url , how to download image and show it in imageview

Please Use This Code for save image in your external Storage by using Url
//Please Put your Image url In $url
Picasso.get().load($url).into(object : Target{
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
}
override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
try {
val root = Environment.getExternalStorageDirectory().toString()
var myDir = File("$root")
if (!myDir.exists()) {
myDir.mkdirs()
}
val name = Date().toString() + ".jpg"
myDir = File(myDir, name)
val out = FileOutputStream(myDir)
bitmap?.compress(Bitmap.CompressFormat.JPEG, 90, out)
out.flush()
out.close()
} catch (e: Exception) {
// some action
}
}
})
and Image will be saved in sdcard.
1- add to AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2- Use this method to download image using Picasso from Url:
private static void SaveImage(final Context context, final String MyUrl){
final ProgressDialog progress = new ProgressDialog(context);
class SaveThisImage extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setTitle("Processing");
progress.setMessage("Please Wait...");
progress.setCancelable(false);
progress.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try{
File sdCard = Environment.getExternalStorageDirectory();
#SuppressLint("DefaultLocale") String fileName = String.format("%d.jpg", System.currentTimeMillis());
File dir = new File(sdCard.getAbsolutePath() + "/savedImageName");
dir.mkdirs();
final File myImageFile = new File(dir, fileName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
Bitmap bitmap = Picasso.get().load(MyUrl).get();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(myImageFile));
context.sendBroadcast(intent);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}catch (Exception e){
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(progress.isShowing()){
progress.dismiss();
}
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
}
SaveThisImage shareimg = new SaveThisImage();
shareimg.execute();
}
3- how to use, just call:
SaveImage(context, "Image URL");
Use this method to download image in internal memory
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
File destination = new File(getActivity().getCacheDir(),
"profile" + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
selectedFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And call this method like this
Picasso.get().load(response.body()?.url).into(object : Target{
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
}
override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {
}
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
new DownloadImage().execute("url_here);
}
})
Note:- Copy this code and paste it , Kotlin converter will
automatically convert it to Kotlin

How i can add a progress notification in my code for download

I have created an app in this app i have display the pdf files and when user click then file should be downloaded.I have write a code for download andt i am only able to show the ProgressDialog for downloading but i want progress notification with cancel button. I don't known how i can do that.
Here is my download code.
public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public DownloadTask(Context context, String downloadUrl, String downloadFileName) {
this.context = context;
this.downloadUrl = downloadUrl;
this.downloadFileName =downloadFileName;
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
Toast.makeText(context, "Downloaded Successfully", Toast.LENGTH_SHORT).show();
File file = new File(Environment.getExternalStorageDirectory() + "/"
+ "android"+"/"+"data"+"/"+"FolderName"+"/"+ downloadFileName);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
if (uri.toString().contains(".pdf")) {
intent.setDataAndType(uri, "application/pdf");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed");
}
} catch (Exception e) {
e.printStackTrace();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();//connect the URL Connection
if (c.getResponseCode() !=
HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(
Environment.getExternalStorageDirectory() + "/"
+ "android"+"/"+"data"+"/"+"Folder name");
} else
Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
fos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
In the doInBackground method of your downloadingTask, regularly call publishProgress to transmit the progress to your UI, then update your progress bar in it's onProgressUpdate which is executed on the UI thread and can hence a progress bar in a dialog box.

Unable to save image from Json response using Volley

Save Image from ImageView in android Not Working. Image loading By Volley from JSON . I want to save that image in Gallery but on some devices this code not working.
BitmapDrawable draw = (BitmapDrawable) thumbnail.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File dir = new File(Environment.getExternalStorageDirectory() + "");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(JobsDetail.this, "Download Successfully", Toas.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);
Simply use this to download directly from Image Url
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
progressBar.setVisibility(View.GONE);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
LicenseFrontFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Set the bitmap into ImageView
//image.setImageBitmap(result);
// Close progressdialog
}
To use , call this way
new DownloadImage().execute(image_url);
Add write permissions in manifest also
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And runtime persmissions for Marshmallow or above devices
Create a class SaveImageHelper code is below
public class SaveImageHelper implements Target {
private Context context;
private WeakReference<AlertDialog> mDialog;
private WeakReference<ContentResolver> contentResolverWeakReference;
private String name;
private String desc;
public SaveImageHelper(Context context,AlertDialog alertDialog, ContentResolver contentResolver, String name, String desc) {
this.context = context;
this.mDialog = new WeakReference<AlertDialog>(alertDialog);
this.contentResolverWeakReference = new WeakReference<ContentResolver>(contentResolver);
this.name = name;
this.desc = desc;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog dialog = mDialog.get();
if(r != null)
MediaStore.Images.Media.insertImage(r,bitmap,name,desc);
dialog.dismiss();
Toast.makeText(context, "Image Download Successfully...", Toast.LENGTH_SHORT).show();
//Open Gallery After Download
//Intent intent = new Intent();
//intent.setType("image/*");
// intent.setAction(Intent.ACTION_GET_CONTENT);
// context.startActivity(Intent.createChooser(intent,"SELECT PICTURE"));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
and Use it in another class / Activity by button click
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ActivityCompat.checkSelfPermission(JobsDetail.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(JobsDetail.this, "You Should Grant Permission..", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_REQUEST_CODE);
}
return;
}
else{
AlertDialog dialog = new SpotsDialog(JobsDetail.this);
dialog.show();
dialog.setMessage("Downloading....");
String filename = UUID.randomUUID().toString()+".jpg";
Picasso.with(getBaseContext())
.load(imageUrl)
.into(new SaveImageHelper(getBaseContext(),
dialog, getApplicationContext().getContentResolver(),
filename,"Image Descp"));
}
Also set Permission in oncreate to access files and images in device
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_REQUEST_CODE);
}

How to Convert Image URL to File in android

I faced this problem in my project, and I need to pass image as a file Image's get from URL(Example: Image URL this url needs to convert into a file without download a image), mean image URL need to convert a file then it passed to the server.Analysized but I'm not getting any answer,
{
"templateName": "e. Before-After(1).png",
"templateId": "",
"templateUrl": "https://cnet4.cbsistatic.com/img/QJcTT2ab-sYWwOGrxJc0MXSt3UI=/2011/10/27/a66dfbb7-fdc7-11e2-8c7c-d4ae52e62bcc/android-wallpaper5_2560x1600_1.jpg"
}
From this response "templateUrl" need to convert file
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
File file = CommonUtils.getDownloadFile(placeHolder);
if (file == null)
return;
try {
FileOutputStream out = new FileOutputStream(file);
result.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
// here you can get file in "file" variable.
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Function for create a file where file download.
public static File getDownloadFile(String placeHolder) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/proManager");
if (!myDir.exists()) {
if (!myDir.mkdirs()) {
return null;
}
}
String fname = FILE_NAME_PRE_TEXT + placeHolder + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
return file;
}
How to Use this class
ImageDownloaderTask imageDownloaderTask = new ImageDownloaderTask();
imageDownloaderTask.execute(url);

Use MediaScannerConnection scanFile To Scan Downloaded Image File

I am working on an app in which I save image(s) to a directory but the Images wont show up in gallery until I restart the phone.
Here's My Code Snippet
public class SaveTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public SaveTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/mydownloaddir/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Toast.makeText(SlideImageActivity.this, "Image Saved Succesfully to Folder 'mydownloaddir'", Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
What code should I use next to make the Images showup in gallery using medisscanner
I got something like this on here But unable to use it properly:
MediaScannerConnection.scanFile(ApplicationContext.context, new String[] { imageFile.getPath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i(TAG, "Scanned " + path);
}
});
Please Help
Use
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
//but it only works on API <19
Second Method
private void scanFile(String path) {
MediaScannerConnection.scanFile(MainActivity.this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
Call it like
scanFile(yourFile.getAbsolutePath());
Also see this Answer

Categories

Resources