Ho anche affrontato lo stesso problema e risolto il mio con questo. Prova questo
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap>
{
@Override
protected Bitmap doInBackground(String... arg0)
{
downloadImagesToSdCard("","");
return null;
}
private void downloadImagesToSdCard(String downloadUrl,String imageName)
{
try
{
URL url = new URL(img_URL);
/* making a directory in sdcard */
String sdCard=Environment.getExternalStorageDirectory().toString();
File myDir = new File(sdCard,"test.jpg");
/* if specified not exist create new */
if(!myDir.exists())
{
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File (myDir, fname);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection)ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
inputStream = httpConn.getInputStream();
}
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) >0)
{
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
}
catch(IOException io)
{
io.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Dichiarare le operazioni di rete in AsyncTask in quanto verrà caricato come attività in background. Non caricare le operazioni di rete sul thread principale. Dopo questo sia in tasto click o nel contenuto delle chiamate vista questa classe come
new ImageDownloadAndSave().execute("");
E non dimenticate di aggiungere l'autorizzazione nework come:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Spero che questo possa aiutare qualcuno :-)
E quale errore si ottiene? – Cristian
Hai provato a caricare un'immagine esistente utilizzando createFromPath? – Ankit
È in un'istruzione try-catch, impostandolo su null se fallisce. Non ho provato un'altra immagine. Sto usando l'emulatore – Jamie