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
Related
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.
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);
How do you implement Progress Download Dialog based on the codes below? My codes downloads images from a specific URL then it saves the image file into SD Card and set the image as wallpaper. I want to show a Progress Download Dialog when the user touches the options menu button setwallpaper().
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.set_wallpaper:
SetWallpaper(image_url);
return true;
default:
return false;
}
}
public void SetWallpaper(String image_url)
{
URL myFileUrl = null;
try
{
myFileUrl = new URL(image_url);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Bitmap bmImg = null;
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
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() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
WallpaperManager wpm = WallpaperManager.getInstance(getBaseContext());
wpm.setBitmap(bmImg);
}
catch (Exception e){
e.printStackTrace();
}
}
My attempt : Caught Exception . Please refer below codes
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_THUMB_URL = "thumb_url";
ProgressBar progressbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
ImageView image = (ImageView) findViewById(R.id.single_image);
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
imgLoader.DisplayImage(image_url, image);
String title = in.getStringExtra(KEY_TITLE);
String artist = in.getStringExtra(KEY_ARTIST);
TextView lblName = (TextView) findViewById(R.id.name_title);
TextView lblCost = (TextView) findViewById(R.id.name_artist);
progressbar = (ProgressBar) findViewById(R.id.loadingBar);
lblName.setText(title);
lblCost.setText(artist);
}
public class loadImageTask extends AsyncTask<String, Void, Void>
{
//Drawable imgLoad;
URL myFileUrl = null;
Bitmap bmImg = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
try {
myFileUrl = new URL(image_url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try {
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() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File 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(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(progressbar.isShown())
{
progressbar.setVisibility(View.GONE);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
switch (item.getItemId()) {
case R.id.save_image:
new loadImageTask().execute(image_url);
return true;
default:
return false;
}
Here you can use the AsyncTask for the show the progressbar/dialogbox .
Show the progress bar visible inside the onPreExecute() method. And performs the image loading operations inside the doInBackground() method. Once this operation is done, we will make progress bar invisible and make imageview visible with that loaded image inside the onPostExecute() method.
For more information check this LINK
Try using this
final ProgressDialog dialog = ProgressDialog.show(
YourACtivity.this, "", "Loading...please wait");
new Thread(new Runnable() {
#Override
public void run() {
SetWallpaper(image_url);
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}).start();
}
instead of
SetWallpaper(image_url);
in the onOptionsItemSelected(MenuItem item)
and next use Handlers to handle http://developer.android.com/reference/android/os/Handler.html
My wallpaper manager uses a Async Task to set as wallpaper. But after changing to AsyncTask from non-Async I got the error "The method getBaseContext() is undefined for the type SetWallpaperTask" Please correct my codes. Thank you very much.
Old Non-AsyncTask
public void SetWallpaper(String image_url)
{
URL myFileUrl = null;
try
{
myFileUrl = new URL(image_url);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Bitmap bmImg = null;
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
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() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
WallpaperManager wpm = WallpaperManager.getInstance(getBaseContext());
wpm.setBitmap(bmImg);
}
catch (Exception e){
e.printStackTrace();
}
}
New AsyncTask
public class SetWallpaperTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
public SetWallpaperTask(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() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File 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
WallpaperManager wpm = WallpaperManager.getInstance(context()); // --The method context() is undefined for the type SetWallpaperTask
wpm.setBitmap(bmImg);
pDialog.dismiss();
}
}
This is because you cannot get a Context inside an AsyncTask using getBaseContext().
I see that you're already receiving a Context in your constructor and storing it in the class variable context. So you can simply change
WallpaperManager wpm = WallpaperManager.getInstance(getBaseContext());
to
WallpaperManager wpm = WallpaperManager.getInstance(context);
Pass your activity context to this AsynTask, and use that context in your onPostExecute().
I need my android app to make request to url to download an image from this url
so I have built this class to help me, BUT it didn't work ???
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try{
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
// Open a connection to that URL.
URLConnection ucon = url.openConnection();
// Define InputStreams to read from the URLConnection.
is = ucon.getInputStream();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(
null,
new String[] { file.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
}
);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And I have, in the Activity class on onclick(), this function:
public void down(View v) {
// ImageManager ob=new ImageManager();
// ob.DownloadFromUrl("");
new MyAsnyc().execute();
}
Although I have written the permissions in the manfiest.xml
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try this
public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;
protected void doInBackground() throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
is = ucon.getInputStream();
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
try {
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(null,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Define these on the top side
Button BtnDownload;
DownloadManager downloadManager;
After, You should write on create inside :
BtnDownload = (Button)findViewById(R.id.button1);
Later, You should write to the button's click event
downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("your url");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
Finally, you need to add this onto the application tag to the manifest.xml :
<uses-permission android:name="android.permission.INTERNET"/>
new DownloadImageFromUrlTask().execute(imagePath);
//add glide dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
public class DownloadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
String downloadPath = "";
#Override
protected Bitmap doInBackground(String... args) {
try {
downloadPath = args[0];
return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
String root_Path = Environment.getExternalStorageDirectory().toString();
String saveImagePath = root_Path + "/" + photoFileName;
saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
loadImageWithGlide(MainActivity.this, myImageView, saveImagePath);
} else {
myImageView.setImageResource(R.drawable.default_photo);
}
}
}
public static Boolean saveBitmapToJPEGFile(Context ctx, Bitmap theTempBitmap, File theTargetFile, int i) {
Boolean result = true;
if (theTempBitmap != null) {
FileOutputStream out = null;
try {
out = new FileOutputStream(theTargetFile);
theTempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out); //kdfsJpegCompressionRatio
} catch (FileNotFoundException e) {
result = false;
e.printStackTrace();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
result = false;
}
return result;
}
public static void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
Glide.with(theCtx)
.load(theUrl)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(theImageView);
}
The problem with your code is you have not read the InputStream.
You should try this
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
and make the Asynctask return type as Bitmap.
Or,
As you have used that is in postExecute() your doInBackground() should return that InputStream object is. But you are returning void.
Okey.Try this edited Asynctask.
private class MyAsnyc extends AsyncTask <Void,Void,File> {
File file;
#Override
protected File doInBackground( Void... params ) {
InputStream is = null;
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
file = new File( path , "Demo Picture.jpg" ) ;
try { // Make sure the Pictures directory exists.path.mkdirs() ; URL url = new URL ( "http: / /androidsaveitem .appspot.com/download.jpg") ; URLConnection ucon = url.openConnection ( ) ;
path.mkdirs();
OutputStream os = new FileOutputStream(file) ;
byte [ ] data = new byte [ is.available ( ) ] ;
is.read ( data ) ; os.write (data );is.close ( ) ; os.close ( ) ;
return file;
}
catch (Exception e){
Log .d ( "ImageManager " , " Error: " + e ) ;
}
return null;
}
protected void onPostExecute (File file) {
try{
MediaScannerConnection.scanFile( null , new String [] {file.toString( ) } , null , new MediaScannerConnection.OnScanCompletedListener ( ) { public void onScanCompleted (String path, Uri uri) {
Log.i ( " External Storage" , " Scanned " + path + " : " ) ; Log.i ( " E x t e r n a l S t o r a g e " , " - > u r i = " + uri ) ; } } ) ;
}catch (Exception e) {
// TODO: handle exception
}
}}