问题
I have made an app which shows a list of image. But before, I downloaded all the images to the sdcard, and I show a progress dialog with the number of downloaded files. I'm thinking to optimise the process using Picasso because of many images to download. So no progress dialog. With Picasso, I would like to save the image in my app directory (as a normal downloaded file) before it is shown in the ImageView. I thought to use this code :
Picasso picassoInstance = new Picasso.Builder(context)
.downloader(new CustomDownloader(context, destination))
.build();
The CustomDownloader :
public class CustomDownloader extends OkHttpDownloader {
private File destination;
public CustomDownloader(Context context, File destination){
super(context);
this.destination = destination;
}
@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
Response response = super.load(uri, networkPolicy);
FileOutputStream fileOutput = new FileOutputStream(destination);
InputStream inputStream = response.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
return response;
}
}
And finally, I use this statement to load the image in the ImageView :
picassoInstance.load(item.getItem().getPath()).resize(width,0).into(imageView);
Am I correct to use this kind of implementation ? Or do you can provide another way ?
EDIT 1 : I use the code above but the image is not shown in the ImageView, even if I see the images downloaded in the SDCARD.
EDIT 2 : With this code, using new Thread :
@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
Response response = super.load(uri, networkPolicy);
new Thread(new Runnable() {
try {
FileOutputStream fileOutput = new FileOutputStream(destination);
InputStream inputStream = response.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch(IOException e){
e.printStackTrace();
}
}).start();
return response;
}
I got an java.lang.ArrayIndexOutOfBoundsException: src.length=2048 srcPos=2048 dst.length=1024 dstPos=0 length=1024
in this line while ((bufferLength = inputStream.read(buffer)) > 0)
回答1:
using picasso to load image is good, there are a serveral advantage like:
- Memory and disk caching of uncompress imagery, post-processing
- An automatically created singleton image downloader
- Multiple downloads at one time
But you can try to use Volley, for me this is the best! About your problem, try to show item.getItem().getPath() in logcat and look if the path is ok or not, the path should be the path in sdcard if you want to use the image in sdcard
来源:https://stackoverflow.com/questions/37066637/android-picasso-save-image-locally-before-viewing-it-in-imageview