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 M
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 {
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
}
}}